• This repository has been archived on 01/Nov/2022
  • Stars
    star
    261
  • Rank 156,630 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🚫 ✨ ❗ AOP-based strict type checks for PHP

StrictPhp

Build Status Scrutinizer Code Quality Code Coverage

StrictPhp is a development tool aimed at bringing stricter runtime assertions into PHP applications and libraries.

Authors

Installation

$ composer require roave/strict-php

Please note that the current version has unstable dependencies.

In order to install those dependencies, you can set "minimum-stability" in your composer.json:

{
    "minimum-stability": "dev"
}

Usage

After installing StrictPhp, point it at the directory to be checked at runtime (the code that you are writing) via following code:

\StrictPhp\StrictPhpKernel::bootstrap([
    'debug'        => true,
    // change this if you use this tool on multiple projects:
    'cacheDir'     => sys_get_temp_dir(),
    'includePaths' => [
        __DIR__ . '/path/to/your/sources',
    ],
]);

StrictPhp will then intercept any runtime operations that are considered "illegal" and throw an exception or a catchable fatal error.

Please remember to execute this code before any code that may autoload any of the classes that should be checked.

Configuration

The StrictPhp\StrictPhpKernel can be initialized with a set of options to be passed to go-aop-php and a set of feature flags:

  • StrictPhp\StrictPhpKernel::CHECK_STATE_AFTER_CONSTRUCTOR_CALL
  • StrictPhp\StrictPhpKernel::JAIL_PUBLIC_METHOD_PARAMETERS
  • StrictPhp\StrictPhpKernel::CHECK_STATE_AFTER_PUBLIC_METHOD_CALL
  • StrictPhp\StrictPhpKernel::CHECK_PUBLIC_METHOD_PARAMETER_TYPE
  • StrictPhp\StrictPhpKernel::CHECK_PUBLIC_METHOD_RETURN_TYPE
  • StrictPhp\StrictPhpKernel::CHECK_PROPERTY_WRITE_IMMUTABILITY
  • StrictPhp\StrictPhpKernel::CHECK_PROPERTY_WRITE_TYPE

Each of these features are described below.

Features

StrictPhp currently supports following features:

Per-property type checks

Enabled via flag StrictPhp\StrictPhpKernel::CHECK_PROPERTY_WRITE_TYPE.

This feature will prevent your application from assigning illegal values to properties that are type-hinted (via docblock) differently. As an example, consider following class:

class Example
{
    /**
     * @var int|null
     */
    public $integer;
}

Following code will work:

$object = new Example();

$object->integer = 123;

Following code will crash:

$object = new Example();

$object->integer = '123';

Please note that this kind of feature currently only works with public and protected properties.

Return type checks

Quite similar to the above functionality, this feature will prevent your application from returning illegal values from methods that are type-hinted (via docblock) differently. As an example, consider following method:

class Example
{
    /**
     * @return string
     */
    public function dummyReturn($value)
    {
        return $value;
    }
}

Following code will work:

(new Example())->dummyReturn('string');

Following code will crash:

(new Example())->dummyReturn(123);

Please note that this kind of feature currently only works with public and protected methods.

immutable properties

Enabled via flag StrictPhp\StrictPhpKernel::CHECK_PROPERTY_WRITE_IMMUTABILITY.

This feature will prevent your application from overwriting object properties that are marked as @immutable. As an example, consider following class:

class Example
{
    /**
     * @immutable
     */
    public $immutableProperty;
}

Following code will crash:

$object = new Example();

$object->immutableProperty = 'a value';

echo 'Works till here!';

$object->immutableProperty = 'another value'; // crash

Please note that this kind of feature currently only works with public and protected properties.

Public constructor property initialization checks

Enabled via flag StrictPhp\StrictPhpKernel::CHECK_STATE_AFTER_CONSTRUCTOR_CALL.

This feature of StrictPhp allows checking whether a public constructor of a class fully initialized an object.

Following code will make StrictPhp crash your application:

class Example
{
    /**
     * @var array
     */
    private $arrayProperty;

    public function __construct()
    {
    }
}

In order to make this code work, you have to either annotate $arrayProperty with @var array|null, or make the constructor initialize the property correctly:

class Example
{
    /**
     * @var array
     */
    private $arrayProperty;

    public function __construct()
    {
        $this->arrayProperty = ['initial status'];
    }
}

Parameter interface jailing

Enabled via flag StrictPhp\StrictPhpKernel::JAIL_PUBLIC_METHOD_PARAMETERS.

This feature of StrictPhp "jails" (restricts) calls to non-interfaced methods whenever an interface is used as a type-hint.

Following example will work, but will crash if StrictPhp is enabled:

interface HornInterface
{
    public function honk();
}

class TheUsualHorn implements HornInterface
{
    public function honk() { var_dump('honk'); }
    public function sadTrombone() { var_dump('pooapooapooapoaaaa'); }
}

class Car
{
    public function honk(HornInterface $horn, $sad = false)
    {
        if ($sad) {
            // method not covered by interface: crash
            $horn->sadTrombone();

            return;
        }

        // interface respected
        $horn->honk();
    }
}
$car  = new Car();
$horn = new TheUsualHorn();

$car->honk($horn, false); // works
$car->honk($horn, true); // crashes

This prevents consumers of your APIs to design their code against non-API methods.

Parameter checking

Enabled via flag StrictPhp\StrictPhpKernel::CHECK_PUBLIC_METHOD_PARAMETER_TYPE.

StrictPhp also provides a way to check parameters types in more detail during public method calls.

Specifically, the following code will work in PHP:

final class Invoice
{
    /**
     * @param LineItem[] $lineItems
     */
    public function __construct(array $lineItems)
    {
        // ...
    }
}

$invoice = new Invoice(['foo', 'bar']);

This code will crash in StrictPhp due to the type mismatch in $lineItems (which should be a collection of LineItem objects instead).

Current limitations

This package uses voodoo magic to operate, specifically go-aop-php.

Go AOP PHP has some limitations when it comes to intercepting access to private class members, so please be aware that it has limited scope (for now).

This package only works against autoloaded classes; classes that aren't handled by an autoloader cannot be rectified by StrictPhp.

License

This package is released under the MIT license.

Contributing

If you wish to contribute to the project, please read the CONTRIBUTING notes.

More Repositories

1

SecurityAdvisories

🔐 Security advisories as a simple composer exclusion list, updated daily
2,694
star
2

BetterReflection

🔮 Better Reflection is a reflection API that aims to improve and provide more features than PHP's built-in reflection API.
PHP
1,176
star
3

BackwardCompatibilityCheck

🆎 Tool to compare two revisions of a class API to check for BC breaks
PHP
568
star
4

no-leaks

🚰 PHPUnit Plugin for detecting Memory Leaks in code and tests
PHP
496
star
5

Dont

🚫 Small set of defensive programming utilities/traits for PHP
PHP
400
star
6

you-are-using-it-wrong

🚔 Type check enforcement for library authors: enforces type-safety downstream
PHP
237
star
7

no-floaters

🔎 static analysis rules to prevent IEEE-754 floating point errors
PHP
207
star
8

FunctionFQNReplacer

PHP
158
star
9

infection-static-analysis-plugin

✅ 🐲 Static analysis on top of mutation testing - prevents escaped mutants from being invalid according to static analysis
PHP
121
star
10

psr-container-doctrine

Doctrine Factories for PSR-11 Containers
PHP
95
star
11

shorty

An asynchronous SMPP client and server built on Node.js. Shorty is sponsored and maintained by SMS Cloud, a subsidiary of Roave
JavaScript
92
star
12

DoctrineSimpleCache

Doctrine Cache adapter for PSR-16 Simple Cache
PHP
57
star
13

DocbookTool

📚 Docbook Tool for static documentation generation from Markdown files
PHP
53
star
14

Signature

✒️ Generate and verify basic signature for classes
PHP
43
star
15

behat-psr11extension

PSR-11 Container extension for Behat
PHP
40
star
16

composer-gpg-verify

🔐 📦 composer plugin to enforce GPG signatures on downloaded GIT composer packages
PHP
39
star
17

zf2-for-1

Enables using Zend Framework 2 features in a Zend Framework 1 application.
PHP
34
star
18

RoaveDeveloperTools

A PHP application visualization/debugging tool for ZendFramework/Symfony
PHP
29
star
19

psalm-html-output

Psalm HTML output format
XSLT
21
star
20

issues

Dead simple issue tracker (think standalone Github issues clone)
PHP
19
star
21

billing

open source php billing and invoicing
PHP
16
star
22

EmailTemplates

PHP
14
star
23

SecurityAdvisoriesBuilder

🔨 Build tools responsible for assembling https://github.com/Roave/SecurityAdvisories/blob/master/composer.json
PHP
10
star
24

RoaveDbCriteria

Use Doctrine Collections expressions with Zend\Db\Sql for smart criteria / filtering / query building.
PHP
6
star
25

NonceUtility

PHP
5
star
26

Assistant

Browser-based virtual assistant framework.
JavaScript
5
star
27

LaravelInfinidash

AWS Infinidash integration for Laravel applications
4
star
28

MtdTimeTracker

Simple time tracker
PHP
4
star
29

zf1-migration

Enables using newer Zend Framework features in a Zend Framework 1 application for easier migration.
PHP
3
star
30

tickets

Ticket thingy
PHP
2
star
31

roave.github.io

The Roave website.
JavaScript
2
star
32

roave.com

Roave.com website
CSS
2
star
33

DPC-Tutorial

ZF2 DPC Tutorial
PHP
2
star
34

Phlam

PHP Lambda runnner for running functions as a service on AWS
2
star
35

RoaveBot

Out little IRC campanion for #roave on Freenode.
CoffeeScript
2
star
36

RoaveTrack

This repository will somehow solve all of Roave's operational needs one day.
1
star
37

Realpath

Realpath, yo!
PHP
1
star
38

smscloud-shorty

Shorty implementation used by SMS Cloud in production.
JavaScript
1
star
39

roave.com-gh

New design for Roave.com
1
star
40

RoaveCast

Experiment(s) in real-time video/audio broadcasting to browsers.
1
star
41

demo-automatic-releases

Nothing to see here: we're just playing with github hooks
1
star