Magento 1.x Coding Standard

Overview

Magento Extension Quality Program Coding Standard

⚠️ Versions 3.0.0 and above of the MEQP Coding Standard are for Magento 1.x code only.

To check Magento 2.x code use Consolidated Magento Coding Standard.

Build Status

Magento EQP Coding Standard is a set of rules and sniffs for PHP_CodeSniffer tool.

It allows automatically check your code against some of the common Magento and PHP coding issues, like:

  • raw SQL queries;
  • SQL queries inside a loop;
  • direct class instantiation;
  • unnecessary collection loading;
  • excessive code complexity;
  • use of dangerous functions;
  • use of PHP superglobals;
  • code style issues and many others.

Magento Extension Quality Program Coding Standard consists of one ruleset - MEQP1 for Magento 1.x.

Installation

Install all dependencies via Composer:

$ composer create-project --repository=https://repo.magento.com magento/marketplace-eqp magento-coding-standard

You’re required to authenticate; see Get your authentication keys for details.

Usage

$ cd magento-coding-standard

Select the standard to run with PHP_CodeSniffer. To check Magento extension run:

$ vendor/bin/phpcs /path/to/your/extension --standard=MEQP1

By default, PHP_CodeSniffer will check any file it finds with a .inc, .php, .js or .css extension. To check design templates you can specify --extensions=php,phtml option.

To check syntax with specific PHP version set paths to php binary dir:

$ vendor/bin/phpcs --config-set php7.0_path /path/to/your/php7
$ vendor/bin/phpcs --config-set php5.4_path /path/to/your/php5.4

Fixing Errors Automatically

PHP_CodeSniffer offers the PHP Code Beautifier and Fixer (phpcbf) tool. It can be used in place of phpcs to automatically generate and fix all fixable issues. We highly recommend run following command to fix as many sniff violations as possible:

$ vendor/bin/phpcbf /path/to/your/extension --standard=MEQP1

Marketplace Technical Review

To make sure your extension will pass CodeSniffer checks of Magento Marketplace Technical Review, you could run phpcs command with --severity=10 option.

$ vendor/bin/phpcs /path/to/your/extension --standard=MEQP1 --severity=10 --extensions=php,phtml

All severity 10 errors must be fixed in order to successfully pass Level 1 CodeSniffer checks.

Requirements

Notice: PHP and Composer should be accessible globally.

Contribution

Please feel free to contribute new sniffs or any fixes or improvements for the existing ones.

Comments
  • Issue installing marketplace-eqp on Mac os sierra

    Issue installing marketplace-eqp on Mac os sierra

    The "https://repo.magento.com/packages.json" file could not be downloaded: SSL: Connection reset by peer  
    Failed to enable crypto                                                                                   
    failed to open stream: operation failed
    

    Getting this error after attempting to install. I never get prompted for any auth. I've tried setting up an auth.json file, according to the Composer docs, and added the public/secret keys that I set up with my Magento account, but get the same error as without having an auth.json.

    Any tips?

    opened by Banjerr 18
  • PHP Fatal error:  Trait 'MEQP\Utils\Helper' not found

    PHP Fatal error: Trait 'MEQP\Utils\Helper' not found

    We have checked the MEQP1 standard. But throw below mentioned errors,

    PHP Fatal error: Trait 'MEQP\Utils\Helper' not found in /var/www/development/marketplace-eqp-master/MEQP1/Sniffs/Classes/ResourceModelSniff.php on line 21

    My system details. OS - Ubuntu 16.04.3 PHP - 7.0.18

    How to solve this issue.....!

    opened by sankar1061 13
  • Error while using it in PHPStorm

    Error while using it in PHPStorm

    Magento 2.1, version 1.0.2. I can't get it working in PHPStorm.

    Using the path$PROJECT/vendor/magento/marketplace-eqp/MEQP1

    phpcs: PHP Fatal error: Uncaught PHP_CodeSniffer_Exception: Referenced sniff "Generic.Arrays.DisallowShortArraySyntax" does not exist in /vendor/squizlabs/php_codesniffer/CodeSniffer.php:847 Stack trace:
    #0 /vendor/squizlabs/php_codesniffer/CodeSniffer.php(587): PHP_CodeSniffer->_expandRulesetReference(Object(SimpleXMLElement), '/Users/paul/Sit...', 0)
    #1 /vendor/squizlabs/php_codesniffer/CodeSniffer.php(435): PHP_CodeSniffer->processRuleset('/Users/paul/Sit...')
    

    Using the path$PROJECT/vendor/magento/marketplace-eqp/MEQP2

    phpcs: PHP Fatal error: Uncaught PHP_CodeSniffer_Exception: Referenced sniff "MEQP1.CodeAnalysis.EmptyBlock" does not exist in vendor/squizlabs/php_codesniffer/CodeSniffer.php:847 Stack trace:
    #0 vendor/squizlabs/php_codesniffer/CodeSniffer.php(587): PHP_CodeSniffer->_expandRulesetReference(Object(SimpleXMLElement), '/Users/paul/Sit...', 0)
    #1 vendor/squizlabs/php_codesniffer/CodeSniffer.php(435): PHP_CodeSniffer->processRuleset('/Users/paul/Sit...')
    

    Instructions how to integrate with PHPStorm to run besides the default code sniffer.

    Magento 2's default code sniffer is ran from here: $PROJECT/dev/tests/static/testsuite/Magento/Test/Php/_files/phpcs

    Is this code sniffer meant to replace Magento's code sniffer or is it complementary? I understand they both offer a different purpose, but I see a lot of smart checks that are helpful during development.

    opened by paales 11
  • MEQP1 does not working properly

    MEQP1 does not working properly

    We have executed the below command,

    phpcs --standard=MEQP1 module/

    But throw below errors:

    PHP Fatal error: Interface 'PHP_CodeSniffer\Sniffs\Sniff' not found in /var/www/marketplace-eqp-master/MEQP1/Sniffs/Classes/Mysql4Sniff.php on line 15

    How to resolve this issue.

    opened by sankar1061 10
  • Inherited from magento 2 core properties and

    Inherited from magento 2 core properties and "Use of protected class members is discouraged."

    Magento 2 have very much classes with protected class members that should be overridden in extension's child classes. Therefor there is no sense to show this message for inherited from Magento-namespace classes, because developers can't change his access-visibility.

    Therefor it would be great to have some command line option to disable this warning for inherited from magento properties and functions.

    False Positive 
    opened by likemusic 8
  • Current configuration not useful for Marketplace Technical Review

    Current configuration not useful for Marketplace Technical Review

    I don't know if this coding standard was ever intended for it (the naming marketplace-eqp suggests it though), but with the current configuration it is not useful to preview the Magento Marketplace technical review.

    The technical review mostly uses the Code Validation Guidelines with some undocumented additions. The current rulesets for MEQP1 and MEQP2 do not define the severity or change the rules/sniffs that would block the technical review from passing to the error type.

    I guess developers using any kind of CI to automatically perform static code analysis would appreciate to have the possibility to let their builds fail, if they would not pass the Marketplace technical review.

    opened by powli 6
  • Conflictive array syntax in M1 and M2

    Conflictive array syntax in M1 and M2

    The coding standard MEQP1 disallows short array syntax and the MEQP2 disallows long array syntax. While I perfectly understand this decision for the sake of consistency with the core code, it leads to a number of violations when using the shared libraries approach.

    Shared libraries, that is delivering platform specific code to hook into one or the other major Magento version, accompanied by framework independent code (the library) that provides functionality for reuse in both, M1 and M2.

    Magento Shared Libraries Fabian Schmengler / integer_net

    To overcome the current situation where the library cannot comply to the rules of both major versions, I suggest enforcing short array syntax in MEQP2 and accepting both in MEQP1 (i.e. remove the rule in question).

    opened by mam08ixo 6
  • composer require magento/marketplace-eqp

    composer require magento/marketplace-eqp

    After I run composer require magento/marketplace-eqp I get error:

    [InvalidArgumentException]
      Could not find package magento/marketplace-eqp at any version for your mi
      nimum-stability (alpha). Check the package spelling or your minimum-stabi
      lity
    
    opened by serzhik 6
  • Erroneous code sniff

    Erroneous code sniff "The use of public non-interface method in ACTION is discouraged" in a Controller plugin

    Prerequisites

    Marketplace EQP 1.0.5

    Steps to reproduce

    1. Create a plugin on a controller with the path to the plugin involving the substring Controller somewhere.
    2. On the beforeExecute/afterExecute/aroundExecute function, see that you receive the following erroneous code sniff: The use of public non-interface method in ACTION is discouraged. Example: https://www.screencast.com/t/Dcw3DdM0R

    Workaround

    Create the plugin without using the word "Controller" in the file or folder structure.

    Analysis

    Seems to be due to PublicNonInterfaceMethodsSniff::foundInAction looking for the substring "Controller" in the file path to determine if a class is a controller.

    Possible solution

    Possibly also look for the phrase "public function execute(" or something similar to determine if a file is indeed a controller action? And/or check that the file's structure is specifically <module top level folder>/Controller, rather than looking for Controller anywhere?

    Not sure if either of these solutions are possible or desired.

    Enhancement 
    opened by jantzenw 5
  • Change Protector class member detector to private

    Change Protector class member detector to private

    Hello, I found not logic rule. https://github.com/magento/marketplace-eqp/blob/develop/MEQP2/Sniffs/PHP/ProtectedClassMemberSniff.php Comment in line 13 says "Detects possible usage of 'private' scope modifiers.", and whole class detecting 'protected'. To fast fix: change return [T_PROTECTED]; to return [T_PRIVATE]; in line 32. And protected $warningCode = 'FoundProtected'; to protected $warningCode = 'FoundPrivate';

    Same on Russian: Похоже что произошла ошибка, PHPCS с стилем MEQP2 говорит мне что protected переменные не желательны. А судя по комменту в коде детектора, должно искать private, а не protected.

    Fixed file: ProtectedClassMemberSniff.php.txt

    opened by Leonede 5
  • False Positive : Possible slow SQL method

    False Positive : Possible slow SQL method

    I've got an install script that creates a CMS page like this:

    $page = $this->pageFactory->create();
    $page->setIsActive(true);
    $page->setTitle('Error');
    $page->setPageLayout('1column');
    $page->setContentHeading('Something went wrong');
    $page->setContent('<p>It looks like something went wrong while handling your request. More details:</p>');
    $page = $this->pageRepository->save($page);
    

    This triggers the "Possible slow SQL method" sniff because the word "like" is in my query.

    False Positive 
    opened by kanduvisla 4
  • Overcomplicate Date/Time handling. Use Mage::getSingleton('core/date'). is displayed even when using it

    Overcomplicate Date/Time handling. Use Mage::getSingleton('core/date'). is displayed even when using it

    I'm getting the following error even when using Mage::getSingleton('core/date'). image

    Even if I use it directly I also get the error.

    The sniffer Sniffs/Stdlib/DateTimeSniff.php doesn't check if the date method in use belongs to core/date Singleton class.

    opened by r-martins 0
  • On Mac OS 'MEQP\Utils\Helper' not found

    On Mac OS 'MEQP\Utils\Helper' not found

    Fatal error: Trait 'MEQP\Utils\Helper' not found in ~/.composer/vendor/magento-ecg/coding-standard/MEQP1/Sniffs/Classes/ResourceModelSniff.php on line 22.

    Occurs when I run: phpcs --standard=MEQP1 /path-to-magento

    opened by roberto-ebizmarts 3
  • False positives with calling count() inside loop

    False positives with calling count() inside loop

    The loop performance error MEQP1.Performance.Loop.ArraySize should not trigger when the variable that count() is being called on is declared inside that same loop. For example:

    foreach ($productIds as $productId) {
        $images = getImages($productId);
        echo count($images) . "\n";
    }
    

    In this case, it isn't possible to call count() outside the loop, and therefore the warning is invalid.

    False Positive 
    opened by mwgamble 0
Releases(4.0.0)
  • 4.0.0(Jun 27, 2019)

  • 3.0.0(Jun 19, 2019)

  • 2.0.1(Jan 16, 2019)

  • 2.0.0(Dec 4, 2018)

    • 🥇 Added PHP_CodeSniffer 3.* compatibility #60 -> #70
    • Added package type "phpcodesniffer-standard" -> #95
    • Fixed issue with not resolvable multi-line function parameters Generic.Functions.OpeningFunctionBraceBsdAllman.BraceOnSameLine #46 -> #52
    • Fixed false-positive findings in MEQP1.Classes.ObjectInstantiation sniff #47 -> #53
    • Improved MEQP1.Templates.XssTemplate #48 -> #54
    • Excluded phtml files from certain rules #57 -> #58
    • Fixed Notice: Undefined index in MEQP1.Security.DiscouragedFunction #63 -> #68
    • Set extensions list to be checked by default in the ruleset -> #80
    • Made exclude pattern for lib folders relative -> #81
    • Added default configuration documentation -> #82
    • Added explanatory comment to MEQP2.Classes.MutableObjects #35 -> #85
    • Add new escaping methods from Magento 2.2 to MEQP2.Templates.XssTemplate sniff whitelist -> #89
    • Fixed possible endless loop in MEQP2.Classes.ObjectInstantiation #88 and MEQP2.Classes. PublicClassMembers #96
    • Reduced false-positive findings in MEQP2.Classes. PublicClassMembers sniff #51 #76 -> #97
    • Changed the severity from 10 to 8 for Generic.Arrays.DisallowShortArraySyntax for M1 -> #98 #100
    Source code(tar.gz)
    Source code(zip)
  • 1.0.5(Apr 11, 2017)

    • Added exclusion for methods which name contains html in MEQP1.Templates.XssTemplateSniff;
    • Removed PSR1.Classes.ClassDeclaration sniff from MEQP1 ruleset;
    • Added Generic.Files.OneClassPerFile.MultipleFound and Generic.Files.OneInterfacePerFile.MultipleFound error codes with severity 10;
    • Moved phpunit to require-dev section in composer.json file;
    • Changed PHP requirenments to >=5.5.0 in composer.json file.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.4(Oct 25, 2016)

    • Added severities to all sniffs. Now to make sure, your extension will pass CodeSniffer checks on Level 1 of Magento Marketplace Technical Review, you could run phpcs command with --severity=10 option;
    • New NameResolutionSniff detects literal namespace;
    • New PublicNonInterfaceMethodsSniff detects public non-interface methods in actions and observers;
    • New XssTemplateSniff for Magento 1.x detects unescaped output;
    • Improved MageEntitySniff;
    Source code(tar.gz)
    Source code(zip)
  • 1.0.3(Sep 29, 2016)

    Added new sniffs:

    • ArrayCountSniff detects count() method is used to check if array is empty;
    • StrlenSniff detects strlen() method is used to check if string is empty;
    • ObjectManagerSniff detects use of ObjectManager;
    • MutableObjectsSniff detects Request, Session and Cookie objects are requested in constructor.
    Source code(tar.gz)
    Source code(zip)
  • 1.0.2(Jul 19, 2016)

    • Added code to ReservedWords and ThisInTemplate sniffs
    • Fixed code style in ConstantUsage sniff
    • Added 'Test' folder to ignore list for ObjectInstantiation sniff
    • Changed DisallowLongArraySyntax sniff to warning
    • Updated readme
    • Added MageEntity sniff
    • Fixed comment (Detects possible usage of 'protected' scope modifiers)
    Source code(tar.gz)
    Source code(zip)
Magento 1.x Coding Standard

Magento Extension Quality Program Coding Standard ⚠️ Versions 3.0.0 and above of the MEQP Coding Standard are for Magento 1.x code only. To check Mage

Magento 224 Nov 29, 2022
Magento Coding Standard

Magento Coding Standard A set of Magento rules for PHP_CodeSniffer tool. Installation within a Magento 2 site To use within your Magento 2 project you

Magento 290 Dec 31, 2022
Documentation on clean coding and demonstration of studied clean coding principals with PHP.

practice-php-clean-code Documentation on clean coding and demonstration of studied clean coding principals with PHP. The document contained in this re

Ferdous Islam 1 Feb 21, 2022
Easy Coding Standard configurations for Craft CMS projects.

Easy Coding Standard config for Craft CMs This package provides Easy Coding Standard configurations for Craft CMS plugins and projects. In general, we

Craft CMS 10 Dec 18, 2022
A wrapper around symplify/config-transformer used to update recipes and using easy coding standard for generating readable config files.

Symfony Recipes Yaml to PHP Converter This is a wrapper around the symplify/config-transformer used to convert Symfony core recipes which uses .yaml c

Alexander Schranz 3 Nov 24, 2022
A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2

Simple Import / Export tool A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2. Table data

EcomDev B.V. 51 Dec 5, 2022
A tool to automatically fix Twig Coding Standards issues

Twig CS Fixer Installation This standard can be installed with the Composer dependency manager. Add the coding standard as a dependency of your projec

Vincent Langlet 50 Jan 6, 2023
This shell script and PHP file create a browseable HTML site from the Zig standard library source.

Browseable Zig standard library This shell script and PHP file create a browseable HTML site from the Zig standard library source. The idea is to inve

Dave Gauer 3 Mar 20, 2022
Composer installer for PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

Dealerdirect 462 Dec 22, 2022
PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions.

PHPCheckstyle Overview PHPCheckstyle is an open-source tool that helps PHP programmers adhere to certain coding conventions. The tools checks the inpu

PHPCheckstyle 157 Dec 5, 2022
Igbinary is a drop in replacement for the standard php serializer.

igbinary Igbinary is a drop in replacement for the standard php serializer. Instead of the time and space consuming textual representation used by PHP

Igbinary development 727 Dec 21, 2022
A Symfony2 bundle that integrates Select2 as a drop-in replacement for a standard entity field on a Symfony form.

select2entity-bundle Introduction This is a Symfony bundle which enables the popular Select2 component to be used as a drop-in replacement for a stand

Ross Keatinge 214 Nov 21, 2022
This package provides a set of factories to be used with containers using the PSR-11 standard for an easy Doctrine integration in a project

psr-container-doctrine: Doctrine Factories for PSR-11 Containers Doctrine factories for PSR-11 containers. This package provides a set of factories to

Roave, LLC 84 Dec 14, 2022
This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards

PHP_CodeSniffer Standards Composer Installer Plugin This composer installer plugin allows for easy installation of PHP_CodeSniffer coding standards (r

PHPCSStandards 393 Feb 25, 2022
PHP_CodeSniffer tokenizes PHP files and detects violations of a defined set of coding standards.

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.

Squiz Labs 9.9k Jan 5, 2023
This tool can write the monolog standard log directly to clickhouse in real time via the tcp protocol

log2ck This tool can write the monolog standard log directly to clickhouse in real time via the tcp protocol. If you can write regular rules, other st

Hisune 9 Aug 15, 2022
Pattern Lab Standard Edition for Twig

Pattern Lab Standard Edition for Twig The Standard Edition for Twig gives developers and designers a clean and stable base from which to develop a Twi

Pattern Lab 102 Oct 24, 2022