Magento 2 standardy kodowania
Tworząc kod, dobrze by było trzymać się pewnych standardów, aby ułatwić pracę innym programistom. Standardy kodowania określają, w jaki sposób możemy ulepszyć czytelność i jakoś naszego kodu. Nabywanie dobrych nawyków staje się szczególnie ważne przy pracy na dużych projektach, taki jak Magento 2 (Adobe Commerce i Magento Open Source). Dla Magento 2 standardy kodowania nie służą tylko do poprawienia czytelności i jakości kodu. Bardzo ważne jest, aby dokonać sprawdzenia modułu, jeśli jesteśmy zainteresowani wysłaniem go do Commerce Marketplace.
Co to jest Magento Coding Standard?
Magento 2 standardy kodowania to zestaw reguł, które sprawdzają kod pod kątem oficjalnych standardów wymaganych przez Magento. Trzymając się standardów, redukujemy ryzyko problemów wydajnościowych, takich jak przeładowanie, nadpisywanie i tak dalej.
Narzędzie Magento 2 Coding Standard sprawdza:
- Zgodność z PSR-1 i PSR-2,
- Niebezpieczne funkcje,
- Nieeskajpowane dane wyjściowe,
- funkcje PHP oznaczone jako deprecated,
- Konwencję nazewniczą,
- Zmienne superglobalne PHP,
- Puste bloki kodu,
- Niewłaściwą obsługę wyjątków,
- Bezpośrednie zapytania SQL (tak zwane raw SQL),
- oraz wiele innych problemów z kodem specyficznych dla PHP i Magento 2.
Sprawdzenie kodu za pomocą Magento Coding Standard
Magento rekomenduje nam użycie PHP_CodeSniffer do sprawdzania jakości kodu w modułach. Jest on domyślnie zainstalowany w Magento 2.
Sprawdzenie instalacji narzędzia Magento Coding Standard wykonamy za pomocą komendy:
1 |
vendor/bin/phpcs -i |
Powyższe polecenie powinno zwrócić nam listę zainstalowanych narzędzie do sprawdzania standardów kodowania. Wśród nich znajdziemy:
- MySource,
- PEAR,
- PSR1,
- PSR2,
- PSR12,
- Squiz,
- Zend,
- Magento2,
- Magento2Framework,
- PHPCompatibility.
Przy generowaniu raportu możemy określić poziom, tak zwane severity, sprawdzenia kodu:
Typ | Severity | Opis |
Error | 10 | Krytyczne problemy z kodem, które wskazują na błąd lub lukę w zabezpieczeniach. |
Warning | 9 | Możliwe problemy z bezpieczeństwem, które mogą powodować błędy. |
Warning | 8 | Specyficzne dla Magento problemy z kodem i nieprawidłowości w designie. |
Warning | 7 | Ogólne kwestie dotyczące kodu. |
Warning | 6 | Problemy związane ze stylem kodu. |
Warning | 5 | Problemy z formatowaniem i komentowaniem PHPDoc. |
Przyjrzyjmy się opcjom, które są dostępne przez polecenie phpcs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
app@580570127a76:~/html$ vendor/bin/phpcs --help Usage: phpcs [-nwlsaepqvi] [-d key[=value]] [--colors] [--no-colors] [--cache[=<cacheFile>]] [--no-cache] [--tab-width=<tabWidth>] [--report=<report>] [--report-file=<reportFile>] [--report-<report>=<reportFile>] [--report-width=<reportWidth>] [--basepath=<basepath>] [--bootstrap=<bootstrap>] [--severity=<severity>] [--error-severity=<severity>] [--warning-severity=<severity>] [--runtime-set key value] [--config-set key value] [--config-delete key] [--config-show] [--standard=<standard>] [--sniffs=<sniffs>] [--exclude=<sniffs>] [--encoding=<encoding>] [--parallel=<processes>] [--generator=<generator>] [--extensions=<extensions>] [--ignore=<patterns>] [--ignore-annotations] [--stdin-path=<stdinPath>] [--file-list=<fileList>] [--filter=<filter>] <file> - ... - Check STDIN instead of local files and directories -n Do not print warnings (shortcut for --warning-severity=0) -w Print both warnings and errors (this is the default) -l Local directory only, no recursion -s Show sniff codes in all reports -a Run interactively -e Explain a standard by showing the sniffs it includes -p Show progress of the run -q Quiet mode; disables progress and verbose output -m Stop error messages from being recorded (saves a lot of memory, but stops many reports from being used) -v Print processed files -vv Print ruleset and token output -vvv Print sniff processing information -i Show a list of installed coding standards -d Set the [key] php.ini value to [value] or [true] if value is omitted --help Print this help message --version Print version information --colors Use colors in output --no-colors Do not use colors in output (this is the default) --cache Cache results between runs --no-cache Do not cache results between runs (this is the default) --ignore-annotations Ignore all phpcs: annotations in code comments <cacheFile> Use a specific file for caching (uses a temporary file by default) <basepath> A path to strip from the front of file paths inside reports <bootstrap> A comma separated list of files to run before processing begins <encoding> The encoding of the files being checked (default is utf-8) <extensions> A comma separated list of file extensions to check The type of the file can be specified using: ext/type e.g., module/php,es/js <file> One or more files and/or directories to check <fileList> A file containing a list of files and/or directories to check (one per line) <filter> Use either the "gitmodified" or "gitstaged" filter, or specify the path to a custom filter class <generator> Use either the "HTML", "Markdown" or "Text" generator (forces documentation generation instead of checking) <patterns> A comma separated list of patterns to ignore files and directories <processes> How many files should be checked simultaneously (default is 1) <report> Print either the "full", "xml", "checkstyle", "csv" "json", "junit", "emacs", "source", "summary", "diff" "svnblame", "gitblame", "hgblame" or "notifysend" report, or specify the path to a custom report class (the "full" report is printed by default) <reportFile> Write the report to the specified file path <reportWidth> How many columns wide screen reports should be printed or set to "auto" to use current screen width, where supported <severity> The minimum severity required to display an error or warning <sniffs> A comma separated list of sniff codes to include or exclude from checking (all sniffs must be part of the specified standard) <standard> The name or path of the coding standard to use <stdinPath> If processing STDIN, the file path that STDIN will be processed as <tabWidth> The number of spaces each tab represents |
Do sprawdzenia modułu będą nas interesowały, przede wszystkim, opcje:
- standard — za wartość podajemy nazwę jednego z zainstalowanych standardów, na przykład: Magento2.
- severity — określenie poziomu wyszukiwania błędów, wartość od 5 do 10.
- ścieżka do pliku lub modułu do sprawdzenia.
Do sprawdzenia standardu Magento2 i modułu, na przykład Anna_GuestbookAdminUI wykonamy polecenie:
1 |
vendor/bin/phpcs --standard=Magento2 app/code/Anna/GuestbookAdminUI --severity=7 |
Przykłady, znaleziony błąd:
1 2 3 4 5 6 7 8 |
FILE: /var/www/html/app/code/Anna/GuestbookAdminUI/Block/Adminhtml/Guestbook/Edit/GenericButton.php --------------------------------------------------------------------------------------------------- FOUND 0 ERRORS AND 1 WARNING AFFECTING 1 LINE --------------------------------------------------------------------------------------------------- 37 | WARNING | Empty CATCH statement detected --------------------------------------------------------------------------------------------------- Time: 1.21 secs; Memory: 18MB |
Zmniejszenie wartości dla opcji severity pokaże więcej błędów, na przykład:
1 2 3 4 5 6 7 8 9 |
FILE: /var/www/html/app/code/Anna/GuestbookAdminUI/registration.php --------------------------------------------------------------------------------------- FOUND 0 ERRORS AND 2 WARNINGS AFFECTING 2 LINES --------------------------------------------------------------------------------------- 5 | WARNING | [x] Only one argument is allowed per line in a multi-line function call 6 | WARNING | [x] Expected 1 blank line at end of file; 2 found --------------------------------------------------------------------------------------- PHPCBF CAN FIX THE 2 MARKED SNIFF VIOLATIONS AUTOMATICALLY --------------------------------------------------------------------------------------- |
Niektóre rodzaje błędów (jak ostatni przykład) możemy naprawić automatycznie, z pomocą przychodzi nam polecenie phpcbf:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
app@580570127a76:~/html$ vendor/bin/phpcbf --help Usage: phpcbf [-nwli] [-d key[=value]] [--ignore-annotations] [--bootstrap=<bootstrap>] [--standard=<standard>] [--sniffs=<sniffs>] [--exclude=<sniffs>] [--suffix=<suffix>] [--severity=<severity>] [--error-severity=<severity>] [--warning-severity=<severity>] [--tab-width=<tabWidth>] [--encoding=<encoding>] [--parallel=<processes>] [--basepath=<basepath>] [--extensions=<extensions>] [--ignore=<patterns>] [--stdin-path=<stdinPath>] [--file-list=<fileList>] [--filter=<filter>] <file> - ... - Fix STDIN instead of local files and directories -n Do not fix warnings (shortcut for --warning-severity=0) -w Fix both warnings and errors (on by default) -l Local directory only, no recursion -p Show progress of the run -q Quiet mode; disables progress and verbose output -v Print processed files -vv Print ruleset and token output -vvv Print sniff processing information -i Show a list of installed coding standards -d Set the [key] php.ini value to [value] or [true] if value is omitted --help Print this help message --version Print version information --ignore-annotations Ignore all phpcs: annotations in code comments <basepath> A path to strip from the front of file paths inside reports <bootstrap> A comma separated list of files to run before processing begins <encoding> The encoding of the files being fixed (default is utf-8) <extensions> A comma separated list of file extensions to fix The type of the file can be specified using: ext/type e.g., module/php,es/js <file> One or more files and/or directories to fix <fileList> A file containing a list of files and/or directories to fix (one per line) <filter> Use either the "gitmodified" or "gitstaged" filter, or specify the path to a custom filter class <patterns> A comma separated list of patterns to ignore files and directories <processes> How many files should be fixed simultaneously (default is 1) <severity> The minimum severity required to fix an error or warning <sniffs> A comma separated list of sniff codes to include or exclude from fixing (all sniffs must be part of the specified standard) <standard> The name or path of the coding standard to use <stdinPath> If processing STDIN, the file path that STDIN will be processed as <suffix> Write modified files to a filename using this suffix ("diff" and "patch" are not used in this mode) <tabWidth> The number of spaces each tab represents |
Jak widzimy, polecenie posiada podobne opcje co narzędzie sprawdzające jakoś kodu.
Automatyczne naprawienie określonych błędów (i nie niżej niż poziom 6), dokonamy za pomocą poniższego polecenia:
1 |
vendor/bin/phpcbf --standard=Magento2 app/code/Anna/GuestbookAdminUI --severity=6 |
W efekcie dostaniemy informację o naprawionych błędach:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
PHPCBF RESULT SUMMARY ----------------------------------------------------------------------------------------------------------------- FILE FIXED REMAINING ----------------------------------------------------------------------------------------------------------------- /var/www/html/app/code/Anna/GuestbookAdminUI/Block/Adminhtml/Guestbook/Edit/DeleteButton.php 2 0 /var/www/html/app/code/Anna/GuestbookAdminUI/Block/Adminhtml/Guestbook/Edit/SaveButton.php 1 0 /var/www/html/app/code/Anna/GuestbookAdminUI/Controller/Adminhtml/Index/Delete.php 2 0 /var/www/html/app/code/Anna/GuestbookAdminUI/registration.php 2 0 ----------------------------------------------------------------------------------------------------------------- A TOTAL OF 7 ERRORS WERE FIXED IN 4 FILES ----------------------------------------------------------------------------------------------------------------- Time: 1.56 secs; Memory: 18MB |
Więcej informacji na temat użycie PHP_CodeSinffera znajdziecie na stronie wiki.
Jeśli chodzi o reguły, jakimi kierują się programiści core Magento przy robieniu code review, znajdziecie je spisane tutaj.