PHP Magic Number Detector

Overview

PHP Magic Number Detector (PHPMND)

Minimum PHP version: 7.1.0 Scrutinizer Code Quality License CI

phpmnd is a tool that aims to help you to detect magic numbers in your PHP code. By default 0 and 1 are not considered to be magic numbers.

What is a magic number?

A magic number is a numeric literal that is not defined as a constant, but which may change at a later stage, and therefore can be hard to update. It's considered a bad programming practice to use numbers directly in any source code without an explanation. In most cases this makes programs harder to read, understand, and maintain.

Consider the following hypothetical code:

class Foo
{
    public function setPassword($password)
    {
         // don't do this
         if (mb_strlen($password) > 7) {
              throw new InvalidArgumentException("password");
         }
    }
}

which should be refactored to:

class Foo
{
    const MAX_PASSWORD_LENGTH = 7; // not const SEVEN = 7 :)

    public function setPassword($password)
    {
         if (mb_strlen($password) > self::MAX_PASSWORD_LENGTH) {
              throw new InvalidArgumentException("password");
         }
    }
}

This clearly improves the code readability and also reduces its maintenance cost.

Of course not every literal number is a magic number.

$is_even = $number % 2 === 0

Surely in this case the number 2 is not a magic number.

My rule of thumb:

If the number came from business specs and is used directly - it's a magic number.

Installation

Locally

You can add this tool as a local, per-project, development dependency to your project by using Composer:

$ composer require --dev povils/phpmnd

Afterwards you can then invoke it using the vendor/bin/phpmnd executable.

Globally

To install it globally simply run:

$ composer global require povils/phpmnd

Afterwards make sure you have the global Composer binaries directory in your PATH. Example for some Unix systems:

$ export PATH="$PATH:$HOME/.composer/vendor/bin"

Usage Example

Demo

demo

Basic usage

$ phpmnd wordpress --ignore-numbers=2,-1 --ignore-funcs=round,sleep --exclude=tests --progress \
--extensions=default_parameter,-return,argument

The --allow-array-mapping option allow keys as strings when using "array" extension.

The --exclude-file option will exclude a file from the code analysis. Multiple values are allowed.

The --exclude-path option will exclude a path, which must be relative to the source, from the code analysis. Multiple values are allowed.

The --exclude option will exclude a directory, which must be relative to the source, from the code analysis. Multiple values are allowed (e.g. --exclude=tests --exclude=examples).

The --extensions option lets you extend the code analysis. The provided extensions must be comma separated.

The --hint option will suggest replacements for magic numbers based on your codebase constants.

The --ignore-funcs option will exclude a list of comma separated functions from the code analysis, when using the "argument" extension. Defaults to intval, floatval, strval.

The --ignore-numbers option will exclude a list of comma separated numbers from the code analysis.

The --ignore-strings option will exclude strings from the code analysis, when using the "strings" option.

The --include-numeric-string option forces numeric strings such as "1234" to also be treated as a number.

The --non-zero-exit-on-violation option will return a non zero exit code, when there are any magic numbers in your codebase.

The --progress option will display a progress bar.

The --strings option will include strings literal search in code analysis.

The --suffixes option will configure a comma separated list of valid source code filename extensions.

The --whitelist option will only process the files listed in the file specified. This is useful for incremental analysis.

The --xml-output option will generate an report in an Xml format to the path specified by the option. By default it analyses conditions, return statements, and switch cases.

Extensions

  • argument
round($number, 4);
  • array
$array = [200, 201];
  • assign
$var = 10;
  • default_parameter
function foo($default = 3);
  • operation
$bar = $foo * 20;
  • property
private $bar = 10;
  • return (default)
return 5;
  • condition (default)
$var < 7;
  • switch_case (default)
case 3;
  • all To include all extensions.

If extensions start with a minus, it means that these will be removed from the code analysis. I would recommend to clean up your code by using the default extension before using any of these extensions.

Ignoring a number from analysis

Sometimes magic numbers are required. For example implementing a known mathematical formula, by default intval, floatval and strval mark a number as not magic.

eg

$percent  = $number / 100;

would show 100 as a magic number

$percent = $number / intval(100);

would mark 100 as not magic.

Contributing

Please see CONTRIBUTING.md for more information.

License

The MIT License (MIT). Please see LICENSE for more information.

Comments
  • Version 3.0 still renders version 2.5

    Version 3.0 still renders version 2.5

    Hello,

    when running version 3.0 of the magic number detection it still runs with this output

    phpmnd version 2.5.0 by Povilas Susinskas
    

    https://github.com/povils/phpmnd/blob/24d250936880ef803ed7a4c4559331e1641ba4e1/src/Console/Application.php#L17

    opened by leonardfischer 8
  • Update to php 7.3 and update dependencies

    Update to php 7.3 and update dependencies

    I'm a great fan of this tool. However, when trying to install alongside other tools such as phpunit version 9, phpmnd cannot be installed because it needs phpunit/php-timer:2.0. Phpunit nowadays uses phpunit/php-timer:3.0. I upgraded to php7.3 as well because new version of used tools have this as a requirement (phpunit v9 and php-timer v3 for example).

    Since this is a backwards incompatible change, a new major version should be released for this. Tests and codestyle are still good.

    Please provide feedback if I have missed anything or did something wrong. I did not see any issues (specifically) for this, so I decided to work on this myself. Please let me know if I overlooked.

    opened by aaajeetee 7
  • query re: compatibility with symfony/console:^5

    query re: compatibility with symfony/console:^5

    I've a general preference for using composer require --dev rather than using global installs/phar builds.

    Are there any plans to nudge up compatibility with symfony/console, i.e. symfony/console:^4.0|^5.0 ?

    opened by SignpostMarv 7
  • Allow multiple files and/or directories

    Allow multiple files and/or directories

    This allows ./bin/phpmnd src/Console src/Extension tests without affecting the old command ./bin/phpmnd src

    My end goal is allowing folders/filenames interchangeably, so that pre-commit hooks can run on changed files only, but I'd like this to be accepted as first step.

    opened by MarkVaughn 7
  • Application Refactoring

    Application Refactoring

    This PR brings a lot of changes to PHPMND.

    • [x] Generators
    • [x] Objects (DetectionResult) instead of plain array
    • [x] Container
    • [x] More tests
    • [x] No BC breaks

    Reducing memory usage and speed up scanning a bit. Real example on my current project: current master:

    Total of Magic Numbers: 17
    Time: 00:06.161, Memory: 32.00 MB
    

    This PR:

    Total of Magic Numbers: 17
    Time: 00:05.373, Memory: 28.00 MB
    
    hacktoberfest-accepted 
    opened by sidz 6
  • Syntax error when using class called `Match` in the code

    Syntax error when using class called `Match` in the code

    Example file:

    <?php
    declare(strict_types=1);
    
    namespace Test;
    
    class Match
    {
        public function compareTo(Match $other)
        {
            // do something
        }
    }
    

    Call:

    phpmnd test.php
    

    Expected result (more or less):

    phpmnd 2.3.0 by Povilas Susinskas
    --------------------------------------------------------------------------------
    Total of Magic Numbers: 0
    Time: 54 ms, Memory: 12.00 MB
    

    Insted it returns:

    phpmnd 2.3.0 by Povilas Susinskas
    Syntax error, unexpected T_MATCH, expecting T_STRING on line 6
    --------------------------------------------------------------------------------
    Total of Magic Numbers: 0
    Time: 65 ms, Memory: 12.00 MB
    

    More info:

    # php -v
    PHP 7.4.11 (cli) (built: Oct 13 2020 10:09:45) ( NTS )
    Copyright (c) The PHP Group
    Zend Engine v3.4.0, Copyright (c) Zend Technologies
        with Zend OPcache v7.4.11, Copyright (c), by Zend Technologies
        with Xdebug v2.9.8, Copyright (c) 2002-2020, by Derick Rethans
        with blackfire v1.42.0~linux-x64-non_zts74, https://blackfire.io, by Blackfire
    
    opened by ksowa 6
  • Update to allow installing with up coming php 8.0 release

    Update to allow installing with up coming php 8.0 release

    Hi

    I'm getting ahead of getting ready to test with PHP 8.0.

    So this is one of the packages that broke for me.

    I've set it, composer, to also support PHP 8.0.

    Unfortunately, it doesn't look like Travis as support for 8.0 testing yet or I couldn't work out the magic string.

    I have put the rules in uncommented.

    I've also removed the 7.4 --prefer-lowest check as PHPUnit 7 breaks with PHP 7.4.

    opened by timhaak 6
  • Support ignore annotations

    Support ignore annotations

    Hey,

    I'm currently running mnd on a larger codebase (~1k classes) and noticed that the tools reports some warnings that I would not consider a problem in the specific context. This clutters the output and prevents a 0 exit code.

    It would be great if we could introduce something like https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#ignoring-parts-of-a-file to mark certain exceptions as "okay".

    Currently, I'd have to ignore the whole file via `--exclude-file=.." - which I'd like to avoid.

    PS: This frequently happens on the null coalesce operator for setting default values. E.g.

    function foo($arg = null){
       $arg = $arg ?? 1000;
    }
    

    Having that operator "removed" from the "conditions" extension (per config?) would also help a lot ;)

    Any thoughts?

    opened by paslandau 6
  • Consider publishing a phar with releases

    Consider publishing a phar with releases

    I'm maintaining a docker image with qa tools which phpmnd is part of.

    I'm trying to limit number of dependencies installed with "composer global require" to prevent conflicts between tools. Having a phar to download would be really helpful.

    enhancement nice to have 
    opened by jakzal 6
  • Exit with an evaluable return code

    Exit with an evaluable return code

    Currently a command run with n magic numbers found evaluates to 0 via echo $?. This should prolly should return a non zero exit code for usage in CI tooling.

    enhancement 
    opened by raphaelstolt 6
  • What is

    What is "12" in Printer\XML ?

    Hi. I have question for this line. https://github.com/povils/phpmnd/blob/8b874f11774157d180ae6b20c339a7a0e934ccf9/src/Printer/Xml.php#L31

    Why 12 added ?

    opened by sasezaki 5
  • How to define the most strict configuration possible for  phpmnd  ?

    How to define the most strict configuration possible for phpmnd ?

    I’m collaborating in a opensource project :

    https://bitbucket.org/AliasAPI/damnp/src/master/etc/phpmnd/run_phpmnd.sh

    And i am finding trouble configuring phpmnd in the most sensitive way possible, so it would detected every generally undesired line of code. If anyone has any tips, it would be very welcome.

    opened by vic131 1
  • Support github action output format

    Support github action output format

    https://docs.github.com/en/actions/learn-github-actions/workflow-commands-for-github-actions#setting-an-error-message

    This will leave comments inline with the offending code, the output option can be used to turn it on, may even detect github by default

    Feature Request 
    opened by exussum12 1
  • Ignore line or array specific key declaration

    Ignore line or array specific key declaration

    Hello,

    First, thanks for the tool!

    I have added it to my development stack, and use it against Drupal contrib modules that I maintain.

    Is there a way to ignore a specific line with a comment? Like PHPStan, PHPCS, etc. do.

    And is there a way to ignore numbers in keyed array for specific keys?

    Because in Drupal, forms are declared with arrays and I think it would be an overburden to have to declare a constant for each weight or size of every element of each form.

    Example of form https://git.drupalcode.org/project/qwantsearch/-/blob/8.x-1.x/src/Form/Settings.php#L124

    Also, there are still procedural parts in Drupal, such as for declaring custom tables https://git.drupalcode.org/project/i18n_sso/-/blob/8.x-1.x/i18n_sso.install#L40. Ok we can create an interface and call it in the procedural parts.

    So would it be possible to have a new option to have a way to ignore array keys:

    #weight
    #size
    

    Thanks for any reply.

    Best regards,

    Feature Request 
    opened by FlorentTorregrosa 7
Releases(v3.0.1)
  • v3.0.1(Aug 19, 2022)

    What's Changed

    • Add symfony/flex to allow-plugins by @sidz in https://github.com/povils/phpmnd/pull/160
    • Update release number by @exussum12 in https://github.com/povils/phpmnd/pull/163

    Full Changelog: https://github.com/povils/phpmnd/compare/v3.0.0...v3.0.1

    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Jul 6, 2022)

    What's Changed

    • Support symfony 6 by @sidz in https://github.com/povils/phpmnd/pull/149
    • PHP 8.1 support by @exussum12 in https://github.com/povils/phpmnd/pull/134
    • Remove --non-zero-exit-on-violation option by @sidz in https://github.com/povils/phpmnd/pull/152
    • Drop php <7.4 support, symfony <4.4, add php 8.1 to pipeline by @sidz in https://github.com/povils/phpmnd/pull/151

    Full Changelog: https://github.com/povils/phpmnd/compare/v2.5.0...v3.0.0

    Source code(tar.gz)
    Source code(zip)
  • v2.5.0(Dec 12, 2021)

    • Update php-parallel-lint/php-console-highlighter to get rid of abandoned dependency
    • Run PHPMND against codebase
    • Improve GitHub Actions pipelines
    Source code(tar.gz)
    Source code(zip)
  • v2.4.0(Feb 27, 2021)

  • v2.3.0(Jul 18, 2020)

  • v2.2.0(Jan 12, 2020)

    • Add default ignore functions (intval, strval and floatval)
    • Fix negative number whitelisting
    • Ignore the negative value if the scalar does not have a value field
    • Allow multiple files and directories
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Jan 27, 2019)

  • v2.0.0(Mar 17, 2018)

    • Update dependencies. Required PHP 7.1
    • Add support for negative numbers.
    • Ignore '0' and '1' by default.
    • Add XML report output
    • Option for allowing array mapping when using array extension
    • Option for including numeric strings
    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(May 16, 2017)

  • v1.1.0(May 15, 2017)

    • Add --non-zero-exit-on-violation option to return non zero exit code when there are magic number in the codebase.
    • Add --hint option suggest replacements for magic numbers.
    • Add more flexibility to extensions. 'all' option and possibility for removal with minus sign.
    • Add --suffixes option.
    • Add PHAR build support with Box.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Apr 27, 2017)

    • Add --strings option to include strings literals in code analysis.
    • Add --ignore-strings option to ignore strings when using strings opton.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Apr 25, 2017)

  • v1.0.1(Apr 21, 2017)

Owner
Povilas Susinskas
"I like to code" - Povilas Susinskas
Povilas Susinskas
Dead Code Detector (DCD) for PHP code.

This project is no longer maintained and its repository is only kept for archival purposes. PHP Dead Code Detector (PHPDCD) phpdcd is a Dead Code Dete

Sebastian Bergmann 406 Dec 30, 2022
Magento Project Mess Detector

Magento Project Mess Detector Author: Fabrizio Branca (fbrnc.net / @fbrnc) Some additional commands for the excellent n98-magerun Magento command-line

AOE 181 Aug 3, 2022
Create easy (and almost magic) forms

Why Magic Forms? Almost everyday we do forms for our clients, personal projects, etc Sometimes we need to add or remove fields, change validations, st

Martin M. 16 Dec 20, 2022
Wordpress starting framework for magic websites

Wideo Wordpress starting framework for magic websites. Full documentation: https://github.com/ideonetwork/wideo/wiki Usage Installation for wordpress

Zeranta Digital 4 Dec 13, 2022
Get the system resources in PHP, as memory, number of CPU'S, Temperature of CPU or GPU, Operating System, Hard Disk usage, .... Works in Windows & Linux

system-resources. A class to get the hardware resources We can get CPU load, CPU/GPU temperature, free/used memory & Hard disk. Written in PHP It is a

Rafael Martin Soto 10 Oct 15, 2022
Version is a library that helps with managing the version number of Git-hosted PHP projects

Version Version is a library that helps with managing the version number of Git-hosted PHP projects. Installation You can add this library as a local,

Sebastian Bergmann 6.3k Dec 26, 2022
Adds a compact "easy-sort" mode to Repeater and Repeater Matrix, making those fields easier to sort when there are a large number of items.

Repeater Easy Sort Adds a compact "easy-sort" mode to Repeater and Repeater Matrix, making those fields easier to sort when there are a large number o

Robin Sallis 3 Oct 10, 2021
Laravel package to convert English numbers to Bangla number or Bangla text, Bangla month name and Bangla Money Format

Number to Bangla Number, Word or Month Name in Laravel | Get Wordpress Plugin Laravel package to convert English numbers to Bangla number or Bangla te

Md. Rakibul Islam 50 Dec 26, 2022
A tool for managing SSH key access to any number of servers.

Revons - SSH Key Authority Features Easily manage SSH key access for all accounts on your servers. Manage user access and server-to-server access rule

Revons Community 1 Mar 14, 2022
Replace, concat strings or change number fields permanently using Grid Options

It's Pimcore Bundle to replace ,concat strings or change number fields permanently using Grid Options. It will save replaced strings directly in object.

LemonMind.com 5 Aug 31, 2022
The Current US Version of PHP-Nuke Evolution Xtreme v3.0.1b-beta often known as Nuke-Evolution Xtreme. This is a hardened version of PHP-Nuke and is secure and safe. We are currently porting Xtreme over to PHP 8.0.3

2021 Nightly Builds Repository PHP-Nuke Evolution Xtreme Developers TheGhost - Ernest Allen Buffington (Lead Developer) SeaBeast08 - Sebastian Scott B

Ernest Buffington 7 Aug 28, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 272 Dec 22, 2022
PHP Meminfo is a PHP extension that gives you insights on the PHP memory content

MEMINFO PHP Meminfo is a PHP extension that gives you insights on the PHP memory content. Its main goal is to help you understand memory leaks: by loo

Benoit Jacquemont 994 Dec 29, 2022
A sampling profiler for PHP written in PHP, which reads information about running PHP VM from outside of the process.

Reli Reli is a sampling profiler (or a VM state inspector) written in PHP. It can read information about running PHP script from outside of the proces

null 258 Sep 15, 2022
A multithreaded application server for PHP, written in PHP.

appserver.io, a PHP application server This is the main repository for the appserver.io project. What is appserver.io appserver.io is a multithreaded

appserver.io 951 Dec 25, 2022
Easy to use utility functions for everyday PHP projects. This is a port of the Lodash JS library to PHP

Lodash-PHP Lodash-PHP is a port of the Lodash JS library to PHP. It is a set of easy to use utility functions for everyday PHP projects. Lodash-PHP tr

Lodash PHP 474 Dec 31, 2022
A PHP 5.3+ and PHP 7.3 framework for OpenGraph Protocol

Opengraph Test with Atoum cd Opengraph/ curl -s https://getcomposer.org/installer | php php composer.phar install --dev ./vendor/atoum/atoum/bin/atoum

Axel Etcheverry 89 Dec 27, 2022
A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch screens with a resolution of 1024x600 connected to a Raspberry Pi.

EDStatusPanel A status monitor for Elite Dangerous, written in PHP. Designed for 1080p screens in the four-panel-view in panel.php, and for 7 inch scr

marcus-s 24 Oct 4, 2022
🐘 A probe program for PHP environment (一款精美的 PHP 探針, 又名X探針、劉海探針)

Simplified Chinese | 简体中文 Traditional Chinese(Taiwan) | 正體中文(臺灣) Traditional Chinese(Hong Kong) | 正體中文(香港) Japanese | 日本語 ?? X Prober This is a probe

Km.Van 1.2k Dec 28, 2022