PHP 7 Compatibility Checker

Related tags

Miscellaneous php7cc
Overview

PHP 7 Compatibility Checker(php7cc)

Project status

The project is no longer supported. Please consider using one of the following alternatives:

Introduction

php7cc is a command line tool designed to make migration from PHP 5.3-5.6 to PHP 7 easier. It searches for potentially troublesome statements in existing code and generates reports containing file names, line numbers and short problem descriptions. It does not automatically fix code to work with the new PHP version.

What kind of problems does it detect?

There are 2 types of issues reported by php7cc:

  1. Errors that will definitely cause some kind of trouble (a fatal, a syntax error, a notice, etc.) on PHP 7. These are highlighted in red.
  2. Warnings that may or may not lead to logical errors. For example, statements that are legal in both PHP 5 and PHP 7, but change their behaviour between versions fall into this category. Warnings are highlighted in yellow.

A list of statements that may cause errors or warnings to be reported can be found in the php-src repository.

Although php7cc tries to detect as much problems as accurately as possible, sometimes 100% reliable detection is very hard to achieve. That's why you should also run a comprehensive test suite for the code you are going to migrate.

Prerequisites

To run php7cc, you need php installed, minimum required version is 5.3.3. PHP 7 is supported, but files with syntax errors (for example, invalid numeric literals or invalid UTF-8 codepoint escape sequences) can't be processed. You will only get the warning message about the first syntax error for such files.

You may also need composer to install php7cc.

Installation

Phar package

You can download a phar package for any stable version from the Github releases page.

Composer (globally)

Make sure you have composer installed. Then execute the following command:

composer global require sstalle/php7cc

It is also recommended to add global Composer binaries directory to your PATH environment variable. The location of this directory depends on the operating system you use (see Composer documentation if you want to know more). The following command should work for some *nix systems:

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

This makes it possible to run php7cc by entering just the executable name.

Composer (locally, per project)

Make sure you have composer installed. Then execute the following command from your project directory:

composer require sstalle/php7cc --dev

Docker image

A docker image is available on Docker Hub (contributed and maintained by ypereirareis).

Usage

Examples in this section assume that you have installed php7cc globally using composer and that you have added it's vendor binaries directory to your PATH. If this is not the case, just substitute php7cc with the correct path to the binary of phar package. For local per project installation the executable will be located at <your_project_path>/vendor/bin/php7cc.

Getting help

To see the full list of available options, run:

php7cc --help

Checking a single file or directory

To check a file or a directory, pass its name as the first argument. Directories are checked recursively.

So, to check a file you could run:

php7cc /path/to/my/file.php

To check a directory:

php7cc /path/to/my/directory/

Specifying file extensions to check

When checking a directory, you can also specify a comma-separated list of file extensions that should be checked. By default, only .php files are processed.

For example, if you want to check .php, .inc and .lib files, you could run:

php7cc --extensions=php,inc,lib /path/to/my/directory/

Excluding file or directories

You can specify a list of absolute or relative paths to exclude from checking. Relative paths are relative to the checked directories.

So, if you want to exclude vendor and test directories, you could run:

php7cc --except=vendor --except=/path/to/my/directory/test /path/to/my/directory/

In this example, directories /path/to/my/directory/vendor, /path/to/my/directory/test and their contents will not be checked.

Specifying minimum issue level

If you set a minimum issue level, only issues having that or higher severity level will be reported by php7cc. There are 3 issue levels: "info", "warning" and "error". "info" is reserved for future use and is the same as "warning".

Example usage:

php7cc --level=error /path/to/my/directory/

Only errors, but not warnings will be shown in this case.

Specifying output format

There are two output format available: plain and json.

output-format command-line option, o in short form, can be used in order to change the output format:

php7cc -o json /path/to/my/directory/ | json_pp

Would output:

{
   "summary" : {
      "elapsedTime" : 0.0060338973999023,
      "checkedFiles" : 3
   },
   "files" : [
      {
         "errors" : {},
         "name" : "/path/to/my/directory/myfile.php",
         "warnings" : [
            {
               "text" : "String containing number in hexadecimal notation",
               "line" : 13
            }
         ]
      },
      {
         "warnings" : [
            {
               "line" : 6,
               "text" : "Reserved name \"string\" used as a class, interface or trait name "
            }
         ],
         "name" : "/path/to/my/directory/myfile.php",
         "errors" : {}
      }
   ]
}

Troubleshooting

Maximum function nesting level of 100/250/N reached, aborting!

You should increase maximum function nesting level in your PHP or Xdebug config file like this:

xdebug.max_nesting_level = 1000

Allowed memory size of N bytes exhausted

You should increase amount of memory available to CLI PHP scripts or disable PHP memory limit. The latter can be done by setting the memory_limit PHP option to -1. This option can be set by editing php.ini or by passing a command-line argument to PHP executable like this:

php -d memory_limit=-1 php7cc.php /path/to/my/directory

Other useful links

Contributing

Please read the contributing guidelines.

Credits

The list of contributors is available on the corresponding Github page.

Comments
  • Memory Issues

    Memory Issues

    I ran on a few files, and i got this error:

    Fatal error: Allowed memory size of 36700160 bytes exhausted (tried to allocate 72 bytes) in /root/.composer/vendor/sstalle/php7cc/src/Token/TokenCollection.php on line 18
    
    Call Stack:
        0.0001     221280   1. {main}() /root/.composer/vendor/sstalle/php7cc/bin/php7cc:0
        0.0003     227112   2. require('/root/.composer/vendor/sstalle/php7cc/bin/php7cc.php') /root/.composer/vendor/sstalle/php7cc/bin/php7cc:4
        0.0112    1670272   3. Symfony\Component\Console\Application->run() /root/.composer/vendor/sstalle/php7cc/bin/php7cc.php:21
        0.0135    2026696   4. Symfony\Component\Console\Application->doRun() /root/.composer/vendor/symfony/console/Application.php:123
        0.0136    2027488   5. Symfony\Component\Console\Application->doRunCommand() /root/.composer/vendor/symfony/console/Application.php:192
        0.0136    2028088   6. Symfony\Component\Console\Command\Command->run() /root/.composer/vendor/symfony/console/Application.php:844
        0.0140    2032432   7. Sstalle\php7cc\Infrastructure\PHP7CCCommand->execute() /root/.composer/vendor/symfony/console/Command/Command.php:259
        0.0333    5421656   8. Sstalle\php7cc\PathCheckExecutor->check() /root/.composer/vendor/sstalle/php7cc/src/Infrastructure/PHP7CCCommand.php:76
        0.0338    5469104   9. Sstalle\php7cc\PathChecker->check() /root/.composer/vendor/sstalle/php7cc/src/PathCheckExecutor.php:35
       11.0865   30588584  10. Sstalle\php7cc\PathChecker->checkFile() /root/.composer/vendor/sstalle/php7cc/src/PathChecker.php:48
       11.0866   30593168  11. Sstalle\php7cc\ContextChecker->checkContext() /root/.composer/vendor/sstalle/php7cc/src/PathChecker.php:63
       11.2009   32747280  12. Sstalle\php7cc\NodeTraverser\Traverser->traverse() /root/.composer/vendor/sstalle/php7cc/src/ContextChecker.php:50
       11.4681   35558448  13. Sstalle\php7cc\Token\TokenCollection->__construct() /root/.composer/vendor/sstalle/php7cc/src/NodeTraverser/Traverser.php:21
    
    opened by ghost 9
  • Use symfony 2.7.x

    Use symfony 2.7.x

    Hello,

    I would like to install this using composer global require sstalle/php7cc, instead of having to create a project for it. This would allow me to run php7cc from anywhere.

    Only problem is that it requires an old version of Symfony (2.5.x) which causes conflicts with other global packages that are requiring 2.7.x.

    Could the dependency be updated safely here ? Or is there any specific reason 2.5.x is uses ?

    Thanks

    opened by nWidart 6
  • PHP Fatal error:  'continue' not in the 'loop' or 'switch' context

    PHP Fatal error: 'continue' not in the 'loop' or 'switch' context

    PHP 7 compatibility checks are not working well, see https://www.drupal.org/node/2760025

    [Sun Jul 03 22:59:57.311158 2016] [:error] [pid 3168:tid 1844] [client ::1:54149] PHP Fatal error: 'continue' not in the 'loop' or 'switch' context in httprl\httprl.module on line 1418

    Drupal 7 code can be found at https://www.drupal.org/project/httprl.

    opened by alexhass 5
  • PHP-7 compatible dependencies?

    PHP-7 compatible dependencies?

    opened by onlyjob 5
  • Differentiate errors from possible warnings

    Differentiate errors from possible warnings

    Currently php7cc can output a lot of "warning" (like "foreach" with reference, etc) that are only possible incompatibilities but which are rendered the same way than real "errors". So I propose you to introduce two others kind of messages: Warning and Error that both extends Message (to keep the changes small).

    Warnings are still displayed in yellow but errors are now rendered in red. Simple Message have been kept (all existing messages have been converted to either Warning or Error, but could be useful in the future) and will be rendered without any style.

    I am not sure about the conversion of some incompatibilities so please let me know if something doesn't look good to you.

    demo

    opened by pyrech 4
  • Backward incompatible changes for PHP7 too few function arguments are not detected

    Backward incompatible changes for PHP7 too few function arguments are not detected

    I noticed, when I run php7cc on my project folder Backward incompatible changes for PHP 7 "too few function arguments are not detected ". Is there way to find list of functions in my project which has incompatible functions with mismatch number of arguments.

    opened by pramodwerea 3
  • test failures: Invalid UTF-8 codepoint escape sequence ; Invalid numeric literal

    test failures: Invalid UTF-8 codepoint escape sequence ; Invalid numeric literal

    With PHP-7.0.5 and PHPUnit-5.3.0 I'm getting the following test failures on Debian:

    There were 4 failures: 
    
    1) ContextCheckerTest::testMessages with data set #97 ('Escaped unicode codepoints in....test)', '<?php $str = "\u{xyz}";\n', array('Invalid UTF-8 codepoint escap...quence')) 
    Escaped unicode codepoints in double quoted string (/build/php7cc-1.0.2/test/resource/escapedUnicodeCodepoint/php7/escapedUnicodeCodepointInString.test) 
    Failed asserting that two strings are equal. 
    --- Expected 
    +++ Actual 
    @@ @@ 
    -'Invalid UTF-8 codepoint escape sequence' 
    +'Unicode codepoint escaping "\u{xyz}" in a string' 
    
    /build/php7cc-1.0.2/test/code/ContextCheckerTest.php:27 
    
    2) ContextCheckerTest::testMessages with data set #103 ('Escaped unicode codepoints in....test)', '<?php\n$str = <<<EOD\n    \u{xyz}\nEOD;\n\n', array('Invalid UTF-8 codepoint escap...quence'))                                                                                                                                                                         
    Escaped unicode codepoints in heredoc (/build/php7cc-1.0.2/test/resource/escapedUnicodeCodepoint/php7/escapedUnicodeCodepointInHeredoc.test) 
    Failed asserting that two strings are equal. 
    --- Expected 
    +++ Actual 
    @@ @@ 
    -'Invalid UTF-8 codepoint escape sequence' 
    +'Unicode codepoint escaping "\u{xyz}" in a string' 
    
    /build/php7cc-1.0.2/test/code/ContextCheckerTest.php:27 
    
    3) ContextCheckerTest::testMessages with data set #148 ('Invalid octal literal (/build....test)', '<?php\n$i = 0781;\n', array('Invalid numeric literal')) 
    Invalid octal literal (/build/php7cc-1.0.2/test/resource/invalidOctalLiteral/php7/invalidOctalLiteral.test) 
    Failed asserting that two strings are equal. 
    --- Expected 
    +++ Actual 
    @@ @@ 
    -'Invalid numeric literal' 
    +'Invalid octal literal 0781' 
    
    /build/php7cc-1.0.2/test/code/ContextCheckerTest.php:27 
    
    4) ContextCheckerTest::testMessages with data set #149 ('Invalid octal literal (/build....test)', '<?php\n$i = 011119;\n', array('Invalid numeric literal')) 
    Invalid octal literal (/build/php7cc-1.0.2/test/resource/invalidOctalLiteral/php7/invalidOctalLiteral.test) 
    Failed asserting that two strings are equal. 
    --- Expected 
    +++ Actual 
    @@ @@ 
    -'Invalid numeric literal' 
    +'Invalid octal literal 011119' 
    
    /build/php7cc-1.0.2/test/code/ContextCheckerTest.php:27 
    

    Please advise.

    opened by onlyjob 3
  • Respecify minimum version dependency

    Respecify minimum version dependency

    Since #9, the minimum requirement for php7cc seems to be PHP 5.5.9 due to the dependency to symfony/expression-language, which requires PHP >= 5.5.9

    opened by NicoHaase 3
  • Fix ReflectionException for lack of constructor

    Fix ReflectionException for lack of constructor

    I get ReflectionExceptions running php7cc on any file or directory, e.g. Class Sstalle\php7cc\NodeVisitor\GlobalVariableVariableVisitor does not have a constructor, so you cannot pass any constructor arguments

    This seems to happen with every single class in that directory so patching the base class seems easier.

    opened by gohanman 3
  • First stable release

    First stable release

    opened by sstalle 3
  • Use of color to indicate issue severity reduces accessibility and ability to write output to a text file.

    Use of color to indicate issue severity reduces accessibility and ability to write output to a text file.

    When run, php7cc outputs error text using only color to indicate the severity. This is an accessibility issue for those with color blindness.

    It also means that severity information is lost when the output is piped to a file. For instance, in the following output, the first is a yellow severity and the second is a red severity but when piped there's no indication of that.

    File: /Users/.../docroot/modules/field_ui/field_ui.module Line 278: Function argument(s) returned by "func_get_args" might have been modified func_get_args();

    File: /Users/.../docroot/modules/filter/filter.api.php Line 205: Removed regular expression modifier "e" used preg_replace('|(.+?)|se', '[codefilter_code]$1[/codefilter_code]', $text);

    opened by ba66e77 2
  • Should

    Should "does not cause an error in PHP 7" be an warning?

    If I have some code that will not throw an error should not that be a warning instead? Here is the code that is throwing an error:

    > Line 5: [Error] Name "object" that is reserved for future use (does not cause an error in PHP 7) used as a class, interface or trait name
        class Object implements \ArrayAccess, \Iterator
        {
        }
    

    Related issue: https://github.com/EasyPost/easypost-php/issues/52

    opened by itsdarrylnorris 1
  • Error without a file: [Error] file_get_contents(): Filename cannot be empty. Processing aborted.

    Error without a file: [Error] file_get_contents(): Filename cannot be empty. Processing aborted.

    I am getting this error:

    File:
    > [Error] file_get_contents(): Filename cannot be empty. Processing aborted.
    

    But is not showing the location (file) of the error.

    Have anyone run into a similar issue?

    opened by itsdarrylnorris 0
  • [Warning]

    [Warning] "yield" usage in expression context

    I am getting some warnings that should not be warnings. Please correct me if I am wrong.

    According to the PHP docs:

    Caution

    If you use yield in an expression context (for example, on the right hand side of an assignment), you must surround the yield statement with parentheses in PHP 5. For example, this is valid: $data = (yield $value);

    But this is not, and will result in a parse error in PHP 5: $data = yield $value;

    The parenthetical restrictions do not apply in PHP 7.

    This means that in PHP 7 does not matter if yield uses () or not. However, If you are supporting backward compatible you should add the () around yield.

    I am using an external package that is giving me this error: [Warning] "yield" usage in expression context

    File: /aws/aws-sdk-php/src/S3/S3MultiRegionClient.php

    
        \GuzzleHttp\Promise\coroutine(function () use($handler, $command, $cacheKey) {
            try {
                (yield $handler($command));
            } catch (\Aws\S3\Exception\PermanentRedirectException $e) {
                if (empty($command['Bucket'])) {
                    throw $e;
                }
                $result = $e->getResult();
                $region = null;
                if (isset($result['@metadata']['headers']['x-amz-bucket-region'])) {
                    $region = $result['@metadata']['headers']['x-amz-bucket-region'];
                    $this->cache->set($cacheKey, $region);
                } else {
                    $region = (yield $this->determineBucketRegionAsync($command['Bucket']));
                }
                $command['@region'] = $region;
                (yield $handler($command));
            } catch (\Aws\Exception\AwsException $e) {
                if ($e->getAwsErrorCode() === 'AuthorizationHeaderMalformed') {
                    $region = $this->determineBucketRegionFromExceptionBody($e->getResponse()->getBody());
                    if (!empty($region)) {
                        $this->cache->set($cacheKey, $region);
                        $command['@region'] = $region;
                        (yield $handler($command));
                    } else {
                        throw $e;
                    }
                } else {
                    throw $e;
                }
            }
        });
    
    

    Looking over the yield implementations, it looks like we are wrapping them around (). Any particular reason why I still get this error? Should we avoid this error if there is () around yield?

    opened by itsdarrylnorris 1
  • PHP nullable typehinting not supported now

    PHP nullable typehinting not supported now

    WTF: https://wiki.php.net/rfc/nullable_types

    Error:

    File: /app/vendor/symfony/config/Definition/BaseNode.php
    > [Error] Syntax error, unexpected '?', expecting T_VARIABLE on line 39. Processing aborted.
    

    Code:

        public function __construct(?string $name, NodeInterface $parent = null, array $values = array())
    
    opened by KarelWintersky 0
  • Unquoted string as  index or general not detected

    Unquoted string as index or general not detected

    $var[not_defined_constant] = $other_var.

    It is a warning in php 7 and will throw error in future versions.

    It should be $var['not_defined_constant'] = $other_var.

    Are you planning on implementing it?

    Thanks

    opened by voskynet 0
  • space between = and & fools the checker where =& would be caught

    space between = and & fools the checker where =& would be caught

    The largest set of things that were missed in the code I checked was assignment of a reference to new object that was caught fine when it had =& but was missed everywhere the code had a space between the = and the &. Might be poor practice, but that's the code I had to work with.

    opened by sidney 0
Releases(1.2.1)
Owner
null
This project backports features found in the latest PHP versions and provides compatibility layers for some extensions and functions

This project backports features found in the latest PHP versions and provides compatibility layers for some extensions and functions. It is intended to be used when portability across PHP versions and extensions is desired.

Symfony 2.2k Dec 29, 2022
Backwards compatibility Extension and Library for PHP 8.x and later

colopl_bc Provides various compatibility functions required for PHP (temporary) migration. WARNING This extension is intended for temporary use only.

COLOPL,Inc. 10 Jun 13, 2023
Silverstripe-sspy - Python based SSPAK export with higher reliability and cross-platform compatibility

SSPY - Python Stand-alone SSPAK solution © Simon Firesphere Erkelens; Moss Mossman Cantwell Usage: sspy [create|load|extract] (db|assets) --file=my.

Simon Erkelens 1 Jun 29, 2021
The tool converts different error reporting standards for deep compatibility with popular CI systems (TeamCity, IntelliJ IDEA, GitHub Actions, etc).

JBZoo / CI-Report-Converter Why? Installing Using as GitHub Action Example GitHub Action workflow Available Directions Help description in terminal Co

JBZoo Toolbox 17 Jun 16, 2022
A Telegram CC Checker Bot with hella lotta features.

SDMN CC Checker Bot A Telegram CC Checker Bot with hella lotta features. ?? Features Admin Panel Ban a user Unban a user Mute a user Unmute a user Che

iNaveen 192 Jan 8, 2023
MD5-CHECKER

MD5-Checker Install on desktop : Install XAMPP Added environment variable system path => C:\xampp\php download the script and save it in your folder o

Alex 1 Jan 9, 2022
My personal uptime checker powered by Filament. ⚡️

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Ryan Chandler 16 Sep 7, 2022
Magento Semantic Versioning Checker

Magento Semantic Versioning Checker

Magento 28 Dec 5, 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
PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP language

php-text-analysis PHP Text Analysis is a library for performing Information Retrieval (IR) and Natural Language Processing (NLP) tasks using the PHP l

null 464 Dec 28, 2022
PHP generics written in PHP

PHP generics written in PHP Require PHP >= 7.4 Composer (PSR-4 Autoload) Table of contents How it works Quick start Example Features Tests How it work

Anton Sukhachev 173 Dec 30, 2022