Hello phpstan-sylius extension
In preparation for the Sylius hackathon last week in Cologne, I wondered what project I could work on. I had a few topics on my mind. In the end, I decided to work on a PHPStan extension for Sylius.
Why that? Since Sylius is based on Symfony, isn't it enough to use the phpstan-symfony extension? Of course, this will give you some good base results, but this extension doesn't understand the Sylius specifics. So there's room for more.
My goal was to come up with PHPStan rules for the two base components of Sylius: The Resource bundle and the Grid bundle.
What issues can the extension detect? Let's take the following code into account to configure a Grid instance:
<?php
declare(strict_types=1);
namespace App\Grid;
use App\Entity\Supplier;
use Sylius\Bundle\GridBundle\Builder\GridBuilderInterface;
use Sylius\Bundle\GridBundle\Grid\AbstractGrid;
use Sylius\Bundle\GridBundle\Grid\ResourceAwareGridInterface;
final class AdminSupplierGrid extends AbstractGrid implements ResourceAwareGridInterface
{
public static function getName(): string
{
return 'app_admin_supplier';
}
public function buildGrid(GridBuilderInterface $gridBuilder): void
{
// ...
}
public function getResourceClass(): string
{
return Supplier::class;
}
}
The grid is connected to the Supplier
resource class. Does the class exist? Is it really a resource class, as Sylius needs it? This is where the extension can be of help.
But even better, let's assume you want to configure your grid in the buildGrid()
method like this:
public function buildGrid(GridBuilderInterface $gridBuilder): void
{
$gridBuilder->addField(
StringField::create('name')->setLabel('app.ui.name')
);
$gridBuilder->addFilter(
Filter::create('company', 'string')
);
}
Are the name
and company
properties part of the Supplier
class? The extension will check this and report any errors.
And given you want to link your resource class to a grid via the #Index
attribute, the extension will also check if the grid class exists as part of your code base:
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Grid\AdminSupplierGrid;
use Sylius\Resource\Metadata\AsResource;
use Sylius\Resource\Metadata\Index;
use Sylius\Resource\Model\ResourceInterface;
#[AsResource]
#[Index(grid: AdminSupplierGrid::class)]
class Supplier implements ResourceInterface
{
private int $id;
public function getId(): int
{
return $this->id;
}
}
If the AdminSupplierGrid
class can't be found, PHPStan will error.
Here's the catch: The extension prototype is currently only working with the Attribute configuration and expects the grid to be configured via code. In the next step, the extension should also understand the YAML configuration and take that into account when evaluating these rules.
Want to give it a try? Grab it from GitHub. If you like the work, let me know.