Making a Check

If you followed the recommended setup, your Checks will be located in ./phecks/Checks.

To make a new Pheck, run:

php artisan make:pheck Jobs/JobClassesMustHaveTheRightSuffixCheck

This command will generate the base of a Check for you.

Checks must implement the interface Juampi92\Phecks\Domain\Contracts\Check.

This is an example of a Pheck:

class JobClassesMustHaveTheRightSuffixCheck implements Check
{
    public function __construct(
        private readonly FileSource $source
    ) {}

    /**
     * Get Matches will fetch and filter all file
     * matches that might be interesting for our Check.
     *
     * In this example, we get the Actions that match a
     * pattern that checks for a class extending another class.
     */
    public function getMatches(): MatchCollection
    {
        return $this->source
            ->directory('./app/Jobs')
            ->recursive()
            ->run();
    }

    /**
     * Process Match will let you return an array of ViolationBuilders.
     *
     * @param FileMatch $match
     */
    public function processMatch($match, FileMatch $file): array
    {
        if ($condition) {
            // If you consider the Match does not need a
            // violation, you can return an empty array.
            return [];
        }

        return [
            ViolationBuilder::make()
                ->message('Explain the problem here.')
                ->setUrl($wikiUrl),
        ];
    }
}

Installing the Check

Now add your check to the array checks in your config file:

config/phecks.php

Remember to clear the config cache to see your changes. php artisan config:clear

Building the Violation

Violations are what describe the error, so it's important they are as descriptive as possible. If the name itself can't be clear enough, consider using a ->setUrl($url) and point that link to an internal Wiki page that documents the error and how to properly fix it.

By default, the violations are assigned to the $file of the Match. Sources will remember the file (and sometimes line) where the match was found, and it will be included in the report whenever is possible.

You can change the file match by using setFile on the ViolationBuilder:

public function processMatch(ReflectionMethod $match, FileMatch $file): array
{
    return [
        ViolationBuilder::make()
            ->message("The method '{$match->getName()}' is not a default CRUD keyword. Try to stick to them or extract to a new controller if you need other actions.")
            ->setFile(new FileMatch(
                (string) $match->getFileName(),
                (int) $match->getStartLine(),
            ))
        ->set,
    ];
}

In the previous example, the ReflectionMethod class is aware of the file and the start line, so you can rely on it instead of the original file match.

Last updated