public function generateNode()
 {
     $factory = new BuilderFactory();
     $class = $factory->class($this->_interfaceApiDefinition->name)->extend('AbstractInterface');
     foreach ($this->_interfaceApiDefinition->methods as $methodApiDefinition) {
         $docComment = '/**' . "\n" . ' * ' . implode('/', array('', $this->_interfaceApiDefinition->name, $methodApiDefinition->name, 'v' . $methodApiDefinition->version, '')) . "\n" . ' *' . "\n";
         $methodParams = array();
         $arrayItems = array();
         foreach ($methodApiDefinition->parameters as $parameterApiDefinition) {
             $parameterName = $this->_escapeVariableName($parameterApiDefinition->name);
             if ($parameterApiDefinition->name !== 'key') {
                 $methodParam = $factory->param($parameterName);
                 if ($parameterApiDefinition->optional !== false) {
                     $methodParam->setDefault(null);
                 }
                 $methodParams[] = $methodParam;
                 $arrayItems[] = new Node\Expr\ArrayItem(new Node\Expr\Variable($parameterName), new Node\Scalar\String_($parameterApiDefinition->name));
                 $docComment .= ' * @param ' . $parameterApiDefinition->type . ' $' . $parameterName;
                 if (isset($parameterApiDefinition->description) && $parameterApiDefinition->description !== '') {
                     $docComment .= ' ' . $parameterApiDefinition->description;
                 }
                 $docComment .= "\n";
             }
         }
         $docComment .= ' */';
         $method = $factory->method($methodApiDefinition->name . 'V' . $methodApiDefinition->version)->makePublic()->addStmt(new Node\Stmt\Return_(new Node\Expr\MethodCall(new Node\Expr\Variable('this'), '_call', array(new Node\Scalar\MagicConst\Method(), new Node\Scalar\String_($methodApiDefinition->httpmethod), new Node\Expr\Array_($arrayItems)))));
         foreach ($methodParams as $methodParam) {
             $method->addParam($methodParam);
         }
         $method->setDocComment($docComment);
         $class->addStmt($method);
     }
     $node = $factory->namespace(self::INTERFACE_NAMESPACE)->addStmt($factory->use('Zyberspace\\SteamWebApi\\AbstractInterface'))->addStmt($class)->getNode();
     return $node;
 }
 /**
  * Generates code
  */
 function it_generates_code(File $file, PrettyPrinterAbstract $printer)
 {
     $factory = new BuilderFactory();
     $file->getNamespaces()->willReturn([new PHPNamespace('test')]);
     $printer->prettyPrintFile([$factory->namespace('test')->getNode()])->willReturn('foo')->shouldBeCalled();
     $this->generate($file)->shouldReturn('foo');
 }
Example #3
0
 /**
  * @return Builder\Class_
  * @throws Exception\DomainException
  */
 private function compileClass()
 {
     $definitions = $this->definitions;
     $class = $this->builderFactory->class($this->class)->extend('CompiledContainer');
     $mapNodes = array();
     foreach ($definitions as $definition) {
         if ($definition instanceof Definition\AliasDefinition) {
             $alias = Utils::resolveAlias($this->definitions, $definition, false);
             $mapNodes[] = new Node\Expr\ArrayItem(new Node\Scalar\String_($alias->getIdentifier()), new Node\Scalar\String_($definition->getKey()));
         } else {
             if ($definition instanceof Definition\InterfaceDefinition) {
                 // ignore
             } else {
                 if (!$definition->isFactory()) {
                     $class->addStmt($property = $this->builderFactory->property($definition->getIdentifier())->makePrivate()->setDocComment('/**
                                           * @var ' . $definition->getTypeHint() . '
                                           */'));
                 }
                 $identifier = $definition->getIdentifier();
                 // Add method
                 $class->addStmt($this->compileDefinition($definition));
                 // Add map entry
                 $mapNodes[] = new Node\Expr\ArrayItem(new Node\Scalar\String_($identifier), new Node\Scalar\String_($definition->getKey()));
             }
         }
     }
     $class->addStmt($this->builderFactory->property('map')->makeProtected()->makeStatic()->setDefault(new Node\Expr\Array_($mapNodes))->setDocComment('/**
                               * @var array
                               */'));
     return $class;
 }
Example #4
0
 /**
  * Convert a ClassModel into an array of statements for the php parser
  *
  * @param ClassModel $classModel
  * @return array
  */
 public function transform(ClassModel $classModel)
 {
     // create namespace
     $namespace = $this->factory->namespace($classModel->getNamespace());
     // create class
     $class = $this->factory->class($classModel->getName());
     $class->implement($classModel->getInterface());
     // add class properties
     foreach ($classModel->getProperties() as $propertyModel) {
         $property = $this->factory->property($propertyModel->getName());
         $property->setDefault($propertyModel->getDefaultValue());
         switch ($propertyModel->getVisibility()) {
             case PropertyModel::VISIBILITY_PUBLIC:
                 $property->makePublic();
                 break;
             case PropertyModel::VISIBILITY_PROTECTED:
                 $property->makeProtected();
                 break;
             case PropertyModel::VISIBILITY_PRIVATE:
                 $property->makePrivate();
                 break;
             default:
                 throw new UnexpectedValueException('Property visibility must be public, protected, private');
         }
         // add property to class
         $class->addStmt($property);
     }
     // add class methods
     foreach ($classModel->getMethods() as $methodModel) {
         $method = $this->factory->method($methodModel->getName());
         $method->makePublic();
         // add method body
         $body = '<?php ' . $methodModel->getBody();
         $methodStatements = $this->parser->parse($body);
         if (null !== $methodStatements) {
             $methodStatements = $this->nodeTraverser->traverse($methodStatements);
             $method->addStmts($methodStatements);
         }
         // add method parameters
         foreach ($methodModel->getParameters() as $parameterModel) {
             $parameter = $this->factory->param($parameterModel->getName());
             if ($parameterModel->hasTypeHint()) {
                 $parameter->setTypeHint($parameterModel->getTypeHint());
             }
             if ($parameterModel->isOptional()) {
                 $parameter->setDefault($parameterModel->getDefaultValue());
             }
             $method->addParam($parameter);
         }
         // add method to class
         $class->addStmt($method);
     }
     // add class to namespace
     $namespace->addStmt($class);
     // return an array of statements
     return [$namespace->getNode()];
 }
 /**
  * @{inheritDoc}
  */
 public function getMethod()
 {
     $method = $this->factory->method($this->methodName);
     if (count($this->statements) > 0) {
         foreach ($this->statements as $statement) {
             $method->addStmt($statement);
         }
     }
     return $method;
 }
Example #6
0
 protected function generateClass($group, $operations, $namespace, Context $context, $suffix = 'Resource')
 {
     $factory = new BuilderFactory();
     $name = $group === 0 ? '' : $group;
     $class = $factory->class(Inflector::classify($name . $suffix));
     $class->extend('Resource');
     foreach ($operations as $operation) {
         $class->addStmt($this->operationGenerator->generate($this->operationNaming->generateFunctionName($operation), $operation, $context));
     }
     return $factory->namespace($namespace . "\\Resource")->addStmt($factory->use('Joli\\Jane\\Swagger\\Client\\QueryParam'))->addStmt($factory->use('Joli\\Jane\\Swagger\\Client\\Resource'))->addStmt($class)->getNode();
 }
Example #7
0
 /**
  * Function to put routes in PHP Classes
  * @return type
  */
 private function createClass()
 {
     $fs = new Filesystem();
     $directory = $this->getPathPHP();
     $path = $this->getPathClass();
     if (!$fs->exists($directory)) {
         $fs->mkdir($directory);
     }
     $routes = $this->routes;
     $factory = new BuilderFactory();
     $node = $factory->namespace('Route')->addStmt($factory->class('RouteArray')->addStmt($factory->property('_routes')->makePrivate()->setDefault($routes))->addStmt($factory->method('getRoutes')->makePublic()->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this->_routes')))))->getNode();
     $stmts = array($node);
     $prettyPrinter = new PrettyPrinter\Standard();
     $php = $prettyPrinter->prettyPrintFile($stmts);
     file_put_contents($path, $php);
 }
 public function sample()
 {
     $factory = new BuilderFactory();
     $node = $factory->namespace('name\\space')->addStmt($factory->class('Sample')->addStmt($factory->property('string')->makeProtected()->setDocComment('/**
                           * @var string String
                           */'))->addStmt($factory->method('get')->makePublic()->setDocComment('/**
                           * Return string
                           *
                           * @return string String
                           */')->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this->string'))))->addStmt($factory->method('set')->makePublic()->setDocComment('/**
                           * Set string
                           *
                           * @param string $string String
                           * @return $this
                           */')->addParam(new Node\Param('string'))->addStmt(new Node\Name('$this->string = $string;'))->addStmt(new Node\Stmt\Return_(new Node\Expr\Variable('this')))))->getNode();
     $stmts = array($node);
     $prettyPrinter = new PrettyPrinter\Standard();
     $code = $prettyPrinter->prettyPrintFile($stmts);
     file_put_contents('tmp/origin/PHPParser.php', (string) $code);
 }
    public function testIntegration()
    {
        $factory = new BuilderFactory();
        $node = $factory->namespace('Name\\Space')->addStmt($factory->use('Foo\\Bar\\SomeOtherClass'))->addStmt($factory->use('Foo\\Bar')->as('A'))->addStmt($factory->class('SomeClass')->extend('SomeOtherClass')->implement('A\\Few', '\\Interfaces')->makeAbstract()->addStmt($factory->method('firstMethod'))->addStmt($factory->method('someMethod')->makePublic()->makeAbstract()->addParam($factory->param('someParam')->setTypeHint('SomeClass'))->setDocComment('/**
                                      * This method does something.
                                      *
                                      * @param SomeClass And takes a parameter
                                      */'))->addStmt($factory->method('anotherMethod')->makeProtected()->addParam($factory->param('someParam')->setDefault('test'))->addStmt(new Expr\Print_(new Expr\Variable('someParam'))))->addStmt($factory->property('someProperty')->makeProtected())->addStmt($factory->property('anotherProperty')->makePrivate()->setDefault(array(1, 2, 3))))->getNode();
        $expected = <<<'EOC'
<?php

namespace Name\Space;

use Foo\Bar\SomeOtherClass;
use Foo\Bar as A;
abstract class SomeClass extends SomeOtherClass implements A\Few, \Interfaces
{
    protected $someProperty;
    private $anotherProperty = array(1, 2, 3);
    function firstMethod()
    {
    }
    /**
     * This method does something.
     *
     * @param SomeClass And takes a parameter
     */
    public abstract function someMethod(SomeClass $someParam);
    protected function anotherMethod($someParam = 'test')
    {
        print $someParam;
    }
}
EOC;
        $stmts = array($node);
        $prettyPrinter = new PrettyPrinter\Standard();
        $generated = $prettyPrinter->prettyPrintFile($stmts);
        $this->assertEquals(str_replace("\r\n", "\n", $expected), str_replace("\r\n", "\n", $generated));
    }
 public static function CreateTests($dir = null)
 {
     if (!is_dir($dir)) {
         throw new InvalidArgumentException('Output directory "' . $dir . '" does not exist!');
     }
     $factory = new BuilderFactory();
     $prettyPrinter = new StandardPrettyPrinter();
     $lazySanitizer = function ($in) {
         return preg_replace('/[^a-z]/i', '', ucfirst($in));
     };
     $namespaceTests = 'VerbalExpressions\\PHPVerbalExpressions\\Tests';
     $useVerbExp = 'VerbalExpressions\\PHPVerbalExpressions\\VerbalExpressions';
     $variableOut = new Variable('out');
     $variableRegex = new Variable('regex');
     $variableThis = new Variable('this');
     $nameVerbalExpressions = new Name('VerbalExpressions');
     $constVerbExp = new ClassConstFetch(new Name('static'), 'VerbExpClassName');
     $nameAssertInstanceOf = new Name('assertInstanceOf');
     $nameAssertEquals = new Name('assertEquals');
     $assignNewVerbExpToRegex = new Assign($variableRegex, new New_($nameVerbalExpressions));
     $parseCallStackItem = function ($callStackItem, $method, $containsDesc) use($variableOut, $variableRegex, $variableThis, $nameAssertInstanceOf, $nameAssertEquals, $constVerbExp) {
         $method->setDocComment('/**
             * ' . $containsDesc->description . '
             */');
         if (count($callStackItem->arguments) > 0) {
             $methodCall = new MethodCall($variableRegex, new Name($callStackItem->method), array_map(array('static', 'CreateArg'), $callStackItem->arguments));
         } else {
             $methodCall = new MethodCall($variableRegex, new Name($callStackItem->method));
         }
         $method->addStmt(new Assign($variableOut, $methodCall));
         if ($callStackItem->returnType === 'sameInstance') {
             $method->addStmt(new MethodCall($variableThis, $nameAssertInstanceOf, array($constVerbExp, $variableOut)));
             $method->addStmt(new Assign($variableRegex, $variableOut));
         } else {
             $method->addStmt(new MethodCall($variableThis, $nameAssertEquals, array(new String_($callStackItem->returnType), new FuncCall(new Name('gettype'), array($variableOut)))));
         }
     };
     foreach (static::GetTestFiles() as $testFile) {
         $data = json_decode(file_get_contents($testFile->getRealPath()));
         $className = $lazySanitizer(substr($testFile->getBasename(), 0, -4)) . 'DynamicallyGeneratedTest';
         $class = $factory->class($className)->extend('PHPUnit_Framework_TestCase')->addStmt(new ClassConst(array(new Const_('VerbExpClassName', new String_($useVerbExp)))));
         if (isset($data->patterns)) {
             foreach ($data->patterns as $pattern) {
                 $method = $factory->method('pattern' . $lazySanitizer($pattern->name))->makeProtected()->addStmt($assignNewVerbExpToRegex);
                 foreach ($pattern->callStack as $callStackItem) {
                     $parseCallStackItem($callStackItem, $method, $pattern);
                 }
                 $method->addStmt(new Return_($variableRegex));
                 $class->addStmt($method);
             }
         }
         $methods = array();
         $methodIncrements = array();
         foreach ($data->tests as $test) {
             $expectedOutputValue = $test->output->default;
             if (isset($test->output->php)) {
                 $expectedOutputValue = $test->output->php;
             }
             $methodName = 'test' . $lazySanitizer($test->name);
             if (in_array($methodName, $methods)) {
                 if (!isset($methodIncrements[$methodName])) {
                     $methodIncrements[$methodName] = 1;
                 }
                 $methodName .= ++$methodIncrements[$methodName];
             }
             $methods[] = $methodName;
             $method = $factory->method($methodName)->makePublic();
             if (isset($test->pattern)) {
                 $method->addStmt(new Assign($variableRegex, new StaticCall(new Name('static'), 'pattern' . $lazySanitizer($test->pattern))));
                 $method->addStmt(new MethodCall($variableThis, $nameAssertInstanceOf, array($constVerbExp, $variableRegex)));
             } else {
                 $method->addStmt($assignNewVerbExpToRegex);
             }
             foreach ($test->callStack as $callStackItem) {
                 $parseCallStackItem($callStackItem, $method, $test);
             }
             $method->addStmt(new MethodCall($variableThis, $nameAssertEquals, array(static::CreateArg($expectedOutputValue), $variableOut)));
             $class->addStmt($method);
         }
         file_put_contents($dir . '/' . $className . '.php', $prettyPrinter->prettyPrintFile(array($factory->namespace($namespaceTests)->addStmt($factory->use('PHPUnit_Framework_TestCase'))->addStmt($factory->use($useVerbExp))->addStmt($class)->getNode())));
     }
 }
Example #11
0
 /**
  * @param PHPNamespace $namespace
  *
  * @return \PhpParser\Node
  */
 public function generateNamespace(PHPNamespace $namespace)
 {
     $ns = $this->factory->namespace($namespace->getName());
     return $ns->getNode();
 }
Example #12
0
 private function createClass($commande, $description)
 {
     $output = $this->_output;
     $root = ROOT . DS;
     $app = $root . 'app' . DS . "Application";
     $lib = $root . 'library' . DS . "commands.php";
     // create command name
     $name = S::create($commande)->replace(':', ' ')->toTitleCase()->replace(' ', '')->append("Command")->__toString();
     // create FQN
     $fqn = "Application\\Commands\\" . $name;
     // check avaibality
     // load commands.php file
     $code = file_get_contents($lib);
     $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP5);
     $prettyPrinter = new PrettyPrinter\Standard();
     $stmts = $parser->parse($code);
     foreach ($stmts[0]->expr as $express) {
         $tmp = $express[0]->value->value;
         if (S::create($tmp)->humanize()->__toString() == S::create($fqn)->humanize()->__toString()) {
             $output->writeln("This command already exists in commands.php");
             die;
         }
     }
     // commands not exists add it to commands.php
     $nb = count($stmts[0]->expr->items);
     $ligne = 4 + $nb;
     $attributes = array("startLine" => $ligne, "endLine" => $ligne, "kind" => 2);
     $obj = new \PhpParser\Node\Expr\ArrayItem(new \PhpParser\Node\Scalar\String_($fqn, $attributes), null, false, $attributes);
     array_push($stmts[0]->expr->items, $obj);
     $code = $prettyPrinter->prettyPrint($stmts);
     $code = "<?php \r\n" . $code;
     $output->writeln("Create FQN commande " . $fqn);
     $path = $app . DS . "Commands" . DS . $name . ".php";
     $arg1 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($commande));
     $arg2 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_($description));
     $arg3 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('Start process'));
     $arg4 = new \PhpParser\Node\Arg(new \PhpParser\Node\Scalar\String_('Finished'));
     $factory = new BuilderFactory();
     $node = $factory->namespace('Application\\Commands')->addStmt($factory->use('Symfony\\Component\\Console\\Command\\Command'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputArgument'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputInterface'))->addStmt($factory->use('Symfony\\Component\\Console\\Input\\InputOption'))->addStmt($factory->use('Symfony\\Component\\Console\\Output\\OutputInterface'))->addStmt($factory->class($name)->extend('Command')->addStmt($factory->method('configure')->makeProtected()->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('this'), "setName", array($arg1)))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('this'), "setDescription", array($arg2))))->addStmt($factory->method('execute')->makeProtected()->addParam($factory->param('input')->setTypeHint('InputInterface'))->addParam($factory->param('output')->setTypeHint('OutputInterface'))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('output'), "writeln", array($arg3)))->addStmt(new Node\Expr\MethodCall(new Node\Expr\Variable('output'), "writeln", array($arg4)))))->getNode();
     $stmts = array($node);
     $prettyPrinter = new PrettyPrinter\Standard();
     $php = $prettyPrinter->prettyPrintFile($stmts);
     file_put_contents($path, $php);
     $fs = new Filesystem();
     // if file exists add command to commands.php
     if ($fs->exists($path)) {
         $output->writeln("File saved in " . $path);
         $output->writeln("Register command to console");
         file_put_contents($lib, $code);
     } else {
         $output->writeln("File not created");
     }
 }
Example #13
0
 /**
  * @param Array_ $values
  * @param BuilderFactory $factory
  *
  * @return Property
  */
 private function createValueField(BuilderFactory $factory, Array_ $values)
 {
     return $factory->property('values')->makePrivate()->makeStatic()->setDefault($values);
 }
Example #14
0
 /**
  * @param string $className
  * @param string $namespace
  * @param Const_[] $consts
  *
  * @return PhpParser\Node
  */
 private function createClassFromData($className, $namespace, $consts)
 {
     $factory = new BuilderFactory();
     return $factory->namespace($namespace)->addStmt($factory->class($className)->addStmt(new ClassConst($consts)))->getNode();
 }