gdbots/pbjc-php

View on GitHub
src/Composer/ScriptHandler.php

Summary

Maintainability
A
2 hrs
Test Coverage
<?php

namespace Gdbots\Pbjc\Composer;

use Composer\Installer\PackageEvent;
use Composer\Package\PackageInterface;
use Symfony\Component\Filesystem\Filesystem;

class ScriptHandler
{
    /**
     * Auto registers the "pbj-schema-store" repos with the SchemaStore.
     *
     * @param PackageEvent $event
     */
    public static function writePbjSchemaStoresFile(PackageEvent $event)
    {
        if (!$event->isDevMode()) {
            return;
        }

        $dirs = [];
        /** @var PackageInterface $package */
        foreach ($event->getInstalledRepo()->getPackages() as $package) {
            if (!$package instanceof PackageInterface) {
                continue;
            }

            if ('pbj-schema-store' !== $package->getType()) {
                continue;
            }

            $dir = sprintf('$vendorDir.\'/%s/schemas/\'', $package->getName());

            // override for current package
            if ($event->getComposer()->getPackage()->getName() == $package->getName()) {
                $dir = '__DIR__.\'/schemas/\'';
            }

            $dirs[] = sprintf('%s    %s', PHP_EOL, $dir);
        }

        if (empty($dirs)) {
            return;
        }

        $dirs = array_unique($dirs);
        $dirs = implode(',', $dirs);

        $event->getIO()->write('<info>Writing "pbj-schema-store" locations to "pbj-schema-stores.php"</info>');

        $text = <<<TEXT
<?php

/**
 * DO NOT EDIT THIS FILE as it will be overwritten by Composer as part of
 * the installation/update process.
 *
 * Registers all directories from all required packages which are of
 * of the type "pbj-schema-store".
 *
 * This file has been auto-generated by the Pbj Compiler.
 */

\$vendorDir = realpath(__DIR__.'/vendor');

\\Gdbots\\Pbjc\\SchemaStore::addDirs([{$dirs}
]);

TEXT;

        $fs = new Filesystem();
        $fs->dumpFile('pbj-schema-stores.php', $text);
    }
}