Git Product home page Git Product logo

phpqa's Introduction

PHPQA

Analyze PHP code with one command.

License Latest Stable Version Total Downloads Build Status Windows status

Requirements

Why?

Every analyzer has different arguments and options in different formats (no surprise in PHP world :). If you ever tried to get ignoring directories to work then you know what I mean. On the other hand CLI tools are cool because you can analyze any directory or file. Unfortunately Jenkins, Travis, Scrutiziner needs special configuration file. What if you want to analyze every bundle in your Symfony app? Will you create e.g. Jenkins project/task for each bundle?

  • I want to analyze selected directory without complex configuration and creating extra files/tasks
  • I don't care about format of ignored directories in phploc, phpmd, ...
  • I don't want to update all projects when QA tool is updated or if I've found cool tool like PHPMetrics
  • I don't want to analyze XML files → tool should be able to build html reports
  • I want fast execution time → tools should run in parallel (thanks Robo)

Available tools

Tool Description
phploc Measure the size of a PHP project
phpcpd Copy/Paste Detector (CPD) for PHP code
phpcs Detect violations of a coding standard
pdepend PHP adaptation of JDepend
phpmd Scan PHP project for messy code
phpmetrics Static analysis tool for PHP
Suggested tools

Newly added tools aren't preinstalled. You have to install relevant composer packages if you want to use them.

Tool PHP Supported since Description
security-checker >= 5.6 1.24 Check composer.lock for known security issues
php-cs-fixer >= 5.3 1.12 Automatically detect and fix PHP coding standards issues
phpunit >= 5.3 1.13 The PHP Unit Testing framework
phpstan >= 7.0 1.9 Discover bugs in your code without running it
psalm >= 5.6 1.14 A static analysis tool for finding errors in PHP applications
parallel-lint >= 5.4 1.9 Check syntax of PHP files
deptrac >= 7.2 1.25 Enforce rules for dependencies between software layers
MacFJA/phpqa-extensions - - PHP Assumptions, Magic Number Detector, ...

Tip: use bin/suggested-tools.sh install for installing the tools.

Install

Clone + composer

# install phpqa
git clone https://github.com/EdgedesignCZ/phpqa.git && cd phpqa && composer install --no-dev

# make phpqa globally accessible
## you can symlink binary
sudo ln -s /path-to-phpqa-repository/phpqa /usr/bin/phpqa
## or add this directory to your PATH in your ~/.bash_profile (or ~/.bashrc)
export PATH=~/path-to-phpqa-repository-from-pwd:$PATH

Composer

# global installation
composer global require edgedesign/phpqa --update-no-dev
# Make sure you have ~/.composer/vendor/bin/ in your PATH.

# local installation
composer require edgedesign/phpqa --dev

Of course you can add dependency to require-dev section in your composer.json. But I wouldn't recommend it. In my experience one QA tool which analyzes N projects is better than N projects with N analyzers. It's up to you how many repositories you want to update when new version is released.

Symfony3 components

Symfony3 is supported since version 1.7. Install at least version ~3.0 of sebastian/phpcpd, otherwise you'll get error The helper "progress" is not defined.

{
    "require-dev": {
        "edgedesign/phpqa": ">=1.7",
        "sebastian/phpcpd": "~3.0"
    }
}
Fake global installation in local project

Do you have problems with dependencies and you can't install phpqa globally? Install phpqa in subdirectory.

#!/bin/sh

if [ ! -f qa/phpqa ];
then
    echo "installing phpqa"
    (git clone https://github.com/EdgedesignCZ/phpqa.git ./qa  && cd qa && composer install --no-dev)
fi

qa/phpqa

Docker

Official docker image repository is https://github.com/EdgedesignCZ/phpqa/pkgs/container/phpqa. Images can be used at Gitlab CI.

docker run --rm -it ghcr.io/edgedesigncz/phpqa:v1.26.2-php7.2 phpqa tools
# using a tool without phpqa
docker run --rm -it ghcr.io/edgedesigncz/phpqa:v1.26.2-php7.2 phploc -v
Image PHP version Composer version Tools versions
ghcr.io/edgedesigncz/phpqa:v1.26.2-php7.2 7.2 1.8.0 Versions that supports symfony2 components from default composer.lock. Not latest versions.
ghcr.io/edgedesigncz/phpqa:v1.26.2-php8.1 8.1 2.2.12 Generally, latest versions available at the moment. If you need different versions, then build custom docker image

Beware that images as lean as possible. That can be a problem for running PHPUnit tests. In that case, you might need different PHP version, miss PHP extensions for database etc. You can install phpqa in another php image Or build custom docker image.

docker run --rm -it ghcr.io/edgedesigncz/phpqa:v1.26.2-php7.2 sh -c "php --version && composer --version && composer outdated --direct --all && phpqa tools"
docker run --rm -it ghcr.io/edgedesigncz/phpqa:v1.26.2-php8.1 sh -c "php --version && composer --version && composer outdated --direct --all && phpqa tools"

There are also available images eko3alpha/docker-phpqa and sparkfabrik/docker-phpqa. phpqa is used as an entrypoint (I haven't been able to use these images at Gitlab CI + Windows probably needs different environment variable).

docker run --rm -u $UID -v $PWD:/app eko3alpha/docker-phpqa --report --ignoredDirs vendor,build,migrations,test

Analyze

Command Description
phpqa --help Show help - available options, tools, default values, ...
phpqa --analyzedDirs ./ --buildDir ./build Analyze current directory and save output to build directory
phpqa --analyzedDirs src,tests Analyze source and test directory (phpmetrics analyzes only src)
phpqa --analyzedDir ./ Deprecated in v1.8 in favor of --analyzedDirs
phpqa --ignoredDirs build,vendor Ignore directories
phpqa --ignoredFiles RoboFile.php Ignore files
phpqa --tools phploc,phpcs Run only selected tools
phpqa --tools phpmd:1,phpcs:0,phpcpd:0 Check number of errors and exit code. New in v1.6
phpqa --verbose Show output from executed tools
phpqa --quiet Show no output at all
phpqa --output cli CLI output instead of creating files in --buildDir
phpqa --execution no-parallel Don't use parallelism if --execution != parallel
phpqa --config ./my-config Use custom configuration
phpqa --report Build html reports
phpqa --report offline Build html reports with bundled assets. New in v1.16
phpqa tools Show versions of available tools

Tip: CLI options can be defined in .phpqa.yml

Output modes

Tool --output file (default) - generated files --output cli
phploc phploc.xml
phpcpd phpcpd.xml
phpcs checkstyle.xml full report
pdepend pdepend-jdepend.xml, pdepend-summary.xml, pdepend-dependencies.xml, pdepend-jdepend.svg, pdepend-pyramid.svg
phpmd phpmd.xml
phpmetrics phpmetrics.html (v1), phpmetrics/index.html (v2), phpmetrics.xml
php-cs-fixer php-cs-fixer.html
parallel-lint parallel-lint.html
phpstan phpstan.html, phpstan-phpqa.neon , phpstan-phpqa.neon
psalm psalm.html, psalm.xml, psalm-phpqa.xml , psalm-phpqa.xml
deptrac deptrac.html

Exit code

phpqa can return non-zero exit code since version 1.6. It's optional feature that is by default turned off. You have to define number of allowed errors for phpcpd, phpcs, phpmd in --tools.

mode Supported version What is analyzed?
--output file >= 1.6 Number of errors in XML files, or exit code for tools without XML
--output cli >= 1.9 Exit code

Let's say your Travis CI or Circle CI build should fail when new error is introduced. Define number of allowed errors for each tools and watch the build:

phpqa --report --tools phpcs:0,phpmd:0,phpcpd:0,parallel-lint:0,phpstan:0,phpmetrics,phploc,pdepend

Number of allowed errors can be also defined in .phpqa.yml.

phpqa:
    # can be overriden by CLI: phpqa --tools phpcs:1
    tools:
        - phpcs:0

File mode

screenshot from 2016-07-23 13 53 34

Tip: override phpcs.ignoreWarnings if you want to count just errors without phpcs warnings.

CLI mode

screenshot from 2016-12-21 14 31 27

Tip: use echo $? for displaying exit code.

Advanced configuration - .phpqa.yml

Provide CLI options from .phpqa.yml:

CLI option .phpqa.yml
phpqa --analyzedDirs ./ phpqa.analyzedDirs: ./
phpqa --buildDir ./build phpqa.buildDir: ./build
phpqa --ignoredDirs build,vendor phpqa.ignoredDirs: build,vendor
phpqa --ignoredFiles RoboFile.php phpqa.ignoredFiles: RoboFile.php
phpqa --tools phploc,phpcs:0 phpqa.tools: phploc,phpcs:0
phpqa --report phpqa.report: true
phpqa --execution no-parallel phpqa.execution: no-parallel
phpqa --output cli phpqa.output: cli
phpqa --verbose phpqa.verbose: true

Files

.phpqa.yml is automatically detected in current working directory, but you can specify directory via option:

# use .phpqa.yml from defined directory
phpqa --config path-to-directory-with-config

You don't have to specify full configuration. Missing or empty values are replaced with default values from our .phpqa.yml. Example of minimal config that defines only standard for CodeSniffer:

phpcs:
    standard: Zend

Tip: use PHP Coding Standard Generator for generating phpcs/phpmd standards.

You can specify multiple configurations directory (separated by ,). They are loaded in the order they are defined. This can be useful if you have a common configuration file that you want to use across multiple project but you still want to have per project configuration. Also, path inside configuration file are relative to where the configuration file is, so if you have a package that bundle a custom tool, the .phpqa.yml in the package can refers files within it.

phpqa --config ~/phpqa/,my-config/,$(pwd)

Custom binary

Every tool can define custom binary. Use phar or global tool, if you have troubles with dependencies, e.g.:

  • can't install something because of symfony components or php version
  • phpstan does not work, if phpmetrics v1 is installed in composer (Hoa main file (Core.php) must be included once.) -> use phar for phpmetrics

Generally, composer installation is preferred because of detecting version. Phar works too, but it might be tricky. If a tool has composer package with phar (e.g. vimeo/phar), use it instead of custom binary:

psalm:
    binary: /usr/local/bin/psalm.phar

Possibilities are infinite. You can define new tool and run it. For example I like exploring codebase in phpmetrics v1 and composer info in v2. Install phpmetrics v2 in composer and use phar for v1 to avoid phpstan conflicts:

$ cat tests/.ci/.phpqa.yml
phpmetricsV1:
    binary: /usr/local/bin/phpmetrics.phar
tool:
    phpmetricsV1: Edge\QA\Tools\Analyzer\PhpMetrics

$ phpqa --config tests/.ci/ --tools phpmetricsV1,phpmetrics

Override tools' settings

Tool Settings Default Value Your value
phpqa.extensions PHP File extensions php Name of php file to parse, you can specify it like a string php,inc,modules or like a yaml array.
phpcs.standard Coding standard PSR2 Name of existing standard (PEAR, PHPCS, PSR1, PSR2, Squiz, Zend), or path to your coding standard. To specify multiple standards, you can use an array
phpcs.ignoreWarnings If number of allowed errors is compared with warnings+errors, or just errors from checkstyle.xml false Boolean value
phpcs.reports Report types full report in cli mode, checkstyle in file mode Predefined report types or custom reports
php-cs-fixer.rules Coding standard rules @PSR2 String value
php-cs-fixer.allowRiskyRules Whether risky rules may run false Boolean value
php-cs-fixer.config Load configuration from file null Path to .phpcs file
php-cs-fixer.isDryRun If code is just analyzed or fixers are applied true Boolean value
phpmetrics.config Configuration for phpmetrics v1 null Path to .phpmetrics.yml file
phpmetrics.git phpmetrics v2 analyses based on Git History null Boolean value or path to git binary
phpmetrics.junit phpmetrics v2 evaluates metrics according to JUnit logs null Path to JUnit xml
phpmetrics.composer phpmetrics v2 analyzes composer dependencies null Path to composer.json when the file is not included in analyzedDirs
pdepend.coverageReport Load Clover style CodeCoverage report null Path to report produced by PHPUnit's --coverage-clover option
phpmd.standard Ruleset Edgedesign's standard Path to ruleset. To specify multiple rule sets, you can use an array
phpmd.ignoreParsingErrors If parsing errors affect exit code, or just violations true Boolean value
phpcpd Minimum number of lines/tokens for copy-paste detection 5 lines, 70 tokens
phpstan Level, config file, memory limit Level 0, %currentWorkingDirectory%/phpstan.neon, memoryLimit: null Take a look at phpqa config in tests/.ci
phpunit.binary Phpunit binary phpqa's phpunit Path to phpunit executable in your project, typically vendor/bin/phpunit
phpunit.config PHPUnit configuration, analyzedDirs and ignoredDirs are not used, you have to specify test suites in XML file null Path to phpunit.xml file
phpunit.reports Report types no report List of reports and formats, corresponds with CLI option, e.g. --log-junit is log: [junit] in .phpqa.yml
psalm.config Psalm configuration, analyzedDirs and ignoredDirs are appended to projectFiles Predefined config Path to psalm.xml file
psalm.deadCode Enable or not --find-dead-code option of psalm false Boolean value
psalm.threads Set the number of process to use in parallel (option --threads of psalm) (Only if --execution == parallel for phpqa) 1 Number (>= 1)
psalm.showInfo Display or not information (non-error) messages (option --show-info= of psalm) true Boolean value
psalm.memoryLimit Custom memory limit, ignore unless you are getting Fatal error: Allowed memory size of ... bytes exhausted null String value, e.g. '1024M', '1G'
deptrac.depfile Complete deptract config (phpqa won't update source and excluded files) null Path to depfile.yml file
security-checker.composerLock Use it if composer.lock is not in current working directory or analyzed directory null Path to composer.lock file

HTML reports

If you don't have Jenkins or other CI server, then you can use HTML reports. HTML files are built when you add option --report. Take a look at report from phpqa.

# build html reports
phpqa --report

Custom templates

Define custom templates if you don't like default templates. You have to define path to xsl files in your .phpqa.yml:

# use different template for PHPMD, use default for other tools
report:
    phpmd: my-templates/phpmd.xsl

Be aware that all paths are relative to .phpqa.yml. Don't copy-paste section report if you don't have custom templates!

Requirements

xsl extension must be installed and enabled for exporting HTML reports. Otherwise you'll get error PHP Fatal error: Class 'XSLTProcessor' not found.

# install xsl extension in Ubuntu
sudo apt-get update
sudo apt-get install php5-xsl
sudo service apache2 restart

Continuous integration

We use Jenkins-CI in Edgedesign. Below you can find examples of Phing, Robo and bash tasks.

Project with one directory

Typically in Symfony project you have project with src directory with all the code and tests. So you don't need ignore vendors, web directory etc.

Phing - build.xml

<target name="ci-phpqa">
    <exec executable="phpqa" passthru="true">
        <arg value="--analyzedDirs=./src" />
        <arg value="--buildDir=./build/logs" />
        <arg value="--report" />
    </exec>
</target>

Robo - RoboFile.php

public function ciPhpqa()
{
    $this->taskExec('phpqa')
        ->option('analyzedDirs', './src')
        ->option('buildDir', './build/logs')
        ->option('report')
        ->run();
}

Project with multiple directories (src, tests, ...)

When you analyze root directory of your project don't forget to ignore vendors and other non-code directories. Otherwise the analysis could take a very long time.

Since version 1.8 phpqa supports analyzing multiple directories. Except phpmetrics that analyzes only first directory. Analyze root directory and ignore other directories if you rely on phpmetrics report.

Phing - build.xml

<target name="ci-phpqa">
    <exec executable="phpqa" passthru="true">
        <arg value="--analyzedDirs=./" />
        <arg value="--buildDir=./build/logs" />
        <arg value="--ignoredDirs=app,bin,build,vendor,web" />
        <arg value="--ignoredFiles= " />
        <arg value="--verbose" />
        <arg value="--report" />
    </exec>
</target>

Robo - RoboFile.php

public function ciPhpqa()
{
    $this->taskExec('phpqa')
        ->option('verbose')
        ->option('report')
        ->option('analyzedDirs', './')
        ->option('buildDir', './build')
        ->option('ignoredDirs', 'build,bin,vendor')
        ->option('ignoredFiles', 'RoboFile.php,error-handling.php')
        ->run();
}

Bash

phpqa --verbose --report --analyzedDirs ./ --buildDir ./var/CI --ignoredDirs=bin,log,temp,var,vendor,www

Circle.ci - artifacts + global installation

machine:
    php:
        version: 7.0.4

dependencies:
    cache_directories:
        - ~/.composer/cache
    post:
        - 'git clone https://github.com/EdgedesignCZ/phpqa.git ./qa && cd qa && composer install --no-dev'

test:
    override:
        - vendor/bin/phpunit --testdox-html ./var/tests/testdox.html --testdox-text ./var/tests/testdox.txt --log-junit $CIRCLE_TEST_REPORTS/phpunit/junit.xml
        - qa/phpqa --report --verbose --buildDir var/QA --ignoredDirs vendor --tools=phpcs:0,phpmd:0,phpcpd:0,phploc,pdepend,phpmetrics
    post:
        - cp -r ./var/QA $CIRCLE_ARTIFACTS
        - cp -r ./var/tests $CIRCLE_ARTIFACTS

Gitlab.ci - docker installation + composer cache + artifacts

stages:
  - test

test:
  stage: test
  image: ghcr.io/edgedesigncz/phpqa:v1.26.2-php7.2
  variables:
    BACKEND_QA: "*/backend/var/QA"
    BACKEND_CACHE: $CI_PROJECT_DIR/.composercache
  cache:
    paths:
    - $BACKEND_CACHE
  script:
    - 'export COMPOSER_CACHE_DIR=$BACKEND_CACHE'
    - 'composer install --ignore-platform-reqs --no-progress --no-suggest'
    - 'phpqa --report --tools phpcs:0,phpunit:0 --buildDir var/QA --analyzedDirs ./ --ignoredDirs var,vendor'
  artifacts:
    when: always
    paths:
    - $BACKEND_QA

Github actions - docker installation + composer cache + artifacts

name: QA

on: [push]

jobs:
  qa:
    container: ghcr.io/edgedesigncz/phpqa:v1.26.2-php8.1
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      # composer is not necessary, if you are not running phpunit/psalm/phpstan
      - name: Cache composer
        uses: actions/cache@v2
        with:
          path: |
            ~/.composer/cache
            vendor
          key: php-composer-${{ hashFiles('**/composer.lock') }}
          restore-keys: "php-composer-74"
      - name: Install dependencies
        run: |
          composer install --no-interaction --no-progress --ignore-platform-reqs;

      - name: phpqa
        run: phpqa --report --tools phpunit:0,phpcs:0,phpmd:0,psalm:0,phpstan:0 --buildDir build --analyzedDirs ./ --ignoredDirs build,vendor

      - name: Upload QA files
        uses: actions/upload-artifact@v2
        with:
          name: phpqa
          path: build

Contributing

Contributions from others would be very much appreciated! Send pull request/issue. Thanks!

License

Copyright (c) 2015 - present Edgedesign.cz. MIT Licensed, see LICENSE for details.

phpqa's People

Contributors

cbastienbaron avatar garak avatar gliautard avatar guvra avatar macfja avatar ndench avatar omarlopesino avatar ondrejmirtes avatar paolomainardi avatar paras-malhotra avatar photodude avatar raul-castellanos-edo avatar sojki avatar thinkspill avatar tomtomau avatar zdenekdrahos avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpqa's Issues

Changing composer bin-dir breaks tools path

When you use phpqa in project locally and you change composer bin-dir, than phpqa cannot find binaries for tools (phpcpd, phpmd, ...).

PHPQA only checks location of autoload.php, but then expects bin folder in same path. Maybe the bin folder should be checked too.

Path of bin folder can be (according to composer docs) changed in two ways

  • Setting the bin-dir configuration setting in composer.json
  • Setting the environment variable COMPOSER_BIN_DIR

Or [the simple solution] PHPQA can only trigger exception if the tool in expected path is not found (Yes, you can see it in exit code 127, but this is easy to overlook).

phpcs warnings should not be reported as errors

phpcs warnings count as errors, exit with code 1 and break ci builds.

this could be avoided by changing the errorsXPath setting of phpcs.
change phpqa/src/CodeAnalysisTasks.php : 26 from "'errorsXPath' => '//checkstyle/file/error'" to "'errorsXPath' => '//checkstyle/file/error[@Severity="error"]'".

Chaotic default output

It would be nice to have better output by default.

  • no cross output due to parallel excetution
  • maybe not so verbose

_2az5um5ug_d

phpunit & code coverage support

Hi,
TY for this pratical tool ;) one line command save my time ! ;)
It's possible to integrate phpunit and particulary code coverage integrate in the UI ?

Thanks in advance for you're response
seb

Twig_loader_filesystem not found with new phpmetrics

Hi, i updated the phpmetrics Package to 2.*
The twig integration has been removed in this new version and do you need twig in your report file generation.
So you should add the Twig ~1 to your dependencies.
Mfg Mario

Symfony Process timeout

Symfony process has a rather stupidly low timeout (60 seconds) which is less than ideal for slow and heavy processing tools (such as pdepends and phpmd)

It would be ideal to allow for a configuration value to "turn up" the default timeout on the process (although robo has a timeout value it's not setting right on the internal symfony process)

I'm currently using this after line 185 in CodeAnalysisTasks.php

$tool->process->setTimeout(3600);

which is at least allowing all the tasks to finish properly

Unexpected deps resolving

I really don't understand current weird requirements using <=, that I can't find anywhere else.
Can't you just do like everyone else and using tilde or caret?
Now, there's consolidation/robo: <=1 that is preventing from install version 1.0.8. Well, in theory the constraint is not wrong, but if I try to force an explicit require, I get:

composer global require consolidation/robo:^1.0.8
[...]
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - edgedesign/phpqa v1.12.0 requires consolidation/robo <=1 -> satisfiable by consolidation/robo[0.1.0, 0.1.1, 0.2.0, 0.3.0, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.4.5, 0.4.6, 0.4.7, 0.5.0, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.6.0, 0.7.0, 0.7.1, 0.7.2, 1.0.0, 1.0.0-RC1, 1.0.0-RC2, 1.0.0-RC3, 1.0.0-beta1] but these conflict with your requirements or minimum-stability.
    - edgedesign/phpqa v1.12.0 requires consolidation/robo <=1 -> satisfiable by consolidation/robo[0.1.0, 0.1.1, 0.2.0, 0.3.0, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.4.5, 0.4.6, 0.4.7, 0.5.0, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.6.0, 0.7.0, 0.7.1, 0.7.2, 1.0.0, 1.0.0-RC1, 1.0.0-RC2, 1.0.0-RC3, 1.0.0-beta1] but these conflict with your requirements or minimum-stability.
    - edgedesign/phpqa v1.12.0 requires consolidation/robo <=1 -> satisfiable by consolidation/robo[0.1.0, 0.1.1, 0.2.0, 0.3.0, 0.3.2, 0.3.3, 0.3.4, 0.3.5, 0.3.6, 0.3.7, 0.4.0, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.4.5, 0.4.6, 0.4.7, 0.5.0, 0.5.1, 0.5.2, 0.5.3, 0.5.4, 0.6.0, 0.7.0, 0.7.1, 0.7.2, 1.0.0, 1.0.0-RC1, 1.0.0-RC2, 1.0.0-RC3, 1.0.0-beta1] but these conflict with your requirements or minimum-stability.
    - Installation request for edgedesign/phpqa (locked at v1.12.0, required as ^1.7) -> satisfiable by edgedesign/phpqa[v1.12.0].

Can't have any spaces in any tool paths

Currently binary paths for the composer base directory location and binary paths of tools are not properly quoted so any path that has a space in it will fail to run

just using escapePath in the Pathtobinary around the returned tool fixes the issue

Total number of warnings and errors

Very helpful package. Thanks.

Is there any way we can only get total number of errors and warnings in terminal?

We need to save it as a env variables when we are merging the codes to master then we pass the variable for allowed warnings for next PR check.

Docker image latest tag

Hi!

Please mark the latest image in Docker Registry via latest tag too. This is standard for Docker world and many soft uses it by default.

phpcs ignoreWarnings does not work in CLI mode

composer info | grep phpqa
edgedesign/phpqa                      v1.18.0 Analyze PHP code with one command.
composer info | grep php_code
squizlabs/php_codesniffer             3.2.3   PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards

ignoreWarnings: in my .phpqa.yml seems ignored.

1° set true the output cli show warnings
2° final repport too

+---------------+-------------------+-----------+--------+--+
| Tool          | Allowed exit code | Exit code | Is OK? |  |
+---------------+-------------------+-----------+--------+--+
| phpcs         | 0                 | 1         | x      |  |
| parallel-lint | 0                 | 0         | ✓      |  |
+---------------+-------------------+-----------+--------+--+
| phpqa         |                   | 1         | x      |  |
+---------------+-------------------+-----------+--------+--+

I've solve it

.../vendor/edgedesign/phpqa/src/Tools/Analyzer/Phpcs.php

I've added

        if ($this->tool->errorsType) {
            $args[] = '-n';
        }

in

    protected function buildPhpcs(array $installedStandards)
    {
        $this->tool->errorsType = $this->config->value('phpcs.ignoreWarnings') === true;
        $standard = $this->config->value('phpcs.standard');
        if (!in_array($standard, $installedStandards)) {
            $standard = \Edge\QA\escapePath($this->config->path('phpcs.standard'));
        }
        $args = array(
            '-p',
            'standard' => $standard,
            $this->options->ignore->phpcs(),
            $this->options->getAnalyzedDirs(' '),
            'extensions' => $this->config->csv('extensions')
        );
        if ($this->tool->errorsType) {
            $args[] = '-n';
        }
        if ($this->options->isSavedToFiles) {

https://patch-diff.githubusercontent.com/raw/EdgedesignCZ/phpqa/pull/120.patch

document the usage of phpcs3

At the moment the usage of php_codesniffer version 3 is not documented.

Moreover, when cloning directly the project, version 2 of php_codesniffer is available since the version is locked in composer.lock, while when installing the library as a composer dependency, you'll get version 3 since there is no bound on composer.json

This and https://github.com/jmolivas/phpqa/

I've been researching this kind of tools, and I found that these two share the exact same name.
Is there any relationship between the two, or it is just a coincidence?

Thanks.

Tools command is broken

~$ phpqa tools
PHP Fatal error:  Call to a member function binary() on null in src/CodeAnalysisTasks.php on line 25

Running phpcs got Exit code 2

I try to use phpqa.
I got this error, but it doesn't fail.

I use
phpqa 1.13.0
phpcs 3.0.2

 [Edge\QA\Task\ParallelExec] "/Users/negaihoshi/Workplace/Project_Template/vendor/edgedesign/phpqa/../../../vendor/bin/phpcs" -p --standard=PSR2  --ignore=*/vendor/* "./" --extensions=php --report-checkstyle="build//checkstyle.xml"
 [Edge\QA\Task\ParallelExec]  '"/Users/negaihoshi/Workplace/Project_Template/vendor/edgedesign/phpqa/../../../vendor/bin/phpcs" -p --standard=PSR2  --ignore=*/vendor/* "./" --extensions=php --report-checkstyle="build//checkstyle.xml"' exited with code 2
  Time 1.584s
 [Edge\QA\Task\ParallelExec]  Exit code 2  Time 1.584s

[phpqa]
+-------+----------------+--------------+--------+-------------+
| Tool  | Allowed Errors | Errors count | Is OK? | HTML report |
+-------+----------------+--------------+--------+-------------+
| phpcs |                | 16           | ✓      |             |
+-------+----------------+--------------+--------+-------------+
| phpqa |                | 16           | ✓      |             |
+-------+----------------+--------------+--------+-------------+

[phpqa] No failed tools

Set multiple analyzedDirs

Hi, wounld to analys multiple folders in one command. Like this
vendor/bin/phpqa --verbose --analyzedDir ./src1 ./src2 --report

The following error occurred on starting this command.
" Too many arguments, expected arguments "command"."

To you have any idea how this works?

Support PHP CS Fixer

Hi.
Are there any chances that you would add PHP CS Fixer to collection of supported tools ?

Parse phpstan output

It would be great if the phpstan output was parsed the same as the output from the other tools. At the moment no matter how many errors phpstan reports, phpqa reports it as a single error as you can see here:
2018-02-08_17-08-15

Here is an example of the current phpstan output:
2018-02-08_17-07-52

And here is an example of the psalm output, which is the same as the other linting tools:
2018-02-08_17-07-40

Error with PhpCpd progress helper

Hi Guys,

first of all thanks for your tool, it's really great !
I encounter an issue with phpcpd running via phpqa. I've trying with parallel and non parallel execution, here the console output.

Output for  /Users/Cyril/.composer/vendor/edgedesign/phpqa/../../bin/phpcpd --progress  --exclude=build --exclude=vendor --exclude=Tests --exclude=scripts --exclude=var --exclude=web "./src" --min-lines 5 --min-tokens 70 --log-pmd "./build/phpcpd.xml" 
phpcpd 2.0.4 by Sebastian Bergmann.




  [Symfony\Component\Console\Exception\InvalidArgumentException]  
  The helper "progress" is not defined.                           


phpcpd [--names NAMES] [--names-exclude NAMES-EXCLUDE] [--exclude EXCLUDE] [--log-pmd LOG-PMD] [--min-lines MIN-LINES] [--min-tokens MIN-TOKENS] [--fuzzy] [--progress] [--] [<values>]...



 [Edge\QA\Task\NonParallelExec]  Exit code 2  Time 68.85s

With phpcpd 2.0.1 with same arguments no problem.
Can you help me please ?
Thanks
Cyril

Allow using custom binary for phpunit (instead of default 4.X from phpqa/vendor/bin/phpunit)

  1. phpqa is installed globally
  2. phpqa's phpunit version != project's phpunit, e.g. v4.8.21 vs v5.7.19
phpqa --analyzedDirs src --tools phpunit:0 --verbose
 [FileSystem\CleanDir] Cleaned build/
 [FileSystem\FilesystemStack] mkdir ["build\/"]
 [Edge\QA\Task\ParallelExec] "/qa/vendor/bin/phpunit" --configuration=phpunit.xml --log-junit="build//log-junit.xml" --log-tap="build//log-tap.text" --testdox-html="build//testdox-html.html" --testdox-text="build//testdox-text.txt"
 1/1 [============================] 100%
 [Edge\QA\Task\ParallelExec] Output for  "/qa/vendor/bin/phpunit" --configuration=phpunit.xml --log-junit="build//log-junit.xml" --log-tap="build//log-tap.text" --testdox-html="build//testdox-html.html" --testdox-text="build//testdox-text.txt"

Fatal error: Uncaught Error: Call to undefined method PHPUnit_Util_Configuration::getTestdoxGroupConfiguration() in /my-project/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:1066
Stack trace:
#0 /my-project/vendor/phpunit/phpunit/src/TextUI/TestRunner.php(163): PHPUnit_TextUI_TestRunner->handleConfiguration(Array)
#1 /qa/vendor/phpunit/phpunit/src/TextUI/Command.php(149): PHPUnit_TextUI_TestRunner->doRun(Object(PHPUnit_Framework_TestSuite), Array)
#2 /qa/vendor/phpunit/phpunit/src/TextUI/Command.php(100): PHPUnit_TextUI_Command->run(Array, true)
#3 /qa/vendor/phpunit/phpunit/phpunit(47): PHPUnit_TextUI_Command::main()
#4 {main}
  thrown in /my-project/vendor/phpunit/phpunit/src/TextUI/TestRunner.php on line 1066

Everything is fine when /my-project/vendor/bin/phpunit is used

Robo dependency should be locked to 0.5

Phpqa can't use robo v0.6.

ubuntu@ip-172-31-24-40:~$ phpqa --help
PHP Fatal error:  Call to undefined method Robo\Runner::createApplication() in /home/ubuntu/.composer/vendor/edgedesign/phpqa/phpqa on line 27

psalm fails because of missing config file

Thanks a lot for phpqa!

Sadly i found an problem with the integration of psalm.

#steps to reproduce:

Installation

    - composer global require edgedesign/phpqa --update-no-dev
    - composer global require jakub-onderka/php-parallel-lint jakub-onderka/php-console-highlighter phpstan/phpstan vimeo/psalm friendsofphp/php-cs-fixer
    - mkdir -p public/phpqa
    - PATH="$PATH:$HOME/.composer/vendor/bin/"
    - phpqa --report --analyzedDirs Packages/Application/PackageName --buildDir public/phpqa --tools phploc,phpcpd,phpcs,pdepend,phpmd,phpmetrics,php-cs-fixer,parallel-lint,phpstan,psalm

.phpqa.yml

phpcs:
    standard: PSR2
    # number of allowed errors is compared with warnings+errors, or just errors from checkstyle.xml
    ignoreWarnings: false
    # https://github.com/squizlabs/PHP_CodeSniffer/wiki/Reporting
    reports:
        cli:
            - full
        #file:
            # checkstyle is always included and overriden
            # checkstyle: checkstyle.xml
            # you can include custom reports (https://github.com/wikidi/codesniffer/blob/master/reports/wikidi/Summary.php#L39)
            # ./vendor/owner/package/src/MySummaryReport.php: phpcs-summary.html

php-cs-fixer:
    # http://cs.sensiolabs.org/#usage
    rules: '@PSR2'
    allowRiskyRules: false
    # by default the tool is runned in dry-run mode (no fixers are applied)
    isDryRun: true

phpstan:
    level: 0

phpunit:
    # binary: vendor/bin/phpunit
    binary: bin/phpunit
    # phpunit.xml
    config: Build/BuildEssentials/PhpUnit/UnitTests.xml
    reports:
        file: []
            # log: [junit, tap, json]
            # testdox: [html, text]
            # coverage: [html, clover, crap4j, php, text, xml] # requires XDebug extension

psalm:
    config: .psalm.xml
    deadCode: true
    threads: 5
    showInfo: true

# Php file extensions to parse.
extensions:
    - php

Result

The result is an exit code larger than zero.

Additionally there is an output in the phpqa.html#psalm which is: DOMDocument::load(): I/O warning : failed to load external entity "/builds/projects/public/phpqa/psalm.xml".

The phpqa/pslam.xml does not exist, BUT there is an psalm-phpqa.xml

Maybe you can either point me to the correct config or accept that as an bug.

ignore patterns and pdepends/phpmd and Windows

Pdepends and phpmd have a really painful method of doing ignores

they use the same filter class for their file and then PIPE IT THROUGH REGEX (oh, ick)

https://github.com/pdepend/pdepend/blob/master/src/main/php/PDepend/Input/ExcludePathFilter.php

This makes the current method of creating ignore rules complete break on windows (where filesystemiterator will give you back backslashes to compare against) and makes ignore directories a pain because you need both a singular (ignore /vendor) and plural (ignore vendor/*) to work right

I have a pretty horrible hacked up fixed for this at

https://github.com/auroraeosrose/phpqa/blob/powershell_works/src/IgnoredPaths.php#L28
and
https://github.com/auroraeosrose/phpqa/blob/powershell_works/src/IgnoredPaths.php#L54

it's not entirely ideal (I should have pulled them out into a base helper method that each calls) and it still needs file level support added but it works to do ignores properly

But without some sort of a fix ignores are completely non-usable on windows for these two tools

Add option to bundle jQuery and bootstrap

Our build server (Jenkins) has the security policy that it does not allow loading external resources in it's reports. This means that the jQuery and bootstrap JavaScript and CSS files in the template are blocked, rendering the report broken.

Would it be an idea to add a configuration flag that bundles these assets in the reports so that there are no external dependencies required?

Phpstan extra config values

Phpstan allows for more than just parameters in the phpstan.neon file. For example see phpstan's own phpstan.neon:

includes:
	- ../vendor/phpstan/phpstan-php-parser/extension.neon
	- ../vendor/phpstan/phpstan-phpunit/extension.neon
	- ../vendor/phpstan/phpstan-phpunit/rules.neon
	- ../vendor/phpstan/phpstan-phpunit/strictRules.neon
	- ../vendor/phpstan/phpstan-strict-rules/rules.neon
parameters:
	bootstrap: %rootDir%/tests/phpstan-bootstrap.php
	excludes_analyse:
		- %rootDir%/tests/*/data/*
		- %rootDir%/tests/PHPStan/Analyser/traits/*
		- %rootDir%/tests/notAutoloaded/*
	ignoreErrors:
		- '#Constant PHPSTAN_TEST_CONSTANT not found#'
		- '#Strict comparison using === between PhpParser\\Node\\Expr\\ArrayItem and null will always evaluate to false#'
		- '#Dynamic call to static method PHPUnit\\Framework\\#'
	tmpDir: %rootDir%/tmp
services:
	-
		class: PHPStan\Build\ServiceLocatorDynamicReturnTypeExtension
		tags:
			- phpstan.broker.dynamicMethodReturnTypeExtension

It also has things like includes and services. However phpqa ignores everything that's not in `parameters.

It would be really great if phpqa supported the entire phpstan config because you can do cool things like include phpstan-strict-rules and create custom rules.

phpmetrics menu doesn't work in v2

phpmetrics v2.3.2 menu is

  • Overview
    
  • Violations (4)
    
  • Size & volume
    
  • Complexity & defects
    
  • Object oriented metrics
    
  • Object relations
    
  • Coupling
    

PHP Qa Menu for phpmetrics is

  •     Overview
    
  •     Score
    
  •     Relations map
    
  •     Repartition
    
  •     Explore
    

phpmetrics specific config file

Hi guys,

This is possible to provide a specific .phpmetrics.yml config via .phpqa.yml or other way ?

i need to integrate some rules for phpmetrics like bellow :

default:
    rules:
        cyclomaticComplexity: [ 10, 6, 2 ]
        maintainabilityIndex: [ 0, 75, 95 ]

    failure: average.maintainabilityIndex < 80 or average.bugs >= 1 or average.cyclomaticComplexity >= 4 or average.lcom >= 3

and so it will be awesome to have an aware .phpqa.yml like this :

phpcpd:
    minLines: 5
    minTokens: 70

phpmetrics:
    config: .phpmetrics.yml

thks in advance ;)

Not installable on PHP 7.2

There is a set of uninstallable dependencies:

$ composer global require edgedesign/phpqa --update-no-dev

Results in

Using version ^1.18 for edgedesign/phpqa
./composer.json has been created
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - fabpot/php-cs-fixer v2.0.0 requires php ^5.3.6 || >=7.0 <7.2 -> your PHP version (7.2.2) does not satisfy that requirement.
    - fabpot/php-cs-fixer v2.0.0 requires php ^5.3.6 || >=7.0 <7.2 -> your PHP version (7.2.2) does not satisfy that requirement.
    - fabpot/php-cs-fixer v2.0.0 requires php ^5.3.6 || >=7.0 <7.2 -> your PHP version (7.2.2) does not satisfy that requirement.
    - Installation request for fabpot/php-cs-fixer (locked at v2.0.0) -> satisfiable by fabpot/php-cs-fixer[v2.0.0].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.

Installation failed, deleting ./composer.json.

PHP-Parallel-Lint should support the extensions

It seems that the --extensions arguments is ignored by parallel-linter command, you know better than me that most of the times just "php" extension is not enough, i'll try in the next few days to implement it.

Stdout output

It would be nice to have some switch for not-logging violations into files but print violations to stdout.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.