ebln/phpstan-factory-rule

PHPStan rule to enforce instanciation by factories

Installs: 14 717

Dependents: 0

Suggesters: 0

Security: 0

Stars: 3

Watchers: 1

Forks: 0

Open Issues: 1

Type:phpstan-extension

0.0.1 2021-11-12 19:38 UTC

This package is not auto-updated.

Last update: 2024-05-12 06:13:58 UTC


README

Enforce that your classes get only instantiated by the factories you define!

Usage

Install this package and the marking package alongside with PHPStan.

Implement \Ebln\PHPStan\EnforceFactory\ForceFactoryInterface with the DTO you want to protect.

<?php
// […]
use Ebln\PHPStan\EnforceFactory\ForceFactoryInterface;

class OnlyViaFactory implements ForceFactoryInterface
{
    // […]
    public static function getFactories(): array
    {   // Return a list of classes that are allowed to
        //   create new OnlyViaFactory instances…
        return [TheOnlyTrueFactory::class];
    }
}

Now rely on PHPStan in CI pipelines, git hooks or IDE integrations.

If somebody introduces a rogue factory:

<?php
// […]

class FailingFactory
{
    public function create(): OnlyViaFactory
    {   
        return new OnlyViaFactory();
    }
}

…that is supposed to fail, when you run PHPStan.

Installation

Require this extention and the package containing the interface via Composer:

composer require ebln/phpstan-factory-mark && composer require --dev ebln/phpstan-factory-rule

If you also install phpstan/extension-installer then you're all set!

Manual installation

If you don't want to use phpstan/extension-installer, just specify the rule in your project's PHPStan config:

rules:
    - \Ebln\PHPStan\EnforceFactory\ForceFactoryRule