/**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace_recursive(self::$defaultOptions, $options);
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/path-mappings.json';
     }
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::boolean($options['optimize'], 'The "optimize" option should be a boolean. Got: %s');
     Assert::isArray($options['change-stream'], 'The "change-stream" option should be an array. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $relBaseDir = Path::makeRelative($options['root-dir'], $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $escBaseDir = $relBaseDir ? '__DIR__.' . var_export('/' . $relBaseDir, true) : '__DIR__';
     if ($options['optimize']) {
         $streamGenerator = $generatorRegistry->getServiceGenerator(GeneratorRegistry::CHANGE_STREAM, $options['change-stream']['type']);
         $streamOptions = $options['change-stream'];
         $streamOptions['root-dir'] = $options['root-dir'];
         $streamGenerator->generateNewInstance('stream', $targetMethod, $generatorRegistry, $streamOptions);
         $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\OptimizedJsonRepository'));
         $targetMethod->addBody(sprintf('$%s = new OptimizedJsonRepository(%s, %s, false, $stream);', $varName, $escPath, $escBaseDir));
     } else {
         $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\JsonRepository'));
         $targetMethod->addBody(sprintf('$%s = new JsonRepository(%s, %s, true);', $varName, $escPath, $escBaseDir));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace(self::$defaultOptions, $options);
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::boolean($options['serialize-strings'], 'The "serialize-strings" option should be a boolean. Got: %s');
     Assert::boolean($options['serialize-arrays'], 'The "serialize-arrays" option should be a boolean. Got: %s');
     Assert::boolean($options['escape-slash'], 'The "escape-slash" option should be a boolean. Got: %s');
     Assert::boolean($options['pretty-print'], 'The "pretty-print" option should be a boolean. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $flags = array();
     if (!$options['serialize-strings']) {
         $flags[] = 'JsonFileStore::NO_SERIALIZE_STRINGS';
     }
     if (!$options['serialize-arrays']) {
         $flags[] = 'JsonFileStore::NO_SERIALIZE_ARRAYS';
     }
     if (!$options['serialize-arrays']) {
         $flags[] = 'JsonFileStore::NO_ESCAPE_SLASH';
     }
     if ($options['pretty-print']) {
         $flags[] = 'JsonFileStore::PRETTY_PRINT';
     }
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\JsonFileStore'));
     $targetMethod->addBody(sprintf('$%s = new JsonFileStore(%s%s%s);', $varName, $flags ? "\n    " : '', '__DIR__.' . var_export('/' . $relPath, true), $flags ? ",\n    " . implode("\n        | ", $flags) . "\n" : ''));
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'rootDir', 'The "rootDir" option is missing.');
     $options = array_replace(self::$defaultOptions, $options);
     $path = Path::makeAbsolute($options['path'], $options['rootDir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\JsonFileStore'));
     $targetMethod->addBody(sprintf('$%s = new JsonFileStore(%s, %s);', $varName, '__DIR__.' . var_export('/' . $relPath, true), $options['cache'] ? 'true' : 'false'));
 }
    protected function putCode($path, Method $method)
    {
        // In the generated class, the repository is passed as argument.
        // Create a repository here so that we can run the code successfully.
        $method->getClass()->addImport(new Import('Puli\\Manager\\Tests\\Factory\\Generator\\Fixtures\\TestRepository'));
        $method->setBody(<<<EOF
\$repo = new TestRepository();
{$method->getBody()}
EOF
);
        parent::putCode($path, $method);
    }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/change-stream.json';
     }
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\ChangeStream\\JsonChangeStream'));
     $targetMethod->addBody(sprintf('$%s = new JsonChangeStream(%s);', $varName, $escPath));
 }
    /**
     * {@inheritdoc}
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
    {
        $options = array_replace(self::$defaultOptions, $options);
        Assert::string($options['host'], 'The host must be a string. Got: %s');
        Assert::integer($options['port'], 'The port must be an integer. Got: %s');
        $escHost = var_export($options['host'], true);
        $escPort = var_export($options['port'], true);
        $targetMethod->getClass()->addImports(array(new Import('Redis'), new Import('Webmozart\\KeyValueStore\\PhpRedisStore')));
        $targetMethod->addBody(<<<EOF
\$client = new Redis();
\$client->connect({$escHost}, {$escPort});
\${$varName} = new PhpRedisStore(\$client);
EOF
);
    }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace_recursive(self::$defaultOptions, $options);
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::isArray($options['store'], 'The "store" option should be an array. Got: %s');
     if (!isset($options['store']['path'])) {
         $options['store']['path'] = $targetMethod->getClass()->getDirectory() . '/change-stream.json';
     }
     $kvsGenerator = $generatorRegistry->getServiceGenerator(GeneratorRegistry::KEY_VALUE_STORE, $options['store']['type']);
     $kvsOptions = $options['store'];
     $kvsOptions['root-dir'] = $options['root-dir'];
     $kvsGenerator->generateNewInstance('store', $targetMethod, $generatorRegistry, $kvsOptions);
     $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\ChangeStream\\KeyValueStoreChangeStream'));
     $targetMethod->addBody(sprintf('$%s = new KeyValueStoreChangeStream($store);', $varName));
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     $options = array_replace_recursive(self::$defaultOptions, $options);
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::isArray($options['store'], 'The "store" option should be an array. Got: %s');
     if (!isset($options['store']['path'])) {
         $options['store']['path'] = $targetMethod->getClass()->getDirectory() . '/bindings.json';
     }
     $kvsGenerator = $generatorRegistry->getServiceGenerator(GeneratorRegistry::KEY_VALUE_STORE, $options['store']['type']);
     $kvsOptions = $options['store'];
     $kvsOptions['root-dir'] = $options['root-dir'];
     $kvsGenerator->generateNewInstance('store', $targetMethod, $generatorRegistry, $kvsOptions);
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\KeyValueStoreDiscovery'));
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\Binding\\Initializer\\ResourceBindingInitializer'));
     $targetMethod->addBody(sprintf("\$%s = new KeyValueStoreDiscovery(\$store, array(\n    new ResourceBindingInitializer(\$repo),\n));", $varName));
 }
    /**
     * {@inheritdoc}
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
    {
        Assert::keyExists($options, 'bucket', 'The "bucket" option is missing.');
        $options = array_replace(self::$defaultOptions, $options);
        Assert::string($options['bucket'], 'The bucket must be a string. Got: %s');
        Assert::string($options['host'], 'The host must be a string. Got: %s');
        Assert::integer($options['port'], 'The port must be an integer. Got: %s');
        $escBucket = var_export($options['bucket'], true);
        $escHost = var_export($options['host'], true);
        $escPort = var_export($options['port'], true);
        $targetMethod->getClass()->addImports(array(new Import('Basho\\Riak\\Riak'), new Import('Webmozart\\KeyValueStore\\RiakStore')));
        $targetMethod->addBody(<<<EOF
\$client = new Riak({$escHost}, {$escPort});
\${$varName} = new RiakStore({$escBucket}, \$client);
EOF
);
    }
    /**
     * {@inheritdoc}
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
    {
        $options = array_replace(self::$defaultOptions, $options);
        Assert::stringNotEmpty($options['host'], 'The "host" option must be a non-empty string. Got: %s');
        Assert::integer($options['port'], 'The "port" option must be an integer. Got: %s');
        $escHost = var_export($options['host'], true);
        $escPort = var_export($options['port'], true);
        $targetMethod->getClass()->addImports(array(new Import('Predis\\Client'), new Import('Webmozart\\KeyValueStore\\PredisStore')));
        $targetMethod->addBody(<<<EOF
\$client = new Client(array(
    'host' => {$escHost},
    'port' => {$escPort},
));
\${$varName} = new PredisStore(\$client);
EOF
);
    }
    /**
     * {@inheritdoc}
     */
    public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
    {
        Assert::keyExists($options, 'rootDir', 'The "rootDir" option is missing.');
        $options = array_replace(self::$defaultOptions, $options);
        if (!isset($options['path'])) {
            $options['path'] = $targetMethod->getClass()->getDirectory() . '/repository';
        }
        Assert::string($options['path'], 'The "path" option should be a string. Got: %s');
        Assert::string($options['rootDir'], 'The "rootDir" option should be a string. Got: %s');
        Assert::boolean($options['symlink'], 'The "symlink" option should be a boolean. Got: %s');
        $path = Path::makeAbsolute($options['path'], $options['rootDir']);
        $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
        $escPath = $relPath ? '__DIR__.' . var_export('/' . $relPath, true) : '__DIR__';
        if ($relPath) {
            $targetMethod->addBody(<<<EOF
if (!file_exists({$escPath})) {
    mkdir({$escPath}, 0777, true);
}

EOF
);
        }
        $targetMethod->getClass()->addImport(new Import('Puli\\Repository\\FilesystemRepository'));
        $targetMethod->addBody(sprintf('$%s = new FilesystemRepository(%s, %s);', $varName, $escPath, var_export($options['symlink'], true)));
    }
 public function addCreateUrlGeneratorMethod(Clazz $class)
 {
     $class->addImport(new Import('Puli\\Discovery\\Api\\ResourceDiscovery'));
     $class->addImport(new Import('Puli\\AssetPlugin\\Api\\Factory\\UrlGeneratorFactory'));
     $class->addImport(new Import('Puli\\AssetPlugin\\Api\\Target\\InstallTargetCollection'));
     $class->addImport(new Import('Puli\\AssetPlugin\\Api\\UrlGenerator\\AssetUrlGenerator'));
     $class->addImport(new Import('Puli\\AssetPlugin\\UrlGenerator\\DiscoveryUrlGenerator'));
     $class->addImplementedInterface('UrlGeneratorFactory');
     $method = new Method('createUrlGenerator');
     $method->setDescription('Creates the URL generator.');
     $arg = new Argument('discovery');
     $arg->setTypeHint('ResourceDiscovery');
     $arg->setType('ResourceDiscovery');
     $arg->setDescription('The resource discovery to read from.');
     $method->addArgument($arg);
     $method->setReturnValue(new ReturnValue('$generator', 'AssetUrlGenerator', 'The created URL generator.'));
     $targets = $this->targetManager->getTargets();
     $targetsString = '';
     foreach ($targets as $target) {
         $parameters = '';
         foreach ($target->getParameterValues() as $name => $value) {
             $parameters .= sprintf("\n        %s => %s,", var_export($name, true), var_export($value, true));
         }
         if ($parameters) {
             $parameters .= "\n    ";
         }
         $targetsString .= sprintf("\n    new InstallTarget(%s, %s, %s, %s, array(%s)),", var_export($target->getName(), true), var_export($target->getInstallerName(), true), var_export($target->getLocation(), true), var_export($target->getUrlFormat(), true), $parameters);
     }
     if ($targetsString) {
         $class->addImport(new Import('Puli\\AssetPlugin\\Api\\Target\\InstallTarget'));
         $targetsString = "array({$targetsString}\n)";
     }
     $method->addBody("\$targets = new InstallTargetCollection({$targetsString});");
     if ($targetsString) {
         $method->addBody("\$targets->setDefaultTarget('{$targets->getDefaultTarget()->getName()}');");
     }
     $method->addBody("\$generator = new DiscoveryUrlGenerator(\$discovery, \$targets);");
     $class->addMethod($method);
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     Assert::keyExists($options, 'root-dir', 'The "root-dir" option is missing.');
     if (!isset($options['path'])) {
         $options['path'] = $targetMethod->getClass()->getDirectory() . '/bindings.json';
     }
     Assert::stringNotEmpty($options['root-dir'], 'The "root-dir" option should be a non-empty string. Got: %s');
     Assert::stringNotEmpty($options['path'], 'The "path" option should be a non-empty string. Got: %s');
     $path = Path::makeAbsolute($options['path'], $options['root-dir']);
     $relPath = Path::makeRelative($path, $targetMethod->getClass()->getDirectory());
     $escPath = '__DIR__.' . var_export('/' . $relPath, true);
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\JsonDiscovery'));
     $targetMethod->getClass()->addImport(new Import('Puli\\Discovery\\Binding\\Initializer\\ResourceBindingInitializer'));
     $targetMethod->addBody(sprintf("\$%s = new JsonDiscovery(%s, array(\n    new ResourceBindingInitializer(\$repo),\n));", $varName, $escPath));
 }
 protected function putCode($path, Method $method)
 {
     $imports = 'use ' . implode(";\nuse ", $method->getClass()->getImports()) . ";\n";
     file_put_contents($path, "<?php\nnamespace Puli\\Test;\n{$imports}\n" . $method->getBody());
     //        echo file_get_contents($path);
 }
Exemple #15
0
 /**
  * Adds the getModuleOrder() method.
  *
  * @param Clazz $class The factory class model.
  */
 public function addGetModuleOrderMethod(Clazz $class)
 {
     $class->addImport(new Import('Puli\\Discovery\\Api\\Discovery'));
     $class->addImport(new Import('Puli\\Manager\\Api\\Server\\ServerCollection'));
     $class->addImport(new Import('Puli\\UrlGenerator\\Api\\UrlGenerator'));
     $class->addImport(new Import('Puli\\UrlGenerator\\DiscoveryUrlGenerator'));
     $class->addImport(new Import('RuntimeException'));
     $method = new Method('getModuleOrder');
     $method->setDescription("Returns the order in which the installed modules should be loaded\naccording to the override statements.");
     $method->setReturnValue(new ReturnValue('$order', 'string[]', 'The sorted module names.'));
     $moduleOrderString = '';
     if (count($this->modules) > 0) {
         $overrideGraph = DependencyGraph::forModules($this->modules);
         foreach ($overrideGraph->getSortedModuleNames() as $moduleName) {
             $moduleOrderString .= sprintf("\n    %s,", var_export($moduleName, true));
         }
         $moduleOrderString .= "\n";
     }
     $method->addBody("\$order = array({$moduleOrderString});");
     $class->addMethod($method);
 }
    public function testWriteMethodWithDocBlockAndReturnValue()
    {
        $method = new Method('doSomething');
        $method->setDescription("The\n  Doc\n    Block");
        $method->setReturnValue(new ReturnValue('42'));
        $this->class->addMethod($method);
        $this->writer->writeClass($this->class);
        $expected = <<<EOF
<?php

class MyClass
{
    /**
     * The
     *   Doc
     *     Block
     *
     * @return mixed
     */
    public function doSomething()
    {
        return 42;
    }
}

EOF;
        $this->assertFileSame($expected, $this->tempDir . '/MyClass.php');
    }
Exemple #17
0
 public function testClearBody()
 {
     $this->method->setBody("\$foo = 'bar';");
     $this->method->clearBody();
     $this->assertSame('', $this->method->getBody());
 }
    /**
     * Adds the createUrlGenerator() method.
     *
     * @param Clazz $class The factory class model.
     */
    public function addCreateUrlGeneratorMethod(Clazz $class)
    {
        $class->addImport(new Import('Puli\\Discovery\\Api\\ResourceDiscovery'));
        $class->addImport(new Import('Puli\\Manager\\Api\\Server\\ServerCollection'));
        $class->addImport(new Import('Puli\\UrlGenerator\\Api\\UrlGenerator'));
        $class->addImport(new Import('Puli\\UrlGenerator\\DiscoveryUrlGenerator'));
        $class->addImport(new Import('RuntimeException'));
        $method = new Method('createUrlGenerator');
        $method->setDescription('Creates the URL generator.');
        $arg = new Argument('discovery');
        $arg->setTypeHint('ResourceDiscovery');
        $arg->setType('ResourceDiscovery');
        $arg->setDescription('The resource discovery to read from.');
        $method->addArgument($arg);
        $method->setReturnValue(new ReturnValue('$generator', 'UrlGenerator', 'The created URL generator.'));
        $method->addBody(<<<EOF
if (!interface_exists('Puli\\UrlGenerator\\Api\\UrlGenerator')) {
    throw new RuntimeException('Please install puli/url-generator to create UrlGenerator instances.');
}

EOF
);
        $urlFormatsString = '';
        foreach ($this->servers as $server) {
            $urlFormatsString .= sprintf("\n    %s => %s,", var_export($server->getName(), true), var_export($server->getUrlFormat(), true));
        }
        if ($urlFormatsString) {
            $urlFormatsString .= "\n";
        }
        $method->addBody("\$generator = new DiscoveryUrlGenerator(\$discovery, array({$urlFormatsString}));");
        $class->addMethod($method);
    }
Exemple #19
0
 /**
  * Adds a method to the class.
  *
  * @param Method $method The method to add to the class.
  *
  * @return static The current instance.
  */
 public function addMethod(Method $method)
 {
     if (isset($this->methods[$method->getName()])) {
         throw new RuntimeException(sprintf('The method "%s" exists already.', $method->getName()));
     }
     $this->methods[$method->getName()] = $method;
     $method->setClass($this);
     return $this;
 }
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\ArrayStore'));
     $targetMethod->addBody('$' . $varName . ' = new ArrayStore();');
 }
Exemple #21
0
 /**
  * {@inheritdoc}
  */
 public function generateNewInstance($varName, Method $targetMethod, GeneratorRegistry $generatorRegistry, array $options = array())
 {
     $targetMethod->getClass()->addImport(new Import('Webmozart\\KeyValueStore\\NullStore'));
     $targetMethod->addBody(sprintf('$%s = new NullStore();', $varName));
 }