function it_is_not_fine_with_abstract_and_private_methods(Method $method)
 {
     $method->isAbstract()->willReturn(true);
     $method->getVisibility()->willReturn('private');
     $method->getName()->willReturn('__construct');
     $this->validate($method)->shouldHaveType('Memio\\Validator\\Violation\\SomeViolation');
 }
 function it_is_not_fine_with_abstract_methods_with_body(Method $method)
 {
     $method->isAbstract()->willReturn(true);
     $method->getBody()->willReturn('');
     $method->getName()->willReturn('__construct');
     $this->validate($method)->shouldHaveType('Memio\\Validator\\Violation\\SomeViolation');
 }
 function it_is_not_fine_with_protected_methods(Contract $contract, Method $method)
 {
     $contract->getName()->willReturn('HttpKernelInterface');
     $contract->allMethods()->willReturn(array($method));
     $method->getVisibility()->willReturn('protected');
     $method->getName()->willReturn('handle');
     $this->validate($contract)->shouldHaveType('Memio\\Validator\\Violation\\SomeViolation');
 }
 function it_is_not_fine_none_pure_virtual_methods(Contract $contract, Method $method)
 {
     $contract->getName()->willReturn('HttpKernelInterface');
     $contract->allMethods()->willReturn(array($method));
     $method->getBody()->willReturn('echo "Nobody expects the spanish inquisition";');
     $method->getName()->willReturn('handle');
     $this->validate($contract)->shouldHaveType('Memio\\Validator\\Violation\\SomeViolation');
 }
 function it_is_not_fine_with_concrete_object_and_abstract_methods(Object $object, Method $method)
 {
     $object->getName()->willReturn('ConcreteClass');
     $object->isAbstract()->willReturn(false);
     $object->allMethods()->willReturn(array($method));
     $method->isAbstract()->willReturn(true);
     $method->getName()->willReturn('abstractClass');
     $this->validate($object)->shouldHaveType('Memio\\Validator\\Violation\\SomeViolation');
 }
Ejemplo n.º 6
0
 function it_also_validates_arguments(ArgumentValidator $argumentValidator, CollectionValidator $collectionValidator, Method $model)
 {
     $arguments = array();
     $violationCollection1 = new ViolationCollection();
     $violationCollection2 = new ViolationCollection();
     $model->isAbstract()->willReturn(false);
     $model->allArguments()->willReturn($arguments);
     $collectionValidator->validate($arguments)->willReturn($violationCollection1);
     $argumentValidator->validate($arguments)->willReturn($violationCollection2);
     $this->validate($model);
 }
Ejemplo n.º 7
0
 function it_inserts_method_in_class_with_stuff(Editor $editor, File $file, Method $method, PrettyPrinter $prettyPrinter)
 {
     $insertMethod = new InsertMethod($file->getWrappedObject(), $method->getWrappedObject());
     $method->getName()->willReturn(self::METHOD_NAME);
     $editor->hasBelow($file, self::METHOD_PATTERN, 0)->willReturn(false);
     $editor->jumpBelow($file, InsertMethodHandler::CLASS_ENDING, 0)->shouldBeCalled();
     $file->decrementCurrentLineNumber(1)->shouldBeCalled();
     $file->getLine()->willReturn('    }');
     $editor->insertBelow($file, '')->shouldBeCalled();
     $prettyPrinter->generateCode($method)->willReturn(self::GENERATED_CODE);
     $editor->insertBelow($file, self::GENERATED_CODE)->shouldBeCalled();
     $this->handle($insertMethod);
 }
 function it_inserts_constructor_in_class_with_methods_and_other_stuff(Editor $editor, File $file, Method $method, PrettyPrinter $prettyPrinter)
 {
     $insertConstructor = new InsertConstructor($file->getWrappedObject(), $method->getWrappedObject());
     $editor->hasBelow($file, InsertConstructorHandler::CONSTRUCTOR, 0)->willReturn(false);
     $editor->hasBelow($file, InsertConstructorHandler::METHOD, 0)->willReturn(true);
     $editor->jumpBelow($file, InsertConstructorHandler::METHOD, 0)->shouldBeCalled();
     $editor->insertAbove($file, '')->shouldBeCalled();
     $prettyPrinter->generateCode($method)->willReturn(self::GENERATED_CODE);
     $editor->insertAbove($file, self::GENERATED_CODE)->shouldBeCalled();
     $file->decrementCurrentLineNumber(1)->shouldBeCalled();
     $file->getLine()->willReturn('    const CONSTANT = 42;');
     $editor->insertBelow($file, '')->shouldBeCalled();
     $this->handle($insertConstructor);
 }
Ejemplo n.º 9
0
    protected function generateCodeForResource(ResourceInterface $resource, array $data)
    {
        /** @var Object $structure */
        $structure = Object::make($resource->getSpecClassname());
        $handledClass = $data['handles'];
        $pieces = explode("\\", $handledClass);
        $handledClassShortName = end($pieces);
        $arguments = '$' . implode(', $', $data['params']);
        $structure->extend(Object::make('PhpSpec\\ObjectBehavior'));
        $methodBody = <<<BODY
        \$this->shouldHaveType('{$resource->getSrcClassname()}');
BODY;
        $structure->addMethod(Method::make('it_is_initializable')->setBody($methodBody));
        $methodBody = <<<BODY
        throw new PendingException('Pending implementation');
        \$command = new {$handledClassShortName}({$arguments});
        \$this->handle(\$command);
BODY;
        $structure->addMethod(Method::make('it_should_handle')->setBody($methodBody));
        $file = File::make($resource->getSpecFilename());
        $file->addFullyQualifiedName(new FullyQualifiedName('PhpSpec\\ObjectBehavior'));
        $file->addFullyQualifiedName(new FullyQualifiedName('Prophecy\\Argument'));
        $file->addFullyQualifiedName(new FullyQualifiedName('PhpSpec\\Exception\\Example\\PendingException'));
        $file->addFullyQualifiedName(new FullyQualifiedName($handledClass));
        $file->setStructure($structure);
        $prettyPrinter = Build::prettyPrinter();
        return $prettyPrinter->generateCode($file);
    }
 public function generate()
 {
     $repository = File::make($this->filename)->setLicensePhpdoc(new LicensePhpdoc(self::PROJECT_NAME, self::AUTHOR_NAME, self::AUTHOR_EMAIL))->addFullyQualifiedName(new FullyQualifiedName(BaseManager::class))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Entities\\" . $this->entity . "Entity as Entity"))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Validators\\" . $this->entity . "Validator as Validator"))->setStructure(Object::make($this->namespace . $this->entity . $this->layer)->extend(new Object(BaseManager::class))->addMethod(Method::make('__construct')->addArgument(new Argument('Entity', 'Entity'))->addArgument(new Argument('Validator', 'Validator'))->setBody('        return parent::__construct($Entity , $Validator);'))->addMethod(Method::make('save')->addArgument(new Argument('array', 'data'))->setBody('        return parent::save($data);'))->addMethod(Method::make('update')->addArgument(new Argument('array', 'data'))->setBody('        return parent::update($data);'))->addMethod(Method::make('delete')->setBody('        return parent::delete();'))->addMethod(Method::make('prepareData')->setBody('        return parent::prepareData();')));
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($repository);
     return $this->generateFile($generatedCode);
 }
Ejemplo n.º 11
0
    protected function generateCodeForResource(ResourceInterface $resource, array $data)
    {
        /** @var Object $structure */
        $structure = Object::make($resource->getSpecClassname());
        $structure->extend(Object::make('PhpSpec\\ObjectBehavior'));
        $methodBody = <<<BODY
        \$this->shouldHaveType('{$resource->getSrcClassname()}');
BODY;
        $structure->addMethod(Method::make('it_is_initializable')->setBody($methodBody));
        foreach ($data['params'] as $param) {
            $specExample = sprintf('it_should_retrieve_%s_getter_value', $param);
            $specMethodBody = "";
            $specMethodBody .= "        throw new PendingException('pending implementation');" . "\n";
            $specMethodBody .= "        \$expectation = 'put value here';" . "\n";
            $specMethodBody .= "        \$this->{$param}()->shouldBeLike(\$expectation);";
            $specExampleMethod = Method::make($specExample)->setBody($specMethodBody);
            $structure->addMethod($specExampleMethod);
        }
        $file = File::make($resource->getSpecFilename());
        $file->addFullyQualifiedName(new FullyQualifiedName('PhpSpec\\ObjectBehavior'));
        $file->addFullyQualifiedName(new FullyQualifiedName('Prophecy\\Argument'));
        $file->addFullyQualifiedName(new FullyQualifiedName('PhpSpec\\Exception\\Example\\PendingException'));
        $file->setStructure($structure);
        $prettyPrinter = Build::prettyPrinter();
        return $prettyPrinter->generateCode($file);
    }
 public function generate()
 {
     $repository = File::make($this->filename)->setLicensePhpdoc(new LicensePhpdoc(self::PROJECT_NAME, self::AUTHOR_NAME, self::AUTHOR_EMAIL))->addFullyQualifiedName(new FullyQualifiedName(BaseValidator::class))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Entities\\" . $this->entity . "Entity as Entity"))->setStructure(Object::make($this->namespace . $this->entity . $this->layer)->extend(new Object(BaseValidator::class))->addProperty(Property::make('rules')->makeProtected()->setDefaultValue("[\n      'name' => 'required'\n    ]"))->addMethod(Method::make('__construct')->addArgument(new Argument('Entity', 'Entity'))->setBody('        parent::__construct($Entity);'))->addMethod(Method::make('getCreateRules')->setBody('        return parent::getCreateRules();'))->addMethod(Method::make('getUpdateRules')->setBody('        return parent::getUpdateRules();')));
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($repository);
     return $this->generateFile($generatedCode);
 }
 public function generate()
 {
     $repository = File::make($this->filename)->setLicensePhpdoc(new LicensePhpdoc(self::PROJECT_NAME, self::AUTHOR_NAME, self::AUTHOR_EMAIL))->addFullyQualifiedName(new FullyQualifiedName(BaseRepository::class))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Entities\\" . $this->entity . "Entity as Entity"))->setStructure(Object::make($this->namespace . $this->entity . $this->layer)->extend(new Object(BaseRepository::class))->addMethod(Method::make('__construct')->addArgument(new Argument('Entity', 'Entity'))->setBody('        parent::__construct($Entity);')));
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($repository);
     return $this->generateFile($generatedCode);
 }
    function it_logs_the_generated_method(File $file, ConsoleIO $io, Method $method, Object $object)
    {
        $generatedMethod = new GeneratedMethod($file->getWrappedObject());
        $file->getStructure()->willReturn($object);
        $object->getName()->willReturn(self::CLASS_NAME);
        $object->allMethods()->willReturn([$method]);
        $method->getName()->willReturn(self::METHOD_NAME);
        $className = self::CLASS_NAME;
        $methodName = self::METHOD_NAME;
        $io->write(<<<OUTPUT

  <info>Generated <value>{$className}#{$methodName}</value></info>

OUTPUT
)->shouldBeCalled();
        $this->onGeneratedMethod($generatedMethod);
    }
Ejemplo n.º 15
0
 public function sample()
 {
     $file = File::make('Memio.php')->setStructure(Object::make('name\\space\\Sample')->addProperty(Property::make('string')->makePublic()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(VariableTag::make('string String'))))->addMethod(Method::make('get')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('Return string'))->setReturnTag(ReturnTag::make('string')))->setBody('return $this->string;'))->addMethod(Method::make('set')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('Set string'))->addParameterTag(ParameterTag::make('string', 'string', 'String'))->setReturnTag(ReturnTag::make('$this')))->addArgument(Argument::make('string', 'string'))->setBody('$this->string = $string;' . PHP_EOL . 'return $this;')));
     // Generate the code and display in the console
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($file);
     file_put_contents('tmp/origin/Memio.php', (string) $generatedCode);
 }
    function it_logs_the_generated_constructor(File $file, ConsoleIO $io, Method $method, Object $object, Property $property)
    {
        $generatedConstructor = new GeneratedConstructor($file->getWrappedObject());
        $file->getStructure()->willReturn($object);
        $object->getName()->willReturn(self::CLASS_NAME);
        $object->allProperties()->willReturn([$property]);
        $object->allMethods()->willReturn([$method]);
        $method->getName()->willReturn(self::METHOD_NAME);
        $className = self::CLASS_NAME;
        $methodName = self::METHOD_NAME;
        $propertiesCount = self::PROPERTIES_COUNT;
        $io->write(<<<OUTPUT

  <info>Generated <value>{$propertiesCount}</value> property for <value>{$className}</value>, with its constructor</info>

OUTPUT
)->shouldBeCalled();
        $this->onGeneratedConstructor($generatedConstructor);
    }
Ejemplo n.º 17
0
 protected function generateCodeForResource(ResourceInterface $resource, array $data)
 {
     $structure = Object::make($resource->getSrcClassname());
     $structure->makeFinal();
     $handle = Method::make('handle');
     $handle->addArgument(Argument::make($data['handles'], 'command'));
     $handle->setBody("        // TODO write your own implementation");
     $structure->addMethod($handle);
     $file = File::make($resource->getSrcFilename())->setStructure($structure);
     $prettyPrinter = Build::prettyPrinter();
     return $prettyPrinter->generateCode($file);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     $entity = $input->getArgument('entity');
     $entityDir = $input->getArgument('entity-dir');
     if (!file_exists($file)) {
         throw new \InvalidArgumentException("{$file} does not exist");
     }
     if (!is_dir($entityDir)) {
         throw new \InvalidArgumentException("{$entityDir} is not a valid directory");
     }
     $item = json_decode(file_get_contents($file))[0];
     $file = File::make($entityDir . '/' . $entity . '.php');
     $object = Object::make('Dandomain\\Api\\Entity\\' . $entity);
     $arrayProperties = [];
     foreach ($item as $key => $val) {
         if (gettype($val) == 'array') {
             $arrayProperties[] = $key;
         }
     }
     if (count($arrayProperties)) {
         $body = [];
         foreach ($arrayProperties as $arrayProperty) {
             $body[] = '        $this->' . $arrayProperty . ' = new ArrayCollection();';
         }
         $object->addMethod(Method::make('__construct')->setBody(join("\n", $body)));
         $file->addFullyQualifiedName(new FullyQualifiedName('Doctrine\\Common\\Collections\\ArrayCollection'));
     }
     foreach ($item as $key => $val) {
         $type = gettype($val);
         if ($type == 'array') {
             $type = 'ArrayCollection';
         }
         $property = Property::make($key)->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($type)));
         $object->addProperty($property);
         $object->addMethod(Method::make('get' . ucfirst($key))->setPhpdoc(MethodPhpdoc::make()->setReturnTag(new ReturnTag($type)))->setBody('        return $this->' . $key . ';'));
         $object->addMethod(Method::make('set' . ucfirst($key))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag($type, $key))->setReturnTag(new ReturnTag($entity)))->addArgument(Argument::make('string', $key))->setBody('        $this->' . $key . ' = $' . $key . ';'));
     }
     $file->setStructure($object);
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($file);
     file_put_contents($file->getFilename(), $generatedCode);
 }
Ejemplo n.º 19
0
    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $model = $input->getArgument('model');
        $outputFile = sprintf('%s.php', $this->joinPaths($input->getOption('output'), str_replace('\\', DIRECTORY_SEPARATOR, $model)));
        $classObject = Object::make($model);
        $file = File::make($outputFile)->setStructure($classObject);
        $file->addFullyQualifiedName(FullyQualifiedName::make('Doctrine\\ODM\\MongoDB\\Mapping\\Annotations as ODM'));
        $file->addFullyQualifiedName(FullyQualifiedName::make('Hive\\Annotations as H'));
        $fields = array_merge(['id:id'], $input->getArgument('fields'));
        foreach ($fields as $field) {
            if (!preg_match('/(\\w+)(?::(string|boolean|id|reference[s]?)(?:\\[([\\w\\\\]+),(\\w+)\\])?)?(?::(\\w+))?/i', $field, $matches)) {
                continue;
            }
            @(list($all, $name, $type, $referenceType, $linkProperty, $fake) = $matches);
            /** @var Property $property */
            $property = Property::make($name);
            $property->makePublic();
            $property->setPhpdoc(new ODMPropertyPhpdoc($name, $type, $referenceType, $linkProperty, $fake));
            $classObject->addProperty($property);
        }
        $classObject->setPhpdoc(StructurePhpdoc::make()->setDescription(Description::make(<<<'EOF'
This class is generated with the hive console.

@ODM\Document @ODM\HasLifecycleCallbacks
EOF
)));
        $classObject->addMethod(Method::make('validate')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make(<<<'EOF'
The validate method can be used to validate properties.

@ODM\PrePersist @ODM\PreUpdate
EOF
))));
        // Generate the code
        $prettyPrinter = Build::prettyPrinter();
        $prettyPrinter->addTemplatePath(realpath($this->joinPaths(dirname(__FILE__), '../../../templates/memio/')));
        $generatedCode = $prettyPrinter->generateCode($file);
        @mkdir(dirname($outputFile), 0755, true);
        file_put_contents($outputFile, html_entity_decode(html_entity_decode($generatedCode)));
        $io = new SymfonyStyle($input, $output);
        $io->success(["Model {$model} created in {$outputFile}"]);
    }
Ejemplo n.º 20
0
    protected function generateCodeForResource(ResourceInterface $resource, array $data)
    {
        $structure = Object::make($resource->getSrcClassname());
        $structure->makeFinal();
        $construct = Method::make('__construct');
        $structure->addMethod($construct);
        $constructBody = [];
        foreach ($data['params'] as $param) {
            $structure->addProperty(Property::make($param));
            $body = <<<METHOD
        return \$this->{$param};
METHOD;
            $construct->addArgument(Argument::make('mixed', $param));
            $constructBody[] = "        \$this->{$param} = \${$param};";
            $method = Method::make($param)->setBody($body);
            $structure->addMethod($method);
        }
        $construct->setBody(implode("\n", $constructBody));
        $file = File::make($resource->getSrcFilename())->setStructure($structure);
        $prettyPrinter = Build::prettyPrinter();
        return $prettyPrinter->generateCode($file);
    }
Ejemplo n.º 21
0
 public function generate($class, $param = NULL)
 {
     // Describe the code you want to generate using "Models"
     $this->_class = Object::make(ucfirst($class));
     if ($param['property'] !== NULL) {
         if (is_array($param['property'])) {
             foreach ($param['property'] as $property) {
                 $this->_class->addProperty(Property::make($property));
             }
         } elseif (is_string($param['property'])) {
             $this->_class->addProperty(Property::make($param['property']));
         }
     }
     if ($param['method'] !== NULL) {
         if (is_array($param['method'])) {
             foreach ($param['method'] as $method) {
                 if (is_array($method)) {
                     foreach ($method as $name => $arguments) {
                         $this->_method = Method::make($name);
                         foreach ($arguments as $kind => $argument) {
                             $this->_method->addArgument(Argument::make($kind, $argument));
                         }
                     }
                     $this->_class->addMethod($this->_method);
                 } elseif (is_string($method)) {
                     $this->_class->addMethod(Method::make($method));
                 }
             }
         } elseif (is_string($param['method'])) {
             $this->_class->addMethod(Method::make($param['method']));
         }
     }
     $file = File::make(ucfirst($class) . 'php')->setStructure($this->_class);
     // Generate the code and display in the console
     $prettyPrinter = Build::prettyPrinter();
     echo '<pre>' . htmlspecialchars($prettyPrinter->generateCode($file)) . '</pre>';
 }
 public function generate()
 {
     /*GENERATE BASE CONTROLLER FOR NAMESPACE */
     if (!FileSystem::exists($this->path . $this->pathname . '/BaseController.php')) {
         $baseDistPath = realpath(__DIR__ . '/../Controllers/BaseController.php.dist');
         $basePath = realpath(__DIR__ . '/../Controllers/') . '/BaseController.php';
         $copy = FileSystem::copy($baseDistPath, $basePath);
         $base = realpath(__DIR__ . '/../Controllers/BaseController.php');
         $find = 'use App\\Http\\Controllers\\Controller;';
         $replace = 'use ' . $this->getAppNamespace() . 'Http\\Controllers\\Controller;';
         $find2 = 'namespace AppNamespace\\Http\\Controllers\\API;';
         $replace2 = 'namespace ' . $this->getAppNamespace() . 'Http\\Controllers\\' . $this->pathname . ';';
         FileSystem::put($base, str_replace($find2, $replace2, str_replace($find, $replace, file_get_contents($base))));
         if (!FileSystem::isDirectory($this->path . $this->pathname)) {
             FileSystem::makeDirectory($this->path . $this->pathname);
         }
         FileSystem::move($base, $this->path . $this->pathname . '/BaseController.php');
     }
     $prefix = $this->prefix ? $this->prefix . '/' : '';
     $repository = File::make($this->filename)->setLicensePhpdoc(new LicensePhpdoc(self::PROJECT_NAME, self::AUTHOR_NAME, self::AUTHOR_EMAIL))->addFullyQualifiedName(new FullyQualifiedName(\Illuminate\Http\Request::class))->addFullyQualifiedName(new FullyQualifiedName($this->namespace . "BaseController"))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Repositories\\" . $this->entity . "Repository as Repository"))->addFullyQualifiedName(new FullyQualifiedName($this->appNamespace . "Managers\\" . $this->entity . "Manager as Manager"))->setStructure(Object::make($this->namespace . $this->entity . $this->layer)->extend(new Object(BaseController::class))->addMethod(Method::make('__construct')->addArgument(new Argument('Repository', 'Repository'))->addArgument(new Argument('Manager', 'Manager'))->setBody('        return parent::__construct($Repository , $Manager);'))->addMethod(Method::make('index')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('@api {get} /' . $prefix . snake_case(str_plural($this->entity)) . ' 1 Request all ' . snake_case(str_plural($this->entity)))->addLine('@apiVersion 1.0.0')->addLine('@apiName All' . str_plural($this->entity))->addLine('@apiGroup ' . str_plural($this->entity))->addEmptyLine()->addLine('@apiSuccess {Object[]}  0 ' . $this->entity . ' Object.')->addLine('@apiSuccess {Number} 0.id Id.')->addLine('@apiSuccess {DateTime} 0.created_at  Created date.')->addLine('@apiSuccess {DateTime} 0.updated_at  Last modification date.')->addEmptyLine()->addLine("@apiSuccessExample Success 200 Example")->addLine(" HTTP/1.1 200 OK")->addLine("[")->addLine("    {")->addLine('        id: 1,')->addLine('        created_at: ' . date('Y-m-d h:i:s') . ',')->addLine('        updated_at: ' . date('Y-m-d h:i:s'))->addLine("    },")->addLine("    {")->addLine('        id: 2,')->addLine('        created_at: ' . date('Y-m-d h:i:s') . ',')->addLine('        updated_at: ' . date('Y-m-d h:i:s'))->addLine("    }")->addLine("]")->addEmptyLine()->addLine("@apiError (ServerError 500) {string} error Server error.")->addEmptyLine()->addLine("@apiErrorExample {json} ServerError 500 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Server error. Try again.')->addLine("}")))->addArgument(new Argument('Request', 'Request'))->setBody('        return parent::index($Request);'))->addMethod(Method::make('show')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('@api {get} /' . $prefix . snake_case(str_plural($this->entity)) . '/:id 2 Request a specific ' . snake_case($this->entity))->addLine('@apiVersion 1.0.0')->addLine('@apiName Get' . $this->entity)->addLine('@apiGroup ' . str_plural($this->entity))->addEmptyLine()->addLine('@apiParam (Url params) {Number} id ' . $this->entity . ' unique id.')->addEmptyLine()->addLine('@apiSuccess {Number} id Id.')->addLine('@apiSuccess {DateTime} created_at  Created date.')->addLine('@apiSuccess {DateTime} updated_at  Last modification date.')->addEmptyLine()->addLine("@apiSuccessExample {json} Success 200 Example")->addLine(" HTTP/1.1 200 OK")->addLine("{")->addLine('    id: 1,')->addLine('    created_at: ' . date('Y-m-d h:i:s') . ',')->addLine('    updated_at: ' . date('Y-m-d h:i:s'))->addLine("}")->addEmptyLine()->addLine("@apiError (EntityNotFound 404) {string} error The id of the " . snake_case($this->entity) . " was not found.")->addEmptyLine()->addLine("@apiErrorExample {json} EntityNotFound 404 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Entity not found')->addLine("}")->addEmptyLine()->addLine("@apiError (ServerError 500) {string} error Server error.")->addEmptyLine()->addLine("@apiErrorExample {json} ServerError 500 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Server error. Try again.')->addLine("}")))->addArgument(new Argument('Request', 'Request'))->addArgument(new Argument('integer', 'id'))->setBody('        return parent::show($Request , $id);'))->addMethod(Method::make('store')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('@api {post} /' . $prefix . snake_case(str_plural($this->entity)) . ' 3 Store a  ' . snake_case($this->entity))->addLine('@apiVersion 1.0.0')->addLine('@apiName Store' . $this->entity)->addLine('@apiGroup ' . str_plural($this->entity))->addEmptyLine()->addLine('@apiParam (FormData) {String} name ' . $this->entity . ' name.')->addEmptyLine()->addLine('@apiSuccess (Success 201) {Number} id Id.')->addLine('@apiSuccess (Success 201)  {DateTime} created_at  Created date.')->addLine('@apiSuccess (Success 201)  {DateTime} updated_at  Last modification date.')->addEmptyLine()->addLine("@apiSuccessExample {json} Success 201 Example")->addLine(" HTTP/1.1 201 OK")->addLine("{")->addLine('    id: 1,')->addLine('    created_at: ' . date('Y-m-d h:i:s') . ',')->addLine('    updated_at: ' . date('Y-m-d h:i:s'))->addLine("}")->addEmptyLine()->addLine("@apiError (ValidationErrors 400)  {array[]} name  List of errors for name field.")->addLine("@apiError (ValidationErrors 400)  {string} name.0  First error for name.")->addLine("@apiError (ValidationErrors 400)  {string} name.1  Second error for name.")->addEmptyLine()->addLine("@apiErrorExample {json} ValidationErrors 400 Example")->addLine("  HTTP/1.1 400 Bad Request")->addLine("{")->addLine('    name: [')->addLine('         The name field is required')->addLine("    ]")->addLine("}")->addEmptyLine()->addLine("@apiError (ServerError 500) {string} error Server error.")->addEmptyLine()->addLine("@apiErrorExample {json} ServerError 500 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Server error. Try again.')->addLine("}")))->addArgument(new Argument('Request', 'Request'))->setBody('        return parent::store($Request);'))->addMethod(Method::make('update')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('@api {put} /' . $prefix . snake_case(str_plural($this->entity)) . '/:id 4 Update a specific  ' . snake_case($this->entity))->addLine('@apiVersion 1.0.0')->addLine('@apiName Update' . $this->entity)->addLine('@apiGroup ' . str_plural($this->entity))->addEmptyLine()->addLine('@apiParam (Url params)  {Number} id ' . $this->entity . ' unique id.')->addLine('@apiParam (FormData) {String} name ' . $this->entity . ' name.')->addEmptyLine()->addLine('@apiSuccess {Number} id Id.')->addLine('@apiSuccess {DateTime} created_at  Created date.')->addLine('@apiSuccess {DateTime} updated_at  Last modification date.')->addEmptyLine()->addLine("@apiSuccessExample {json} Success 200 Example")->addLine(" HTTP/1.1 200 OK")->addLine("{")->addLine('    id: 1,')->addLine('    created_at: ' . date('Y-m-d h:i:s') . ',')->addLine('    updated_at: ' . date('Y-m-d h:i:s'))->addLine("}")->addEmptyLine()->addLine("@apiError (EntityNotFound 404) {string} error The id of the " . snake_case($this->entity) . " was not found.")->addEmptyLine()->addLine("@apiErrorExample {json} EntityNotFound 404 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Entity not found')->addLine("}")->addEmptyLine()->addLine("@apiError (ValidationErrors 400)  {array[]} name  List of errors for name field.")->addLine("@apiError (ValidationErrors 400)  {string} name.0  First error for name.")->addLine("@apiError (ValidationErrors 400)  {string} name.1  Second error for name.")->addEmptyLine()->addLine("@apiErrorExample {json} ValidationErrors 400 Example")->addLine("  HTTP/1.1 400 Bad Request")->addLine("{")->addLine('    name: [')->addLine('         The name field is required')->addLine("    ]")->addLine("}")->addEmptyLine()->addLine("@apiError (ServerError 500) {string} error Server error.")->addEmptyLine()->addLine("@apiErrorExample {json} ServerError 500 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Server error. Try again.')->addLine("}")))->addArgument(new Argument('Request', 'Request'))->addArgument(new Argument('integer', 'id'))->setBody('        return parent::update($Request , $id);'))->addMethod(Method::make('destroy')->setPhpdoc(MethodPhpdoc::make()->setDescription(Description::make('@api {delete} /' . $prefix . snake_case(str_plural($this->entity)) . '/:id 5 Delete a specific  ' . snake_case($this->entity))->addLine('@apiVersion 1.0.0')->addLine('@apiName Delete' . $this->entity)->addLine('@apiGroup ' . str_plural($this->entity))->addEmptyLine()->addLine('@apiParam (Url params)  {Number} id ' . $this->entity . ' unique id.')->addEmptyLine()->addLine("@apiSuccessExample Success 204 Example")->addLine(" HTTP/1.1 204 OK")->addEmptyLine()->addLine("@apiError (EntityNotFound 404) {string} error The id of the " . snake_case($this->entity) . " was not found.")->addEmptyLine()->addLine("@apiErrorExample {json} EntityNotFound 404 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Entity not found')->addLine("}")->addEmptyLine()->addLine("@apiError (ServerError 500) {string} error Server error.")->addEmptyLine()->addLine("@apiErrorExample {json} ServerError 500 Example")->addLine("  HTTP/1.1 404 Not Found")->addLine("{")->addLine('    error: Server error. Try again.')->addLine("}")))->addArgument(new Argument('Request', 'Request'))->addArgument(new Argument('integer', 'id'))->setBody('        return parent::destroy($Request , $id);')));
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($repository);
     return $this->generateFile($generatedCode);
 }
Ejemplo n.º 23
0
    protected function generateRepositoryModel($modulePath, $moduleName, $modelName, array $fields)
    {
        $resourceModelName = basename($modelName) . 'Resource';
        $resourceModelFqn = str_replace('/', '\\', "{$moduleName}/Model/ResourceModel/{$modelName}");
        $collectionFactoryName = 'CollectionFactory';
        $collectionFactoryFqn = str_replace('/', '\\', "{$moduleName}/Model/ResourceModel/{$modelName}/CollectionFactory");
        $searchResultsFactoryName = basename($modelName) . 'SearchResultsInterfaceFactory';
        $searchResultsFactoryFqn = str_replace('/', '\\', "{$moduleName}/Api/Data/{$modelName}SearchResultsInterfaceFactory");
        $searchResultsContractName = basename($modelName) . 'SearchResultsInterface';
        $searchResultsContractFqn = str_replace('/', '\\', "{$moduleName}/Api/Data/{$modelName}SearchResultsInterface");
        $dataContractName = basename($modelName) . 'Interface';
        $dataContractFqn = str_replace('/', '\\', "{$moduleName}/Api/Data/{$modelName}Interface");
        $dataFactoryName = basename($modelName) . 'InterfaceFactory';
        $dataFactoryFqn = str_replace('/', '\\', "{$moduleName}/Api/Data/{$modelName}InterfaceFactory");
        $factoryName = basename($modelName) . 'Factory';
        $model = Object::make(str_replace('/', '\\', "{$moduleName}/Model/{$modelName}Repository"));
        $model->implement(Contract::make(str_replace('/', '\\', "{$moduleName}/Api/{$modelName}RepositoryInterface")));
        $__constructBody = '        $this->resource             = $resource;
        $this->factory              = $factory;
        $this->collectionFactory    = $collectionFactory;
        $this->searchResultsFactory = $searchResultsFactory;
        $this->dataFactory          = $dataFactory;
        $this->dataObjectHelper     = $dataObjectHelper;
        $this->dataObjectProcessor  = $dataObjectProcessor;
        $this->storeManager         = $storeManager;';
        $model->addProperty(Property::make('resource')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($resourceModelName))));
        $model->addProperty(Property::make('factory')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($factoryName))));
        $model->addProperty(Property::make('collectionFactory')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($collectionFactoryName))));
        $model->addProperty(Property::make('searchResultsFactory')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($searchResultsFactoryName))));
        $model->addProperty(Property::make('dataFactory')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag($dataFactoryName))));
        $model->addProperty(Property::make('dataObjectHelper')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag('DataObjectHelper'))));
        $model->addProperty(Property::make('dataObjectProcessor')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag('DataObjectProcessor'))));
        $model->addProperty(Property::make('storeManager')->makeProtected()->setPhpdoc(PropertyPhpdoc::make()->setVariableTag(new VariableTag('StoreManagerInterface'))));
        $model->addMethod(Method::make('__construct')->setBody($__constructBody)->addArgument(new Argument($resourceModelName, 'resource'))->addArgument(new Argument($factoryName, 'factory'))->addArgument(new Argument($collectionFactoryName, 'collectionFactory'))->addArgument(new Argument($searchResultsFactoryName, 'searchResultsFactory'))->addArgument(new Argument($dataFactoryName, 'dataFactory'))->addArgument(new Argument('DataObjectHelper', 'dataObjectHelper'))->addArgument(new Argument('DataObjectProcessor', 'dataObjectProcessor'))->addArgument(new Argument('StoreManagerInterface', 'storeManager'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag($resourceModelName, 'resource'))->addParameterTag(new ParameterTag($factoryName, 'factory'))->addParameterTag(new ParameterTag($collectionFactoryName, 'collectionFactory'))->addParameterTag(new ParameterTag($searchResultsFactoryName, 'searchResultsFactory'))->addParameterTag(new ParameterTag($dataFactoryName, 'dataFactory'))->addParameterTag(new ParameterTag('DataObjectHelper', 'dataObjectHelper'))->addParameterTag(new ParameterTag('DataObjectProcessor', 'dataObjectProcessor'))->addParameterTag(new ParameterTag('StoreManagerInterface', 'storeManager'))));
        $model->addMethod(Method::make('getById')->setBody('        $object = $this->factory->create();
        $this->resource->load($object, $id);
        if (!$object->getId()) {
            throw new NoSuchEntityException("Object not found");
        }

        return $object;')->addArgument(new Argument('int', 'id'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag('int', 'id'))->setReturnTag(new ReturnTag($dataContractName))->addThrowTag(new ThrowTag('NoSuchEntityException'))));
        $model->addMethod(Method::make('save')->setBody('        $this->resource->save($object);

        return $object;')->addArgument(new Argument($dataContractName, 'object'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag($dataContractName, 'object'))->setReturnTag(new ReturnTag($dataContractName))));
        $getListBody = '        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($criteria);

        $collection = $this->collectionFactory->create();
        foreach ($criteria->getFilterGroups() as $filterGroup) {
            foreach ($filterGroup->getFilters() as $filter) {
                $condition = $filter->getConditionType() ?: \'eq\';
                $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
            }
        }
        $searchResults->setTotalCount($collection->getSize());
        $sortOrders = $criteria->getSortOrders();
        if ($sortOrders) {
            /** @var SortOrder $sortOrder */
            foreach ($sortOrders as $sortOrder) {
                $collection->addOrder(
                    $sortOrder->getField(),
                    ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? \'ASC\' : \'DESC\'
                );
            }
        }
        $collection->setCurPage($criteria->getCurrentPage());
        $collection->setPageSize($criteria->getPageSize());
        $objects = [];
        /** @var ' . $dataContractName . ' $object */
        foreach ($collection as $object) {
            $data = $this->dataFactory->create();
            $this->dataObjectHelper->populateWithArray(
                $data,
                $object->getData(),
                \'' . $dataContractFqn . '\'
            );
            $objects[] = $this->dataObjectProcessor->buildOutputDataArray(
                $data,
                \'' . $dataContractFqn . '\'
            );
        }
        $searchResults->setItems($objects);

        return $searchResults;';
        $model->addMethod(Method::make('getList')->setBody($getListBody)->addArgument(new Argument('SearchCriteriaInterface', 'criteria'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag('SearchCriteriaInterface', 'criteria'))->setReturnTag(new ReturnTag($searchResultsContractName))));
        $model->addMethod(Method::make('delete')->setBody('        $this->resource->delete($object);

        return true;')->addArgument(new Argument($dataContractName, 'object'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag($dataContractName, 'object'))->setReturnTag(new ReturnTag('bool'))));
        $model->addMethod(Method::make('deleteById')->setBody('        return $this->resource->delete($this->getById($id));')->addArgument(new Argument('int', 'id'))->setPhpdoc(MethodPhpdoc::make()->addParameterTag(new ParameterTag('int', 'id'))->setReturnTag(new ReturnTag('bool'))));
        $this->dumpObject($model, "{$modulePath}/Model/{$modelName}Repository.php", [[$resourceModelName => $resourceModelFqn], $collectionFactoryFqn, $searchResultsFactoryFqn, $dataFactoryFqn, $dataContractFqn, $searchResultsContractFqn, 'Magento\\Framework\\Api\\DataObjectHelper', 'Magento\\Framework\\Reflection\\DataObjectProcessor', 'Magento\\Framework\\Api\\SortOrder', 'Magento\\Store\\Model\\StoreManagerInterface', 'Magento\\Framework\\Exception\\NoSuchEntityException', 'Magento\\Framework\\Api\\SearchCriteriaInterface']);
        return $this;
    }
Ejemplo n.º 24
0
 public function testAbstract()
 {
     $method = Method::make('method')->makeAbstract();
     $generatedCode = $this->prettyPrinter->generateCode($method);
     $this->assertSame('    public abstract function method();', $generatedCode);
 }
Ejemplo n.º 25
0
 public function generateCode($source, $target, $constructor = false)
 {
     $classAnalyzer = new ClassAnalyzer();
     $classAnalyzer->setFile($source);
     $parent = Object::make($classAnalyzer->getClassName());
     $targetClassName = $this->getClassName($target);
     $file = File::make($target);
     $object = Object::make($targetClassName);
     $object->extend($parent);
     $file->addFullyQualifiedName(new FullyQualifiedName($classAnalyzer->getFullClassName()));
     if ($constructor) {
         $constructor = $classAnalyzer->getConstructor();
         $method = Method::make('__construct');
         foreach ($constructor as $parameter) {
             $type = $parameter[0];
             if ($type === null) {
                 $type = 'null';
             }
             $method->addArgument(new Argument($type, $parameter[1]));
             $method->setBody('parent::__construct()');
         }
         $object->addMethod($method);
     }
     $file->setStructure($object);
     $prettyPrinter = Build::prettyPrinter();
     $generatedCode = $prettyPrinter->generateCode($file);
     return $generatedCode;
 }
Ejemplo n.º 26
0
 public function testFull()
 {
     $file = File::make(self::FILENAME)->addFullyQualifiedName(new FullyQualifiedName('DateTime'))->setStructure(Object::make(self::FULLY_QUALIFIED_NAME)->addConstant(new Constant('FIRST_CONSTANT', '0'))->addConstant(new Constant('SECOND_CONSTANT', "'meh'"))->addProperty(new Property('firstProperty'))->addProperty(new Property('secondProperty'))->addMethod(Method::make('firstMethod')->addArgument(new Argument('DateTime', 'firstArgument'))->addArgument(new Argument('array', 'secondArgument'))->addArgument(new Argument('string', 'thirdArgument')))->addMethod(new Method('secondMethod')));
     $generatedCode = $this->prettyPrinter->generateCode($file);
     $this->assertExpectedCode($generatedCode);
 }
Ejemplo n.º 27
0
 public function testFull()
 {
     $contract = Contract::make(self::NAME)->extend(new Contract('FirstContract'))->extend(new Contract('SecondContract'))->addConstant(new Constant('FIRST_CONSTANT', '0'))->addConstant(new Constant('SECOND_CONSTANT', "'meh'"))->addMethod(Method::make('firstMethod')->addArgument(new Argument('DateTime', 'firstArgument'))->addArgument(new Argument('array', 'secondArgument'))->addArgument(new Argument('string', 'thirdArgument')))->addMethod(new Method('secondMethod'));
     $generatedCode = $this->prettyPrinter->generateCode($contract);
     $this->assertExpectedCode($generatedCode);
 }
Ejemplo n.º 28
0
 public function testThreeMethods()
 {
     $methods = array(Method::make('__construct')->addArgument(new Argument('DateTime', 'dateTime'))->addArgument(new Argument('ArrayObject', 'arrayObject')), new Method('getDateTime'), new Method('getArrayObject'));
     $generatedCode = $this->prettyPrinter->generateCode($methods);
     $this->assertExpectedCode($generatedCode);
 }