MBrownieBytes

A blog for software engineers, sys admins, devops, and the technically inclined.
How to guides, Tutorials, Tips and Tricks

  1. You are here:  
  2. Home

Blog

PHPStan - static analysis of PHP code

Details
Published: 21 March 2022
  • php
  • devops

PHPStan - static analysis of PHP code

'PHPStan finds bugs in your code without writing tests.'
https://phpstan.org/

PHPStan performs static code analysis on your code.

Static analysis is the method of testing your code for basic logical, runtime or typographical exceptions without actually executing the code or accessing external services like databases

Static analysis of your codebase happens relatively fast since the code doesn't actually get executed but scanned for common errors, like having a method that doesn't return the expected date type.

PHPStan checks for a couple of language constructs such as use of instanceof, try-catch blocks, typehints, number of arguments passed to a function, accessibility of called methods and variables, and many more.

Install PHPStan

> composer require --dev phpstan/phpstan


Add helper script commands to composer.json

    "scripts": {

        "phpstan-dev": "php vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=1G",

        "phpstan-ci": "php vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=1G --no-progress",

...

    }

 

-c:
The configuration file phpstan.neon allows you to commit additional options for your project

--memory-limit=1G:
argument is to suppress a common false warning on runs which suggests that the errors are due to a memory limit;  projects often only consume tens to a couple hundreds of MB.

--no-progress:
omits the progress bar which could be useful for Continuous Integration runs.

Configuration

PHPStan makes use of the neon file format for its configuration, which is yaml like. 

An example configuration file, phpstan.neon:

# https://phpstan.org/config-reference
parameters:

    # https://phpstan.org/user-guide/rule-levels
    level: 8

    # code paths
    paths:
        - cfg
        - public
        - src
    excludePaths:
        analyse:
            - vendor
    tmpDir: tmp
    # https://phpstan.org/config-reference#vague-typehints
    checkMissingIterableValueType: false

    checkGenericClassInNonGenericObjectType: false
    # btr if true, but false allows changing level w/o errors
    reportUnmatchedIgnoredErrors: true
    ignoreErrors:
        - '#Negated boolean expression is always true\.#'
        - '#If condition is always false\.#'
...

level:
indicates how many tests to run
https://phpstan.org/user-guide/rule-levels

paths: 
should point to your code

excludePaths:
should exclude code you are not responsible for, such as vendor

tmpDir: 
if not set will use your default os tmp dir, but setting to a local tmp allows for easier cleanup, observation

ignoreErrors:
allows common code patterns in your project to be ignored by PHPStan
https://phpstan.org/user-guide/ignoring-errors
This should be used minimally, but may be necessary depending on your code.  It can also be used when adding PHPStan to an existing project with lots of errors and you want to ease PHPStan into your workflow.

reportUnmatchedIgnoredErrors:
shows you if you have any unused ignoreError expressions

 

Run PHPStan

Run using composer

> php composer phpstan-dev

php vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=1G

...

------------------------------------------------------------------------------

  Line   src\Your\Service\AService.php

------------------------------------------------------------------------------

  15     Property App\Your\Service\AService::$aDomain has no typehint specified.

------------------------------------------------------------------------------

...

 [ERROR] Found 214 errors

 115/115 [============================] 100%

Script php vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=1G handling the phpstan event returned with error code 1

 

Now the 'fun' begins.  The errors list the file name, method, and line number.  Go through all the reported errors and 'fix' them increasing code quality, and sometimes functionality; and only if necessary, add the error(s) to the ignore list.

Work toward the goal of no reported errors

 

> php composer phpstan-dev

php vendor/bin/phpstan analyse -c phpstan.neon --memory-limit=1G

 115/115 [============================] 100%

 [OK] No errors

 

Now celebrate!

And before every Push, Pull/Merge Request, run PHPStan.

Sounds like a good job for git hooks or CI huh?

 

-End of Document-

Thanks for reading

Enable PHP 8 xdebug from the command line

Details
Published: 21 February 2022
  • php

 "Xdebug is an extension for PHP, and provides a range of features to improve the PHP development experience. Step Debugging A way to step through your code in your IDE or editor while the script is executing."

Source: https://xdebug.org/ 

Install following the instructions from https://xdebug.org/docs/install

Note, PHP 8 settings are different than earlier versions of PHP, xdebug
For PHP 7 settings, see the prior post 
Enable PHP xdebug from the command line 

Download and place the xdebug extension in php\ext
C:\laragon8\bin\php\php-8.0.11-Win32-vs16-x64\ext

Configure your PHP 8 php.ini settings:

zend_extension=xdebug-3.0.4-8.0-vs16-x86_64

[xdebug]
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9081
xdebug.idekey=PHPSTORM 

Note, if you use xdebug.start_with_request=trigger, this may be more efficient for large code paths as xdebug should only be started when you send a request with XDEBUG_SESSION set, which can be set via xdebug helper for chrome or xdebug helper for firefox


You can also add arguments to your PHP call

> php -d -dxdebug.mode=debug -dxdebug.start_with_request=yes -dxdebug.client_host=127.0.0.1 -dxdebug.client_port=9081 -dxdebug.idekey=PHPSTORM your/script.php

The option -d can set/override php.ini values

-d foo[=bar]     Define INI entry foo with value 'bar'
Reference: https://www.php.net/manual/en/features.commandline.options.php


If you are using the conemu console you can add the alias to your settings -> startup -> environment

alias xphp8=C:/laragon80/bin/php/php-8.0.11-Win32-vs16-x64/php -dxdebug.mode=debug -dxdebug.start_with_request=yes -dxdebug.client_host=127.0.0.1 -dxdebug.client_port=9081 -dxdebug.idekey=PHPSTORM $*

alias php8=C:/laragon80/bin/php/php-8.0.11-Win32-vs16-x64/php $*

If you are using git for windows, which adds bash, you can add the same aliases
Edit your .bashrc
C:\Users\[youruser]\.bashrc

alias xphp8="C:/laragon80/bin/php/php-8.0.11-Win32-vs16-x64/php -dxdebug.mode=debug -dxdebug.start_with_request=yes -dxdebug.client_host=127.0.0.1 -dxdebug.client_port=9081 -dxdebug.idekey=PHPSTORM $*"

alias php8="C:/laragon80/bin/php/php-8.0.11-Win32-vs16-x64/php $*"

 

And use as

> xphp8 slimapp/cli.php arg1 arg2=test

Reference:Slim PHP CLI

-End of Document-
Thanks for reading

App breaks out of Cypress test run frame

Details
Published: 24 January 2022
  • reactjs
  • cypress
Cypress is a end-to-end testing framework which is fast, easy and reliable testing for anything that runs in a browser.
https://www.cypress.io/
Cypress version: 8.3.0
 
When using Cypress with ReactJS, you may run into a scenario where the tests run the first time, but subsequent tests break out of the Cypress tests run frame; and just shows your app, or your apps loading indicator.  So your tests stop.  
 
While clearing the Cypress cache fixes the tests for the next run, there should be a better solution.
https://docs.cypress.io/guides/getting-started/installing-cypress#Binary-cache
 
In the developers tools, if you enable preserve logs for the console and network, you may see a redirect to `__`
 
Some searching for `cypress redirects to __` will lead you to
 
'Cypress test runner redirects to __ suddenly'
https://github.com/cypress-io/cypress/issues/1064#issuecomment-351462579
 
which suggests adding 
`
Cypress.on('window:before:load', (win) => {
      Object.defineProperty(win, 'self', {
            get: () => {
                return window.top
            }
        })
});
`
 
To add to your Cypress config,
assuming in `cypress.json` you have your support dir set to 
"supportFile": "[app-product]/support",
 
add the suggestion to a file
support/callbacks/fix_iframe_redirects.js
 
and in the support/index.js,
reference the file
import './callbacks/fix_iframe_redirects';
 
You may have to force refresh the Cypress browser, or clear the Cypress cache once more.
 
Additional config to check for:
While this seems to be the default, if you happen to be using an ejected Webpack config, also check that `navigateFallbackWhitelist` is set to check for `__`.  
 
...
new SWPrecacheWebpackPlugin({
...
navigateFallback: publicUrl + "/index.html",
navigateFallbackWhitelist: [/^(?!\/__).*/]
});
 
 
You may also encounter the generic error:
TypeError: Cannot set property name of  which has only a getter
 
Unfortunately, it seems that you can either delete the Cypress cache each time, or disable Chrome web security
tests/cypress/cypress.json
    "chromeWebSecurity": false,
 
With these changes, your Cypress tests should stay framed and run as expected.
 
 
-End of Document-
Thanks for reading 
 
 

Windows Development Software - Tweaks

Details
Published: 06 December 2021
  • windows
  • tweaks

This is a series of posts which will list some useful apps for development and general usage of Windows. These are just some examples of what can be useful. Of course, use any app you already know or have.

 

tweak windows:

Open Shell

https://github.com/Open-Shell/Open-Shell-Menu

Start menu replacement with Classic style Start Menu for Windows 7, 8, 8.1, 10 and Toolbar for Windows Explorer



Winaero Tweaker

https://winaerotweaker.com/

Winaero Tweaker is a freeware app, all-in-one application that comes with dozens of options for fine-grained tuning of various Windows settings and features.



O&O ShutUp10

https://www.oo-software.com/en/shutup10

O&O ShutUp10 means you have full control over which comfort functions under Windows 10 you wish to use, and you decide when the passing on of your data goes too far. Using a very simple interface, you decide how Windows 10 should respect your privacy by deciding which unwanted functions should be deactivated.


 

-End of Document-
Thanks for reading 
  1. Windows Development Software - Maintenance/Security/Utilities
  2. Windows Development Software - Code Editor, IDE

Page 3 of 21

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

Search

Tags

php 21 git 10 windows 10 aws 9 nodejs 7 security 6 virtualbox 6 android 5 portable 4 redhat 4 ubuntu 4 react native 3 reactjs 3 docker 3 devops 3 nginx 3 bash 3 symfony 3 apache 3 ide 2

Most Read Posts

  • Handle HTTP 302 response from proxy in Angular
  • PHPUnit exceeds memory limit
  • Adding camera api to react native
  • Portable Java
  • Clear out old MSMQ messages

Older Posts

  • HDMI and Display Port versions
  • Useful Linux Commands
  • DevOps SysAdmin Tips for researching a slow or unresponsive app or system
  • DDEV for local development in containers
  • Valid local self signed certs
  • Bash script to delete merged local git branches
My Blog