Be Strict! PhpSpec 2 Best Practices Extension Just Released!

logo
image source: phpspec.net. Disclaimer: I have no affiliation with the creators of phpspec. I am just a user giving an opinion.

I just ran into a nice feature left out in the issues of phpspec and couldn’t resist to create my extension for it.

The trend is more and more generating final classes, this can be quickly achieved by a template under .phpspec folder. However, why do we want to copy paste templates all over the place? It makes little sense if in our projects we have determined to a strict adherence to better practices.

So I adapted my extension from the previous blog post and added a way to override completely with templates located on the extension itself.

<?php
 
namespace Cordoval\BestPractices\PhpSpec;
 
use PhpSpec\Extension\ExtensionInterface;
use PhpSpec\ServiceContainer;
 
class BestPracticesExtension implements ExtensionInterface
{
    /**
     * @param ServiceContainer $container
     */
    public function load(ServiceContainer $container)
    {
        $container->setShared('code_generator.generators.specification', function (ServiceContainer $c) {
            return new ClassNotationSpecificationGenerator(
                $c->get('console.io'),
                $c->get('code_generator.templates')
            );
        });
 
        $container->setParam('code_generator.templates.paths', array(
            rtrim(__DIR__, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'.phpspec',
        ));
    }
}

The way it is achieved is the following. PhpSpec has a way to override certain parameters. The template render mechanism first tries to use the renderer to get some content string rendered, if it is not found or the result is null then it moves into the default phpspec templates. So it first tries to check local project templates and under your home directory, and then it falls back to the phpspec package templates. To just lock the templates into our extension templates location we just override this parameter with our __DIR__/.phpspec location in our extension. Then just place the templates we want to override there and that is it.

We are very opinionated so here is the resultant package: cordoval/best-practice-extension

All you need is:

    // ...
    "cordoval/best-practice-extension": "~1.0@dev"
    "phpspec/phpspec": "~2.1@dev",
    // ...

Yeah, they don’t tag the package that often and we have templates moving after 2.0.1, sometimes we need help to follow best practices too :). So in any case with those requires you get it.

Then just add it to your phpspec.yml

extensions:
    - Cordoval\BestPractices\PhpSpec\BestPracticesExtension

And generate away! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *