From 5a13dd349936410681bd1637c8e290fe3569fb90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 13 Nov 2014 10:40:09 -0400 Subject: [PATCH 01/46] Initial test --- .../Resources/skeleton/rest/actions/delete.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 11bce1f..9021817 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -1,6 +1,6 @@ /** {% block phpdoc_method_header %} - * Delete a {{ entity }} entity. + * Delete a {{ entity }} entity. Wberredo version * * @View(statusCode=204) * From 3c9a713b38e6401c9cec112af6af19b9bdb6b982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 13:31:36 -0400 Subject: [PATCH 02/46] Work with handlers as service --- .../Controller/VoryxController.php | 47 ---- .../Generator/DoctrineRESTGenerator.php | 264 +++++++++++++++--- .../skeleton/rest/actions/delete.php.twig | 13 +- .../skeleton/rest/actions/getAll.php.twig | 22 +- .../skeleton/rest/actions/getById.php.twig | 5 +- .../skeleton/rest/actions/getOr404.php.twig | 14 + .../skeleton/rest/actions/patch.php.twig | 5 +- .../skeleton/rest/actions/post.php.twig | 20 +- .../skeleton/rest/actions/put.php.twig | 26 +- .../skeleton/rest/controller.php.twig | 8 +- .../skeleton/rest/form_exception.php.twig | 29 ++ .../Resources/skeleton/rest/handler.php.twig | 43 +++ .../skeleton/rest/handler/construct.php.twig | 12 + .../skeleton/rest/handler/delete.php.twig | 16 ++ .../skeleton/rest/handler/extras.php.twig | 20 ++ .../skeleton/rest/handler/get.php.twig | 9 + .../skeleton/rest/handler/getAll.php.twig | 9 + .../skeleton/rest/handler/patch.php.twig | 9 + .../skeleton/rest/handler/post.php.twig | 11 + .../skeleton/rest/handler/put.php.twig | 9 + .../skeleton/rest/service/services.xml.twig | 6 + 21 files changed, 449 insertions(+), 148 deletions(-) delete mode 100644 src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/form_exception.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.xml.twig diff --git a/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php b/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php deleted file mode 100644 index 51cca5c..0000000 --- a/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php +++ /dev/null @@ -1,47 +0,0 @@ -container->get('form.factory')->createNamed( - null, //since we're not including the form name in the request, set this to null - $type, - $data, - $options - ); - - return $form; - } - - /** - * Get rid on any fields that don't appear in the form - * - * @param Request $request - * @param Form $form - */ - protected function removeExtraFields(Request $request, Form $form) - { - $data = $request->request->all(); - $children = $form->all(); - $data = array_intersect_key($data, $children); - $request->request->replace($data); - } -} diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index d664e2e..ccef8a1 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -11,6 +11,7 @@ namespace Voryx\RESTGeneratorBundle\Generator; +use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Doctrine\ORM\Mapping\ClassMetadataInfo; @@ -38,41 +39,52 @@ class DoctrineRESTGenerator extends Generator */ public function __construct(Filesystem $filesystem) { - $this->filesystem = $filesystem; + $this->filesystem = $filesystem; } /** * Generate the REST controller. * - * @param BundleInterface $bundle A bundle object - * @param string $entity The entity relative class name - * @param ClassMetadataInfo $metadata The entity class metadata - * @param string $routePrefix The route name prefix - * @param array $forceOverwrite Whether or not to overwrite an existing controller + * @param BundleInterface $bundle A bundle object + * @param string $entity The entity relative class name + * @param ClassMetadataInfo $metadata The entity class metadata + * @param string $routePrefix The route name prefix + * @param array $forceOverwrite Whether or not to overwrite an existing controller * * @throws \RuntimeException */ - public function generate(BundleInterface $bundle, $entity, ClassMetadataInfo $metadata, $routePrefix, $forceOverwrite) - { + public function generate( + BundleInterface $bundle, + $entity, + ClassMetadataInfo $metadata, + $routePrefix, + $forceOverwrite + ) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = str_replace('/', '_', $routePrefix); $this->actions = array('getById', 'getAll', 'post', 'put', 'delete'); if (count($metadata->identifier) > 1) { - throw new \RuntimeException('The REST api generator does not support entity classes with multiple primary keys.'); + throw new \RuntimeException( + 'The REST api generator does not support entity classes with multiple primary keys.' + ); } if (!in_array('id', $metadata->identifier)) { - throw new \RuntimeException('The REST api generator expects the entity object has a primary key field named "id" with a getId() method.'); + throw new \RuntimeException( + 'The REST api generator expects the entity object has a primary key field named "id" with a getId() method.' + ); } - $this->entity = $entity; - $this->bundle = $bundle; + $this->entity = $entity; + $this->bundle = $bundle; $this->metadata = $metadata; $this->setFormat('yml'); $this->generateControllerClass($forceOverwrite); - + $this->generateHandler($forceOverwrite); + $this->generateExceptionClass(); + $this->declareService(); } /** @@ -112,13 +124,17 @@ protected function generateConfiguration() $this->format ); - $this->renderFile('rest/config/routing.'.$this->format.'.twig', $target, array( - 'actions' => $this->actions, - 'route_prefix' => $this->routePrefix, - 'route_name_prefix' => $this->routeNamePrefix, - 'bundle' => $this->bundle->getName(), - 'entity' => $this->entity, - )); + $this->renderFile( + 'rest/config/routing.' . $this->format . '.twig', + $target, + array( + 'actions' => $this->actions, + 'route_prefix' => $this->routePrefix, + 'route_name_prefix' => $this->routeNamePrefix, + 'bundle' => $this->bundle->getName(), + 'entity' => $this->entity, + ) + ); } /** @@ -144,17 +160,166 @@ protected function generateControllerClass($forceOverwrite) throw new \RuntimeException('Unable to generate the controller as it already exists.'); } - $this->renderFile('rest/controller.php.twig', $target, array( - 'actions' => $this->actions, - 'route_prefix' => $this->routePrefix, - 'route_name_prefix' => $this->routeNamePrefix, - 'bundle' => $this->bundle->getName(), - 'entity' => $this->entity, - 'entity_class' => $entityClass, - 'namespace' => $this->bundle->getNamespace(), - 'entity_namespace' => $entityNamespace, - 'format' => $this->format, - )); + $this->renderFile( + 'rest/controller.php.twig', + $target, + array( + 'route_prefix' => $this->routePrefix, + 'route_name_prefix' => $this->routeNamePrefix, + 'bundle' => $this->bundle->getName(), + 'entity' => $this->entity, + 'entity_class' => $entityClass, + 'namespace' => $this->bundle->getNamespace(), + 'entity_namespace' => $entityNamespace, + 'format' => $this->format, + ) + ); + } + + /** + * Generates the Handle only. + */ + protected function generateHandler($forceOverwrite) + { + $dir = $this->bundle->getPath(); + + $parts = explode('\\', $this->entity); + $entityClass = array_pop($parts); + $entityNamespace = implode('\\', $parts); + + $target = sprintf( + '%s/Handler/%s/%sRESTHandler.php', + $dir, + str_replace('\\', '/', $entityNamespace), + $entityClass + ); + + if (!is_dir(dirname($target))) { + mkdir(dirname($target), 0777, true); + } + + if (!$forceOverwrite && file_exists($target)) { + throw new \RuntimeException('Unable to generate the controller as it already exists.'); + } + + $this->renderFile( + 'rest/handler.php.twig', + $target, + array( + 'route_prefix' => $this->routePrefix, + 'route_name_prefix' => $this->routeNamePrefix, + 'bundle' => $this->bundle->getName(), + 'entity' => $this->entity, + 'entity_class' => $entityClass, + 'namespace' => $this->bundle->getNamespace(), + 'entity_namespace' => $entityNamespace, + 'format' => $this->format, + ) + ); + } + + public function generateExceptionClass() + { + $dir = $this->bundle->getPath(); + + $target = sprintf('%s/Exception/InvalidFormException.php', $dir); + + if (!is_dir(dirname($target))) { + mkdir(dirname($target), 0777, true); + } + + $this->renderFile( + 'rest/form_exception.php.twig', + $target, + array('namespace' => $this->bundle->getNamespace()) + ); + } + + /** + * Declares the handler as a service + */ + public function declareService() + { + $dir = $this->bundle->getPath(); + + $parts = explode('\\', $this->entity); + $entityClass = array_pop($parts); + $entityNamespace = implode('\\', $parts); + $namespace = $this->bundle->getNamespace(); + + $bundleName = strtolower($this->bundle->getName()); + $entityName = strtolower($this->entity); + + $services = sprintf( + "%s/Resources/config/servicesREST.xml", + $dir + ); + + $handlerClass = sprintf( + "%s\\Handler\\%s%sRESTHandler", + $namespace, + $entityNamespace, + $entityClass + ); + + $newId = sprintf( + "%s.%s.handler", + str_replace("bundle", "", $bundleName), + $entityName + ); + + $fileName = sprintf( + "%s/DependencyInjection/%s.php", + $dir, + str_replace("Bundle", "Extension", $this->bundle->getName()) + ); + + if (!is_file($services)) { + $this->renderFile("rest/service/services.xml.twig", $services, array()); + } + + $newXML = simplexml_load_file($services); + + if (!($servicesTag = $newXML->services)) { + $servicesTag = $newXML->addChild("services"); + } + + $search = $newXML->xpath("//*[@id='$newId']"); + if(!$search) { + $newServiceTag = $servicesTag->addChild("service"); + $newServiceTag->addAttribute("id", $newId); + $newServiceTag->addAttribute("class", $handlerClass); + + $entityManagerTag = $newServiceTag->addChild("argument"); + $entityManagerTag->addAttribute("type", "service"); + $entityManagerTag->addAttribute("id", "doctrine.orm.entity_manager"); + + $newServiceTag->addChild( + "argument", + sprintf( + "%s\\Entity\\%s%s", + $namespace, + $entityNamespace, + $entityClass + ) + ); + + $formFactoryTag = $newServiceTag->addChild("argument"); + $formFactoryTag->addAttribute("type", "service"); + $formFactoryTag->addAttribute("id", "form.factory"); + } + + $newXML->saveXML($services); + + $content = file_get_contents($fileName); + if (!strpos($content, "servicesREST.xml")) { + $content = str_replace("}", "", $content); + + $content .= "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . + "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t}" . PHP_EOL . "}"; + + file_put_contents($fileName, $content); + } } /** @@ -167,20 +332,29 @@ protected function generateTestClass() $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); - $dir = $this->bundle->getPath() .'/Tests/Controller'; - $target = $dir .'/'. str_replace('\\', '/', $entityNamespace).'/'. $entityClass .'RESTControllerTest.php'; - - $this->renderFile('rest/tests/test.php.twig', $target, array( - 'route_prefix' => $this->routePrefix, - 'route_name_prefix' => $this->routeNamePrefix, - 'entity' => $this->entity, - 'bundle' => $this->bundle->getName(), - 'entity_class' => $entityClass, - 'namespace' => $this->bundle->getNamespace(), - 'entity_namespace' => $entityNamespace, - 'actions' => $this->actions, - 'form_type_name' => strtolower(str_replace('\\', '_', $this->bundle->getNamespace()).($parts ? '_' : '').implode('_', $parts).'_'.$entityClass.'Type'), - )); + $dir = $this->bundle->getPath() . '/Tests/Controller'; + $target = $dir . '/' . str_replace('\\', '/', $entityNamespace) . '/' . $entityClass . 'RESTControllerTest.php'; + + $this->renderFile( + 'rest/tests/test.php.twig', + $target, + array( + 'route_prefix' => $this->routePrefix, + 'route_name_prefix' => $this->routeNamePrefix, + 'entity' => $this->entity, + 'bundle' => $this->bundle->getName(), + 'entity_class' => $entityClass, + 'namespace' => $this->bundle->getNamespace(), + 'entity_namespace' => $entityNamespace, + 'actions' => $this->actions, + 'form_type_name' => strtolower( + str_replace('\\', '_', $this->bundle->getNamespace()) . ($parts ? '_' : '') . implode( + '_', + $parts + ) . '_' . $entityClass . 'Type' + ), + ) + ); } } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig old mode 100644 new mode 100755 index 9021817..7511e13 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -15,18 +15,15 @@ {% endblock phpdoc_method_annotations %} */ {% block method_definition %} - public function deleteAction(Request $request, {{ entity }} $entity) + public function deleteAction($id) {% endblock method_definition %} { {% block method_body %} + ${{ entity|lower }} = $this->getOr404($id); try { - $em = $this->getDoctrine()->getManager(); - $em->remove($entity); - $em->flush(); - - return null; - } catch (\Exception $e) { - return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR); + return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); + } catch (\Exception $exception) { + return $exception; } {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig old mode 100644 new mode 100755 index 0acdc63..e9f44bf --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -22,22 +22,16 @@ {% endblock method_definition %} { {% block method_body %} - try { - $offset = $paramFetcher->get('offset'); - $limit = $paramFetcher->get('limit'); - $order_by = $paramFetcher->get('order_by'); - $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); + $offset = $paramFetcher->get('offset'); + $limit = $paramFetcher->get('limit'); + $order_by = $paramFetcher->get('order_by'); + $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); - $em = $this->getDoctrine()->getManager(); - $entities = $em->getRepository('{{ bundle }}:{{ entity }}')->findBy($filters, $order_by, $limit, $offset); - if ($entities) { - return $entities; - } - - return FOSView::create('Not Found', Codes::HTTP_NO_CONTENT); - } catch (\Exception $e) { - return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR); + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); + if ($answer['{{ entity|lower }}']) { + return $answer; } + return null; {% endblock method_body %} {% block method_return '' %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig old mode 100644 new mode 100755 index 848910e..4461e82 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -13,11 +13,12 @@ {% endblock phpdoc_method_annotations %} */ {% block method_definition %} - public function getAction({{ entity }} $entity) + public function getAction($id) {% endblock method_definition %} { {% block method_body %} - return $entity; + $answer['{{ entity|lower }}'] = $this->getOr404($id); + return $answer; {% endblock method_body %} {% block method_return '' %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig new file mode 100644 index 0000000..35ded1b --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig @@ -0,0 +1,14 @@ + +{% block method_definition %} + protected function getOr404($id) +{% endblock method_definition %} + { +{% block method_body %} + if (!($entity = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id))) { + throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$id)); + } + + return $entity; +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig old mode 100644 new mode 100755 index 323cb7a..fb43876 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -14,11 +14,12 @@ {% endblock phpdoc_method_annotations %} */ {% block method_definition %} - public function patchAction(Request $request, {{ entity }} $entity) + public function patchAction(Request $request, $id) {% endblock method_definition %} { {% block method_body %} - return $this->putAction($request, $entity); + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); + return $answer; {% endblock method_body %} {% block method_return '' %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig old mode 100644 new mode 100755 index 54beeec..47c604b --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -18,22 +18,14 @@ {% endblock method_definition %} { {% block method_body %} - $entity = new {{ entity }}(); - $form = $this->createForm(new {{ entity }}Type(), $entity, array("method" => $request->getMethod())); - $this->removeExtraFields($request, $form); - $form->handleRequest($request); + try { + $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $answer['{{ entity|lower }}'] = $new; - if ($form->isValid()) { - $em = $this->getDoctrine()->getManager(); - $em->persist($entity); - $em->flush(); - - return $entity; + return $answer; + } catch (InvalidFormException $exception) { + return $exception->getForm(); } - {% endblock method_body %} -{% block method_return %} - return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR); -{% endblock method_return %} } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig old mode 100644 new mode 100755 index 31cf008..7d39cd5 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -14,26 +14,24 @@ {% endblock phpdoc_method_annotations %} */ {% block method_definition %} - public function putAction(Request $request, {{ entity }} $entity) + public function putAction(Request $request, $id) {% endblock method_definition %} { {% block method_body %} try { - $em = $this->getDoctrine()->getManager(); - $request->setMethod('PATCH'); //Treat all PUTs as PATCH - $form = $this->createForm(new {{ entity }}Type(), $entity, array("method" => $request->getMethod())); - $this->removeExtraFields($request, $form); - $form->handleRequest($request); - if ($form->isValid()) { - $em->flush(); - - return $entity; + if ($bairro = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + $code = Codes::HTTP_OK; + } else { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $code = Codes::HTTP_CREATED; } - - return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR); - } catch (\Exception $e) { - return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR); + } catch (InvalidFormException $exception) { + return $exception->getForm(); } + + $view = $this->view($answer, $code); + return $this->handleView($view); {% endblock method_body %} {% block method_return '' %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig old mode 100644 new mode 100755 index 6cf716a..6ffcb8e --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -5,6 +5,7 @@ namespace {{ namespace }}\Controller{{ entity_namespace ? '\\' ~ entity_namespac {% block use_statements %} use {{ namespace }}\Entity\{{ entity }}; use {{ namespace }}\Form\{{ entity }}Type; +use {{ namespace }}\Exception\InvalidFormException; use FOS\RestBundle\Controller\Annotations\QueryParam; use FOS\RestBundle\Controller\Annotations\RouteResource; @@ -22,8 +23,9 @@ use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use Voryx\RESTGeneratorBundle\Controller\VoryxController; +use FOS\RestBundle\Controller\FOSRestController; {% endblock use_statements %} /** @@ -38,7 +40,7 @@ use Voryx\RESTGeneratorBundle\Controller\VoryxController; {% endblock phpdoc_class_annotations %} */ {% block class_definition %} -class {{ entity_class }}RESTController extends VoryxController +class {{ entity_class }}RESTController extends FOSRestController {% endblock class_definition %} { {% block class_body %} @@ -53,5 +55,7 @@ class {{ entity_class }}RESTController extends VoryxController {%- include 'rest/actions/patch.php.twig' %} {%- include 'rest/actions/delete.php.twig' %} + + {%- include 'rest/actions/getOr404.php.twig' %} {% endblock class_body %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/form_exception.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/form_exception.php.twig new file mode 100644 index 0000000..14a0b4c --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/form_exception.php.twig @@ -0,0 +1,29 @@ +form = $form; + } + + public function getForm() + { + return $this->form; + } +{% endblock class_body %} +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig new file mode 100644 index 0000000..0eaeace --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig @@ -0,0 +1,43 @@ +om = $om; + $this->entityClass = $entityClass; + $this->repository = $this->om->getRepository($this->entityClass); + $this->formFactory = $formFactory; +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig new file mode 100644 index 0000000..c5ead31 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -0,0 +1,16 @@ +{% block method_definition %} + public function delete({{ entity }} ${{ entity|lower }}) +{% endblock method_definition %} + { +{% block method_body %} + try { + $this->om->remove(${{ entity|lower }}); + $this->om->flush(); + + return null; + } catch (\Exception $e) { + throw new \RuntimeException("Exclusion not allowed"); + } +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig new file mode 100644 index 0000000..903caf5 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -0,0 +1,20 @@ +{% block extras_methods %} + private function processForm({{ entity }} ${{ entity|lower }}, array $parameters, $method = "PUT") + { + $form = $this->formFactory->create(new {{ entity }}Type(), ${{ entity|lower }}, array('method' => $method)); + $form->submit($parameters, 'PATCH' !== $method); + if ($form->isValid()) { + ${{ entity|lower }} = $form->getData(); + $this->om->persist(${{ entity|lower }}); + $this->om->flush(${{ entity|lower }}); + + return ${{ entity|lower }}; + } + throw new InvalidFormException('Invalid submitted data', $form); + } + + private function create{{ entity }}() + { + return new $this->entityClass(); + } +{% endblock extras_methods %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig new file mode 100644 index 0000000..202e2e7 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig @@ -0,0 +1,9 @@ +{% block method_definition %} + public function get($id) +{% endblock method_definition %} + { +{% block method_body %} + return $this->repository->find($id); +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig new file mode 100644 index 0000000..74fa0b5 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -0,0 +1,9 @@ +{% block method_definition %} + public function getAll($filters, $order_by, $limit, $offset) +{% endblock method_definition %} + { +{% block method_body %} + return $this->repository->findBy($filters, $order_by, $limit, $offset); +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig new file mode 100644 index 0000000..fbe9b54 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig @@ -0,0 +1,9 @@ +{% block method_definition %} + public function patch({{ entity }} ${{ entity|lower }}, array $parameters) +{% endblock method_definition %} + { +{% block method_body %} + return $this->processForm(${{ entity|lower }}, $parameters, 'PATCH'); +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig new file mode 100644 index 0000000..7cfa712 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig @@ -0,0 +1,11 @@ +{% block method_definition %} + public function post($parameters) +{% endblock method_definition %} + { +{% block method_body %} + ${{ entity|lower }} = $this->create{{ entity }}(); + + return $this->processForm(${{ entity|lower }}, $parameters, 'POST'); +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig new file mode 100644 index 0000000..5c44191 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig @@ -0,0 +1,9 @@ +{% block method_definition %} + public function put({{ entity }} ${{ entity|lower }}, array $parameters) +{% endblock method_definition %} + { +{% block method_body %} + return $this->processForm(${{ entity|lower }}, $parameters, 'PUT'); +{% endblock method_body %} + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.xml.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.xml.twig new file mode 100644 index 0000000..124152f --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.xml.twig @@ -0,0 +1,6 @@ + + + + \ No newline at end of file From 8c096804093c0bb3b74f5bc61afb01a7c179f5d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 13:38:11 -0400 Subject: [PATCH 03/46] Revert "Initial test" This reverts commit 5a13dd349936410681bd1637c8e290fe3569fb90. Only a commit test --- .../Resources/skeleton/rest/actions/delete.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 7511e13..2dce68a 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -1,6 +1,6 @@ /** {% block phpdoc_method_header %} - * Delete a {{ entity }} entity. Wberredo version + * Delete a {{ entity }} entity. * * @View(statusCode=204) * From 812692d30a9b228816737066ab36ef74b2af1dc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 14:19:12 -0400 Subject: [PATCH 04/46] restore VoryxController class, for older controllers. --- .../Controller/VoryxController.php | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php diff --git a/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php b/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php new file mode 100644 index 0000000..95847dd --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Controller/VoryxController.php @@ -0,0 +1,41 @@ +container->get('form.factory')->createNamed( + null, //since we're not including the form name in the request, set this to null + $type, + $data, + $options + ); + return $form; + } + /** + * Get rid on any fields that don't appear in the form + * + * @param Request $request + * @param Form $form + */ + protected function removeExtraFields(Request $request, Form $form) + { + $data = $request->request->all(); + $children = $form->all(); + $data = array_intersect_key($data, $children); + $request->request->replace($data); + } +} \ No newline at end of file From eb08d00b8b855b350481697ffe1f661d72256133 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 14:42:48 -0400 Subject: [PATCH 05/46] refactory of put template --- .../Resources/skeleton/rest/actions/put.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 7d39cd5..c8cd398 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -19,7 +19,7 @@ { {% block method_body %} try { - if ($bairro = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { + if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); $code = Codes::HTTP_OK; } else { From 28d43e9ebca0d3875ec772f4b8514a63eaf9f7db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 16:27:41 -0400 Subject: [PATCH 06/46] Use the NelmioApiDocBundle to document the API --- README.md | 3 +++ composer.json | 3 ++- .../Resources/skeleton/rest/actions/delete.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/getAll.php.twig | 8 ++++++++ .../Resources/skeleton/rest/actions/getById.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/getOr404.php.twig | 0 .../Resources/skeleton/rest/actions/patch.php.twig | 10 ++++++++++ .../Resources/skeleton/rest/actions/post.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/put.php.twig | 11 +++++++++++ 9 files changed, 61 insertions(+), 1 deletion(-) mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig diff --git a/README.md b/README.md index af64c7c..2e0b399 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ public function registerBundles() new FOS\RestBundle\FOSRestBundle(), new JMS\SerializerBundle\JMSSerializerBundle($this), new Nelmio\CorsBundle\NelmioCorsBundle(), + new Nelmio\ApiDocBundle\NelmioApiDocBundle(), //... ); //... @@ -73,6 +74,8 @@ sensio_framework_extra: request: { converters: true } view: { annotations: false } router: { annotations: true } + +nelmio_api_doc: ~ ``` ## Generating the Controller diff --git a/composer.json b/composer.json index 1aab61a..533e3cb 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "php": ">=5.3.0", "friendsofsymfony/rest-bundle": "1.4.*", "jms/serializer-bundle": "0.13.*", - "nelmio/cors-bundle": "1.3.*" + "nelmio/cors-bundle": "1.3.*", + "nelmio/api-doc-bundle": "~2.7" }, "autoload": { "psr-0": { diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 2dce68a..c282306 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Delete a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Delete a {{ entity }} entity.", + * statusCodes = { + * 204 = "No content. Successfully excluded.", + * 404 = "Not found." + * } + * ) + * * @View(statusCode=204) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index e9f44bf..33bb934 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -2,6 +2,14 @@ {% block phpdoc_method_header %} * Get all {{ entity }} entities. * + * @ApiDoc( + * resource = true, + * description = "Get all {{ entity }} entities.", + * statusCodes = { + * 200 = "List of {{ entity }}", + * 204 = "No content. Nothing to list." + * } + * ) * @View(serializerEnableMaxDepthChecks=true) * * @param ParamFetcherInterface $paramFetcher diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 4461e82..55aaeaa 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Get a {{ entity }} entity * + * @ApiDoc( + * resource = true, + * description = "Get a {{ entity }} entity.", + * statusCodes = { + * 200 = "{{ entity }}'s object.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @return Response diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig old mode 100644 new mode 100755 diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index fb43876..45ccd01 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -2,6 +2,16 @@ {% block phpdoc_method_header %} * Partial Update to a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Partial Update to a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 47c604b..2f88538 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Create a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Create a {{ entity }} entity.", + * statusCodes = { + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) * @View(statusCode=201, serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index c8cd398..81fdcbc 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -2,6 +2,17 @@ {% block phpdoc_method_header %} * Update a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Update a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request From 72219c34580700805c348c000bf0f9d4cade64aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Thu, 20 Nov 2014 16:27:41 -0400 Subject: [PATCH 07/46] Add 'use' statement to NelmioAPiDoc --- README.md | 3 +++ composer.json | 3 ++- .../Resources/skeleton/rest/actions/delete.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/getAll.php.twig | 8 ++++++++ .../Resources/skeleton/rest/actions/getById.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/getOr404.php.twig | 0 .../Resources/skeleton/rest/actions/patch.php.twig | 10 ++++++++++ .../Resources/skeleton/rest/actions/post.php.twig | 9 +++++++++ .../Resources/skeleton/rest/actions/put.php.twig | 11 +++++++++++ .../Resources/skeleton/rest/controller.php.twig | 1 + 10 files changed, 62 insertions(+), 1 deletion(-) mode change 100644 => 100755 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig diff --git a/README.md b/README.md index af64c7c..2e0b399 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ public function registerBundles() new FOS\RestBundle\FOSRestBundle(), new JMS\SerializerBundle\JMSSerializerBundle($this), new Nelmio\CorsBundle\NelmioCorsBundle(), + new Nelmio\ApiDocBundle\NelmioApiDocBundle(), //... ); //... @@ -73,6 +74,8 @@ sensio_framework_extra: request: { converters: true } view: { annotations: false } router: { annotations: true } + +nelmio_api_doc: ~ ``` ## Generating the Controller diff --git a/composer.json b/composer.json index 1aab61a..533e3cb 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "php": ">=5.3.0", "friendsofsymfony/rest-bundle": "1.4.*", "jms/serializer-bundle": "0.13.*", - "nelmio/cors-bundle": "1.3.*" + "nelmio/cors-bundle": "1.3.*", + "nelmio/api-doc-bundle": "~2.7" }, "autoload": { "psr-0": { diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 2dce68a..c282306 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Delete a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Delete a {{ entity }} entity.", + * statusCodes = { + * 204 = "No content. Successfully excluded.", + * 404 = "Not found." + * } + * ) + * * @View(statusCode=204) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index e9f44bf..33bb934 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -2,6 +2,14 @@ {% block phpdoc_method_header %} * Get all {{ entity }} entities. * + * @ApiDoc( + * resource = true, + * description = "Get all {{ entity }} entities.", + * statusCodes = { + * 200 = "List of {{ entity }}", + * 204 = "No content. Nothing to list." + * } + * ) * @View(serializerEnableMaxDepthChecks=true) * * @param ParamFetcherInterface $paramFetcher diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 4461e82..55aaeaa 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Get a {{ entity }} entity * + * @ApiDoc( + * resource = true, + * description = "Get a {{ entity }} entity.", + * statusCodes = { + * 200 = "{{ entity }}'s object.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @return Response diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig old mode 100644 new mode 100755 diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index fb43876..45ccd01 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -2,6 +2,16 @@ {% block phpdoc_method_header %} * Partial Update to a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Partial Update to a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 47c604b..2f88538 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -2,6 +2,15 @@ {% block phpdoc_method_header %} * Create a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Create a {{ entity }} entity.", + * statusCodes = { + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) * @View(statusCode=201, serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index c8cd398..81fdcbc 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -2,6 +2,17 @@ {% block phpdoc_method_header %} * Update a {{ entity }} entity. * + * @ApiDoc( + * resource = true, + * description = "Update a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + * * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig index 6ffcb8e..1794ea2 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -26,6 +26,7 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use FOS\RestBundle\Controller\FOSRestController; +use Nelmio\ApiDocBundle\Annotation\ApiDoc; {% endblock use_statements %} /** From 5c1b219f815dd8416e5f2ffc10f3e8cb330d0cd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 10:45:07 -0400 Subject: [PATCH 08/46] Fix the function that update DependencyInjection file --- .../Generator/DoctrineRESTGenerator.php | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index ccef8a1..28c6504 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -310,18 +310,25 @@ public function declareService() } $newXML->saveXML($services); + $this->updateDIFile($fileName); + } + + private function updateDIFile($fileName) + { + $toInput = PHP_EOL."\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" .PHP_EOL. + "\t\t\$loader2->load('servicesREST.xml');".PHP_EOL."\t"; - $content = file_get_contents($fileName); - if (!strpos($content, "servicesREST.xml")) { - $content = str_replace("}", "", $content); + $text = file_get_contents($fileName); - $content .= "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . - "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t}" . PHP_EOL . "}"; + if (strpos($text, "servicesREST.xml") == false) { + $position = strpos($text, "}", strpos($text, "function load(")); - file_put_contents($fileName, $content); + $newContent = substr_replace($text, $toInput, $position, 0); + file_put_contents($fileName, $newContent); } } + /** * Generates the functional test class only. * From e12a93b828261be7cf9864db4eb0961bda86baef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 14:57:44 -0400 Subject: [PATCH 09/46] Make documentation be optional --- .../Command/GenerateDoctrineRESTCommand.php | 54 ++++++------- .../Generator/DoctrineRESTGenerator.php | 8 +- .../skeleton/rest/actions/delete.php.twig | 61 ++++++++------- .../skeleton/rest/actions/getAll.php.twig | 72 +++++++++-------- .../skeleton/rest/actions/getById.php.twig | 49 ++++++------ .../skeleton/rest/actions/patch.php.twig | 51 ++++++------ .../skeleton/rest/actions/post.php.twig | 62 ++++++++------- .../skeleton/rest/actions/put.php.twig | 77 ++++++++++--------- .../skeleton/rest/controller.php.twig | 2 + 9 files changed, 231 insertions(+), 205 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 65ed376..821ce40 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -33,10 +33,11 @@ protected function configure() { $this ->setDefinition(array( - new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), - new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), - new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), - )) + new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), + new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), + new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), + new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller') + )) ->setDescription('Generates a REST api based on a Doctrine entity') ->setHelp(<<voryx:generate:rest command generates a REST api based on a Doctrine entity. @@ -88,9 +89,10 @@ protected function execute(InputInterface $input, OutputInterface $output) $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle).'\\'.$entity; $metadata = $this->getEntityMetadata($entityClass); $bundle = $this->getContainer()->get('kernel')->getBundle($bundle); + $document = $input->getOption('document'); $generator = $this->getGenerator($bundle); - $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite); + $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $document); $output->writeln('Generating the REST api code: OK'); @@ -116,16 +118,16 @@ protected function interact(InputInterface $input, OutputInterface $output) // namespace $output->writeln(array( - '', - 'This command helps you generate a REST api controller.', - '', - 'First, you need to give the entity for which you want to generate a REST api.', - 'You can give an entity that does not exist yet and the wizard will help', - 'you defining it.', - '', - 'You must use the shortcut notation like AcmeBlogBundle:Post.', - '', - )); + '', + 'This command helps you generate a REST api controller.', + '', + 'First, you need to give the entity for which you want to generate a REST api.', + 'You can give an entity that does not exist yet and the wizard will help', + 'you defining it.', + '', + 'You must use the shortcut notation like AcmeBlogBundle:Post.', + '', + )); $entity = $dialog->askAndValidate($output, $dialog->getQuestion('The Entity shortcut name', $input->getOption('entity')), array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateEntityName'), false, $input->getOption('entity')); $input->setOption('entity', $entity); @@ -134,22 +136,22 @@ protected function interact(InputInterface $input, OutputInterface $output) // route prefix $prefix = $this->getRoutePrefix($input, $entity); $output->writeln(array( - '', - 'Determine the routes prefix (all the routes will be "mounted" under this', - 'prefix: /prefix/, /prefix/new, ...).', - '', - )); + '', + 'Determine the routes prefix (all the routes will be "mounted" under this', + 'prefix: /prefix/, /prefix/new, ...).', + '', + )); $prefix = $dialog->ask($output, $dialog->getQuestion('Routes prefix', '/'.$prefix), '/'.$prefix); $input->setOption('route-prefix', $prefix); // summary $output->writeln(array( - '', - $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), - '', - sprintf("You are going to generate a REST api controller for \"%s:%s\"", $bundle, $entity), - '', - )); + '', + $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), + '', + sprintf("You are going to generate a REST api controller for \"%s:%s\"", $bundle, $entity), + '', + )); } /** diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 28c6504..25f9321 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -58,7 +58,8 @@ public function generate( $entity, ClassMetadataInfo $metadata, $routePrefix, - $forceOverwrite + $forceOverwrite, + $document ) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = str_replace('/', '_', $routePrefix); @@ -81,7 +82,7 @@ public function generate( $this->metadata = $metadata; $this->setFormat('yml'); - $this->generateControllerClass($forceOverwrite); + $this->generateControllerClass($forceOverwrite, $document); $this->generateHandler($forceOverwrite); $this->generateExceptionClass(); $this->declareService(); @@ -141,7 +142,7 @@ protected function generateConfiguration() * Generates the controller class only. * */ - protected function generateControllerClass($forceOverwrite) + protected function generateControllerClass($forceOverwrite, $document) { $dir = $this->bundle->getPath(); @@ -172,6 +173,7 @@ protected function generateControllerClass($forceOverwrite) 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, + 'document' => $document, ) ); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index c282306..a7357e5 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -1,40 +1,43 @@ - /** +/** {% block phpdoc_method_header %} - * Delete a {{ entity }} entity. - * - * @ApiDoc( - * resource = true, - * description = "Delete a {{ entity }} entity.", - * statusCodes = { - * 204 = "No content. Successfully excluded.", - * 404 = "Not found." - * } - * ) - * - * @View(statusCode=204) - * - * @param Request $request - * @param $entity - * @internal param $id - * - * @return Response + * Delete a {{ entity }} entity. + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Delete a {{ entity }} entity.", + * statusCodes = { + * 204 = "No content. Successfully excluded.", + * 404 = "Not found." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(statusCode=204) + * + * @param Request $request + * @param $entity + * @internal param $id + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} + {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ +*/ {% block method_definition %} public function deleteAction($id) {% endblock method_definition %} - { +{ {% block method_body %} - ${{ entity|lower }} = $this->getOr404($id); - try { - return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); - } catch (\Exception $exception) { - return $exception; - } + ${{ entity|lower }} = $this->getOr404($id); + try { + return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); + } catch (\Exception $exception) { + return $exception; + } {% endblock method_body %} {% block method_return '' %} - } +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 33bb934..8845fe3 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -1,46 +1,50 @@ - /** +/** {% block phpdoc_method_header %} - * Get all {{ entity }} entities. - * - * @ApiDoc( - * resource = true, - * description = "Get all {{ entity }} entities.", - * statusCodes = { - * 200 = "List of {{ entity }}", - * 204 = "No content. Nothing to list." - * } - * ) - * @View(serializerEnableMaxDepthChecks=true) - * - * @param ParamFetcherInterface $paramFetcher - * - * @return Response - * - * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.") - * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.") - * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC") - * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") + * Get all {{ entity }} entities. + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Get all {{ entity }} entities.", + * statusCodes = { + * 200 = "List of {{ entity }}", + * 204 = "No content. Nothing to list." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(serializerEnableMaxDepthChecks=true) + * + * @param ParamFetcherInterface $paramFetcher + * + * @return Response + * + * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.") + * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.") + * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC") + * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} + {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ +*/ {% block method_definition %} public function cgetAction(ParamFetcherInterface $paramFetcher) {% endblock method_definition %} - { +{ {% block method_body %} - $offset = $paramFetcher->get('offset'); - $limit = $paramFetcher->get('limit'); - $order_by = $paramFetcher->get('order_by'); - $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); + $offset = $paramFetcher->get('offset'); + $limit = $paramFetcher->get('limit'); + $order_by = $paramFetcher->get('order_by'); + $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); - if ($answer['{{ entity|lower }}']) { - return $answer; - } - return null; + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); + if ($answer['{{ entity|lower }}']) { + return $answer; + } + return null; {% endblock method_body %} {% block method_return '' %} - } +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 55aaeaa..9f4f5c8 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -1,34 +1,37 @@ - /** +/** {% block phpdoc_method_header %} - * Get a {{ entity }} entity - * - * @ApiDoc( - * resource = true, - * description = "Get a {{ entity }} entity.", - * statusCodes = { - * 200 = "{{ entity }}'s object.", - * 404 = "Not Found." - * } - * ) - * - * @View(serializerEnableMaxDepthChecks=true) - * - * @return Response + * Get a {{ entity }} entity + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Get a {{ entity }} entity.", + * statusCodes = { + * 200 = "{{ entity }}'s object.", + * 404 = "Not Found." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(serializerEnableMaxDepthChecks=true) + * + * @return Response {% endblock phpdoc_method_header %} - * +* {% block phpdoc_method_annotations %} -{% if 'annotation' == format %} -{% endif %} + {% if 'annotation' == format %} + {% endif %} {% endblock phpdoc_method_annotations %} - */ +*/ {% block method_definition %} public function getAction($id) {% endblock method_definition %} - { +{ {% block method_body %} - $answer['{{ entity|lower }}'] = $this->getOr404($id); - return $answer; + $answer['{{ entity|lower }}'] = $this->getOr404($id); + return $answer; {% endblock method_body %} {% block method_return '' %} - } +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 45ccd01..13c53ca 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -1,36 +1,39 @@ - /** +/** {% block phpdoc_method_header %} - * Partial Update to a {{ entity }} entity. - * - * @ApiDoc( - * resource = true, - * description = "Partial Update to a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - * - * @View(serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * @param $entity - * - * @return Response + * Partial Update to a {{ entity }} entity. + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Partial Update to a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * @param $entity + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} + {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} */ {% block method_definition %} public function patchAction(Request $request, $id) {% endblock method_definition %} - { +{ {% block method_body %} - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); - return $answer; + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); + return $answer; {% endblock method_body %} {% block method_return '' %} - } +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 2f88538..0ae9e24 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -1,40 +1,44 @@ - /** +/** {% block phpdoc_method_header %} - * Create a {{ entity }} entity. - * - * @ApiDoc( - * resource = true, - * description = "Create a {{ entity }} entity.", - * statusCodes = { - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - * @View(statusCode=201, serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * - * @return Response + * Create a {{ entity }} entity. + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Create a {{ entity }} entity.", + * statusCodes = { + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(statusCode=201, serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * + * @return Response {% endblock phpdoc_method_header %} - * +* {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} + {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ +*/ {% block method_definition %} public function postAction(Request $request) {% endblock method_definition %} - { +{ {% block method_body %} - try { - $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - $answer['{{ entity|lower }}'] = $new; + try { + $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $answer['{{ entity|lower }}'] = $new; - return $answer; - } catch (InvalidFormException $exception) { - return $exception->getForm(); - } -{% endblock method_body %} + return $answer; + } catch (InvalidFormException $exception) { + return $exception->getForm(); } +{% endblock method_body %} +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 81fdcbc..a728ffe 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -1,49 +1,52 @@ - /** +/** {% block phpdoc_method_header %} - * Update a {{ entity }} entity. - * - * @ApiDoc( - * resource = true, - * description = "Update a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - * - * @View(serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * @param $entity - * - * @return Response + * Update a {{ entity }} entity. + * + {% block documentation %} + {% if document %} + * @ApiDoc( + * resource = true, + * description = "Update a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) + {% endif %} + {% endblock documentation %} + * @View(serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * @param $entity + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} + {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ +*/ {% block method_definition %} public function putAction(Request $request, $id) {% endblock method_definition %} - { +{ {% block method_body %} - try { - if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); - $code = Codes::HTTP_OK; - } else { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - $code = Codes::HTTP_CREATED; - } - } catch (InvalidFormException $exception) { - return $exception->getForm(); - } + try { + if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + $code = Codes::HTTP_OK; + } else { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $code = Codes::HTTP_CREATED; + } + } catch (InvalidFormException $exception) { + return $exception->getForm(); + } - $view = $this->view($answer, $code); - return $this->handleView($view); + $view = $this->view($answer, $code); + return $this->handleView($view); {% endblock method_body %} {% block method_return '' %} - } +} {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig index 1794ea2..624a63c 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -26,7 +26,9 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use FOS\RestBundle\Controller\FOSRestController; +{% if document %} use Nelmio\ApiDocBundle\Annotation\ApiDoc; +{% endif %} {% endblock use_statements %} /** From a4f924772878249661cf2fdb1a98dbc202b448ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 15:04:01 -0400 Subject: [PATCH 10/46] Fix ident on documentation --- .../skeleton/rest/actions/delete.php.twig | 24 ++++++++-------- .../skeleton/rest/actions/getAll.php.twig | 24 ++++++++-------- .../skeleton/rest/actions/getById.php.twig | 24 ++++++++-------- .../skeleton/rest/actions/patch.php.twig | 26 ++++++++--------- .../skeleton/rest/actions/post.php.twig | 26 ++++++++--------- .../skeleton/rest/actions/put.php.twig | 28 +++++++++---------- 6 files changed, 76 insertions(+), 76 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index a7357e5..6207291 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -2,18 +2,18 @@ {% block phpdoc_method_header %} * Delete a {{ entity }} entity. * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Delete a {{ entity }} entity.", - * statusCodes = { - * 204 = "No content. Successfully excluded.", - * 404 = "Not found." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Delete a {{ entity }} entity.", + * statusCodes = { + * 204 = "No content. Successfully excluded.", + * 404 = "Not found." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(statusCode=204) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 8845fe3..84550be 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -2,18 +2,18 @@ {% block phpdoc_method_header %} * Get all {{ entity }} entities. * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Get all {{ entity }} entities.", - * statusCodes = { - * 200 = "List of {{ entity }}", - * 204 = "No content. Nothing to list." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Get all {{ entity }} entities.", + * statusCodes = { + * 200 = "List of {{ entity }}", + * 204 = "No content. Nothing to list." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(serializerEnableMaxDepthChecks=true) * * @param ParamFetcherInterface $paramFetcher diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 9f4f5c8..088485e 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -2,18 +2,18 @@ {% block phpdoc_method_header %} * Get a {{ entity }} entity * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Get a {{ entity }} entity.", - * statusCodes = { - * 200 = "{{ entity }}'s object.", - * 404 = "Not Found." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Get a {{ entity }} entity.", + * statusCodes = { + * 200 = "{{ entity }}'s object.", + * 404 = "Not Found." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(serializerEnableMaxDepthChecks=true) * * @return Response diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 13c53ca..bb801b7 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -2,19 +2,19 @@ {% block phpdoc_method_header %} * Partial Update to a {{ entity }} entity. * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Partial Update to a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Partial Update to a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 0ae9e24..28e21b0 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -2,19 +2,19 @@ {% block phpdoc_method_header %} * Create a {{ entity }} entity. * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Create a {{ entity }} entity.", - * statusCodes = { - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Create a {{ entity }} entity.", + * statusCodes = { + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(statusCode=201, serializerEnableMaxDepthChecks=true) * * @param Request $request diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index a728ffe..4b256c9 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -2,20 +2,20 @@ {% block phpdoc_method_header %} * Update a {{ entity }} entity. * - {% block documentation %} - {% if document %} - * @ApiDoc( - * resource = true, - * description = "Update a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) - {% endif %} - {% endblock documentation %} +{% block documentation %} +{% if document %} + * @ApiDoc( + * resource = true, + * description = "Update a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) +{% endif %} +{% endblock documentation %} * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request From ad5bc0736497955cfcd05f1eafd2ec1063b8ae35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 15:13:44 -0400 Subject: [PATCH 11/46] Indent of functions on controller --- .../skeleton/rest/actions/delete.php.twig | 16 +++++----- .../skeleton/rest/actions/getAll.php.twig | 22 +++++++------- .../skeleton/rest/actions/getById.php.twig | 9 +++--- .../skeleton/rest/actions/patch.php.twig | 8 ++--- .../skeleton/rest/actions/post.php.twig | 18 +++++------ .../skeleton/rest/actions/put.php.twig | 30 +++++++++---------- 6 files changed, 51 insertions(+), 52 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 6207291..f9db7e6 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -29,15 +29,15 @@ {% block method_definition %} public function deleteAction($id) {% endblock method_definition %} -{ + { {% block method_body %} - ${{ entity|lower }} = $this->getOr404($id); - try { - return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); - } catch (\Exception $exception) { - return $exception; - } + ${{ entity|lower }} = $this->getOr404($id); + try { + return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); + } catch (\Exception $exception) { + return $exception; + } {% endblock method_body %} {% block method_return '' %} -} + } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 84550be..d8de8f4 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -32,19 +32,19 @@ {% block method_definition %} public function cgetAction(ParamFetcherInterface $paramFetcher) {% endblock method_definition %} -{ + { {% block method_body %} - $offset = $paramFetcher->get('offset'); - $limit = $paramFetcher->get('limit'); - $order_by = $paramFetcher->get('order_by'); - $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); + $offset = $paramFetcher->get('offset'); + $limit = $paramFetcher->get('limit'); + $order_by = $paramFetcher->get('order_by'); + $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); - if ($answer['{{ entity|lower }}']) { - return $answer; - } - return null; + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); + if ($answer['{{ entity|lower }}']) { + return $answer; + } + return null; {% endblock method_body %} {% block method_return '' %} -} + } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 088485e..a4621e4 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -18,7 +18,6 @@ * * @return Response {% endblock phpdoc_method_header %} -* {% block phpdoc_method_annotations %} {% if 'annotation' == format %} {% endif %} @@ -27,11 +26,11 @@ {% block method_definition %} public function getAction($id) {% endblock method_definition %} -{ + { {% block method_body %} - $answer['{{ entity|lower }}'] = $this->getOr404($id); - return $answer; + $answer['{{ entity|lower }}'] = $this->getOr404($id); + return $answer; {% endblock method_body %} {% block method_return '' %} -} + } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index bb801b7..0a50021 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -29,11 +29,11 @@ {% block method_definition %} public function patchAction(Request $request, $id) {% endblock method_definition %} -{ + { {% block method_body %} - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); - return $answer; + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); + return $answer; {% endblock method_body %} {% block method_return '' %} -} + } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 28e21b0..4b639ae 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -29,16 +29,16 @@ {% block method_definition %} public function postAction(Request $request) {% endblock method_definition %} -{ + { {% block method_body %} - try { - $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - $answer['{{ entity|lower }}'] = $new; + try { + $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $answer['{{ entity|lower }}'] = $new; - return $answer; - } catch (InvalidFormException $exception) { - return $exception->getForm(); - } + return $answer; + } catch (InvalidFormException $exception) { + return $exception->getForm(); + } {% endblock method_body %} -} + } {% block form '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 4b256c9..14134e5 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -30,23 +30,23 @@ {% block method_definition %} public function putAction(Request $request, $id) {% endblock method_definition %} -{ + { {% block method_body %} - try { - if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); - $code = Codes::HTTP_OK; - } else { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - $code = Codes::HTTP_CREATED; - } - } catch (InvalidFormException $exception) { - return $exception->getForm(); - } + try { + if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + $code = Codes::HTTP_OK; + } else { + $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $code = Codes::HTTP_CREATED; + } + } catch (InvalidFormException $exception) { + return $exception->getForm(); + } - $view = $this->view($answer, $code); - return $this->handleView($view); + $view = $this->view($answer, $code); + return $this->handleView($view); {% endblock method_body %} {% block method_return '' %} -} + } {% block form '' %} From 19c410c0f2e4f813e99bc00a7598bed90d4d43f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 16:12:17 -0400 Subject: [PATCH 12/46] Make the resource as object be optional. --- .../Command/GenerateDoctrineRESTCommand.php | 132 +++++++++++++----- .../Generator/DoctrineRESTGenerator.php | 12 +- .../skeleton/rest/actions/delete.php.twig | 2 +- .../skeleton/rest/actions/getAll.php.twig | 6 +- .../skeleton/rest/actions/getById.php.twig | 4 +- .../skeleton/rest/actions/patch.php.twig | 4 +- .../skeleton/rest/actions/post.php.twig | 7 +- .../skeleton/rest/actions/put.php.twig | 6 +- 8 files changed, 119 insertions(+), 54 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 821ce40..568a4bc 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -32,15 +32,39 @@ class GenerateDoctrineRESTCommand extends GenerateDoctrineCommand protected function configure() { $this - ->setDefinition(array( - new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), + ->setDefinition( + array( + new InputOption( + 'entity', + '', + InputOption::VALUE_REQUIRED, + 'The entity class name to initialize (shortcut notation)' + ), new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), - new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), - new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller') - )) + new InputOption( + 'overwrite', + '', + InputOption::VALUE_NONE, + 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files' + ), + new InputOption( + 'resource', + '', + InputOption::VALUE_NONE, + 'The object will return with the resource name' + ), + new InputOption( + 'document', + '', + InputOption::VALUE_NONE, + 'Use NelmioApiDocBundle to document the controller' + ), + ) + ) ->setDescription('Generates a REST api based on a Doctrine entity') - ->setHelp(<<voryx:generate:rest command generates a REST api based on a Doctrine entity. + ->setHelp( + <<voryx:generate:rest command generates a REST api based on a Doctrine entity. php app/console voryx:generate:rest --entity=AcmeBlogBundle:Post --route-prefix=post_admin @@ -59,8 +83,7 @@ protected function configure() EOT ) ->setName('voryx:generate:rest') - ->setAliases(array('generate:voryx:rest')) - ; + ->setAliases(array('generate:voryx:rest')); } /** @@ -71,7 +94,12 @@ protected function execute(InputInterface $input, OutputInterface $output) $dialog = $this->getDialogHelper(); if ($input->isInteractive()) { - if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) { + if (!$dialog->askConfirmation( + $output, + $dialog->getQuestion('Do you confirm generation', 'yes', '?'), + true + ) + ) { $output->writeln('Command aborted'); return 1; @@ -86,13 +114,14 @@ protected function execute(InputInterface $input, OutputInterface $output) $dialog->writeSection($output, 'REST api generation'); - $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle).'\\'.$entity; - $metadata = $this->getEntityMetadata($entityClass); - $bundle = $this->getContainer()->get('kernel')->getBundle($bundle); - $document = $input->getOption('document'); + $entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle) . '\\' . $entity; + $metadata = $this->getEntityMetadata($entityClass); + $bundle = $this->getContainer()->get('kernel')->getBundle($bundle); + $resource = $input->getOption('resource'); + $document = $input->getOption('document'); $generator = $this->getGenerator($bundle); - $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $document); + $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document); $output->writeln('Generating the REST api code: OK'); @@ -117,7 +146,8 @@ protected function interact(InputInterface $input, OutputInterface $output) $dialog->writeSection($output, 'Welcome to the Doctrine2 REST api generator'); // namespace - $output->writeln(array( + $output->writeln( + array( '', 'This command helps you generate a REST api controller.', '', @@ -127,31 +157,42 @@ protected function interact(InputInterface $input, OutputInterface $output) '', 'You must use the shortcut notation like AcmeBlogBundle:Post.', '', - )); - - $entity = $dialog->askAndValidate($output, $dialog->getQuestion('The Entity shortcut name', $input->getOption('entity')), array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateEntityName'), false, $input->getOption('entity')); + ) + ); + + $entity = $dialog->askAndValidate( + $output, + $dialog->getQuestion('The Entity shortcut name', $input->getOption('entity')), + array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateEntityName'), + false, + $input->getOption('entity') + ); $input->setOption('entity', $entity); list($bundle, $entity) = $this->parseShortcutNotation($entity); // route prefix $prefix = $this->getRoutePrefix($input, $entity); - $output->writeln(array( + $output->writeln( + array( '', 'Determine the routes prefix (all the routes will be "mounted" under this', 'prefix: /prefix/, /prefix/new, ...).', '', - )); - $prefix = $dialog->ask($output, $dialog->getQuestion('Routes prefix', '/'.$prefix), '/'.$prefix); + ) + ); + $prefix = $dialog->ask($output, $dialog->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix); $input->setOption('route-prefix', $prefix); // summary - $output->writeln(array( + $output->writeln( + array( '', $this->getHelper('formatter')->formatBlock('Summary before generation', 'bg=blue;fg=white', true), '', sprintf("You are going to generate a REST api controller for \"%s:%s\"", $bundle, $entity), '', - )); + ) + ); } /** @@ -161,38 +202,61 @@ protected function generateForm($bundle, $entity, $metadata) { try { $this->getFormGenerator($bundle)->generate($bundle, $entity, $metadata[0]); - } catch (\RuntimeException $e ) { + } catch (\RuntimeException $e) { // form already exists } } - protected function updateRouting(DialogHelper $dialog, InputInterface $input, OutputInterface $output, BundleInterface $bundle, $entity, $prefix) - { + protected function updateRouting( + DialogHelper $dialog, + InputInterface $input, + OutputInterface $output, + BundleInterface $bundle, + $entity, + $prefix + ) { $auto = true; if ($input->isInteractive()) { - $auto = $dialog->askConfirmation($output, $dialog->getQuestion('Confirm automatic update of the Routing', 'yes', '?'), true); + $auto = $dialog->askConfirmation( + $output, + $dialog->getQuestion('Confirm automatic update of the Routing', 'yes', '?'), + true + ); } $output->write('Importing the REST api routes: '); - $this->getContainer()->get('filesystem')->mkdir($bundle->getPath().'/Resources/config/'); - $routing = new RoutingManipulator($bundle->getPath().'/Resources/config/routing.yml'); + $this->getContainer()->get('filesystem')->mkdir($bundle->getPath() . '/Resources/config/'); + $routing = new RoutingManipulator($bundle->getPath() . '/Resources/config/routing.yml'); try { // TODO: fix the format parameter - leaving it for now $format = "annotation"; - $ret = $auto ? $routing->addResource($bundle->getName(), $format, '/'.$prefix, 'routing/'.strtolower(str_replace('\\', '_', $entity))) : false; + $ret = $auto ? $routing->addResource( + $bundle->getName(), + $format, + '/' . $prefix, + 'routing/' . strtolower(str_replace('\\', '_', $entity)) + ) : false; } catch (\RuntimeException $exc) { $ret = false; } if (!$ret) { - $help = sprintf(" resource: \"@%s/Resources/config/routing/%s.%s\"\n", $bundle->getName(), strtolower(str_replace('\\', '_', $entity)), $format); + $help = sprintf( + " resource: \"@%s/Resources/config/routing/%s.%s\"\n", + $bundle->getName(), + strtolower(str_replace('\\', '_', $entity)), + $format + ); $help .= sprintf(" prefix: /%s\n", $prefix); return array( '- Import the bundle\'s routing resource in the bundle routing file', - sprintf(' (%s).', $bundle->getPath().'/Resources/config/routing.yml'), + sprintf(' (%s).', $bundle->getPath() . '/Resources/config/routing.yml'), '', - sprintf(' %s:', $bundle->getName().('' !== $prefix ? '_'.str_replace('/', '_', $prefix) : '')), + sprintf( + ' %s:', + $bundle->getName() . ('' !== $prefix ? '_' . str_replace('/', '_', $prefix) : '') + ), $help, '', ); diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 25f9321..64ff329 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -59,6 +59,7 @@ public function generate( ClassMetadataInfo $metadata, $routePrefix, $forceOverwrite, + $resource, $document ) { $this->routePrefix = $routePrefix; @@ -82,7 +83,7 @@ public function generate( $this->metadata = $metadata; $this->setFormat('yml'); - $this->generateControllerClass($forceOverwrite, $document); + $this->generateControllerClass($forceOverwrite, $document, $resource); $this->generateHandler($forceOverwrite); $this->generateExceptionClass(); $this->declareService(); @@ -142,7 +143,7 @@ protected function generateConfiguration() * Generates the controller class only. * */ - protected function generateControllerClass($forceOverwrite, $document) + protected function generateControllerClass($forceOverwrite, $document, $resource) { $dir = $this->bundle->getPath(); @@ -173,6 +174,7 @@ protected function generateControllerClass($forceOverwrite, $document) 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, + 'resource' => $resource, 'document' => $document, ) ); @@ -287,7 +289,7 @@ public function declareService() } $search = $newXML->xpath("//*[@id='$newId']"); - if(!$search) { + if (!$search) { $newServiceTag = $servicesTag->addChild("service"); $newServiceTag->addAttribute("id", $newId); $newServiceTag->addAttribute("class", $handlerClass); @@ -317,8 +319,8 @@ public function declareService() private function updateDIFile($fileName) { - $toInput = PHP_EOL."\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" .PHP_EOL. - "\t\t\$loader2->load('servicesREST.xml');".PHP_EOL."\t"; + $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . + "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; $text = file_get_contents($fileName); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index f9db7e6..37c4dce 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Delete a {{ entity }} entity. * diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index d8de8f4..50e3245 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Get all {{ entity }} entities. * @@ -39,8 +39,8 @@ $order_by = $paramFetcher->get('order_by'); $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); - if ($answer['{{ entity|lower }}']) { + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); + if ($answer{{ resource ? "['" ~ entity|lower ~ "']" }}) { return $answer; } return null; diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index a4621e4..45b14f8 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Get a {{ entity }} entity * @@ -28,7 +28,7 @@ {% endblock method_definition %} { {% block method_body %} - $answer['{{ entity|lower }}'] = $this->getOr404($id); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->getOr404($id); return $answer; {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 0a50021..15a5878 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Partial Update to a {{ entity }} entity. * @@ -31,7 +31,7 @@ {% endblock method_definition %} { {% block method_body %} - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); return $answer; {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 4b639ae..5a73ec3 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Create a {{ entity }} entity. * @@ -21,9 +21,8 @@ * * @return Response {% endblock phpdoc_method_header %} -* {% block phpdoc_method_annotations %} - {% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} */ {% block method_definition %} @@ -33,7 +32,7 @@ {% block method_body %} try { $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - $answer['{{ entity|lower }}'] = $new; + {{ resource ? "['" ~ entity|lower ~ "']" }} = $new; return $answer; } catch (InvalidFormException $exception) { diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 14134e5..38e5743 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -1,4 +1,4 @@ -/** + /** {% block phpdoc_method_header %} * Update a {{ entity }} entity. * @@ -34,10 +34,10 @@ {% block method_body %} try { if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + {{ resource ? "['" ~ entity|lower ~ "']" }}= $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); $code = Codes::HTTP_OK; } else { - $answer['{{ entity|lower }}'] = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); $code = Codes::HTTP_CREATED; } } catch (InvalidFormException $exception) { From 5cd1c9e4eecbdac0d726310e4cabdc1ba8468cad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 24 Nov 2014 16:20:19 -0400 Subject: [PATCH 13/46] Update the templates. --- .../Resources/skeleton/rest/actions/post.php.twig | 2 +- .../Resources/skeleton/rest/actions/put.php.twig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 5a73ec3..074d273 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -32,7 +32,7 @@ {% block method_body %} try { $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); - {{ resource ? "['" ~ entity|lower ~ "']" }} = $new; + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $new; return $answer; } catch (InvalidFormException $exception) { diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 38e5743..7019fe7 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -34,7 +34,7 @@ {% block method_body %} try { if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { - {{ resource ? "['" ~ entity|lower ~ "']" }}= $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }}= $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); $code = Codes::HTTP_OK; } else { $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); From 45fddae19c9be3ad7c27a924cefc361abc260bd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Fri, 28 Nov 2014 09:42:09 -0400 Subject: [PATCH 14/46] Allow getAll function on handler without parameters --- .../Resources/skeleton/rest/actions/post.php.twig | 2 +- .../Resources/skeleton/rest/handler/getAll.php.twig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 074d273..8cadcd4 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -24,7 +24,7 @@ {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} -*/ + */ {% block method_definition %} public function postAction(Request $request) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig index 74fa0b5..d8d5bc8 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -1,5 +1,5 @@ {% block method_definition %} - public function getAll($filters, $order_by, $limit, $offset) + public function getAll($filters = array(), $order_by = null, $limit = null, $offset = null) {% endblock method_definition %} { {% block method_body %} From e99058a314691c12b3d82692ecbc82b540839282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 1 Dec 2014 12:58:45 -0400 Subject: [PATCH 15/46] Permit show delete message. --- .../Resources/skeleton/rest/actions/delete.php.twig | 2 +- .../Resources/skeleton/rest/handler/delete.php.twig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 37c4dce..05f3f83 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -35,7 +35,7 @@ try { return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); } catch (\Exception $exception) { - return $exception; + throw new \RuntimeException("Exclusion not allowed"); } {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig index c5ead31..8824fc8 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -9,7 +9,7 @@ return null; } catch (\Exception $e) { - throw new \RuntimeException("Exclusion not allowed"); + throw new \RuntimeException(); } {% endblock method_body %} } From 4e55ef365bf4a107a671441236ba882009323968 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Mon, 22 Dec 2014 09:27:24 -0400 Subject: [PATCH 16/46] Fix PHPdocs messages --- .../Resources/skeleton/rest/actions/delete.php.twig | 3 +-- .../Resources/skeleton/rest/actions/getById.php.twig | 1 + .../Resources/skeleton/rest/actions/getOr404.php.twig | 9 ++++++++- .../Resources/skeleton/rest/actions/patch.php.twig | 2 +- .../Resources/skeleton/rest/actions/put.php.twig | 2 +- 5 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 05f3f83..b1ab62e 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -17,8 +17,7 @@ * @View(statusCode=204) * * @param Request $request - * @param $entity - * @internal param $id + * @param $id * * @return Response {% endblock phpdoc_method_header %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 45b14f8..f6f1b42 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -17,6 +17,7 @@ * @View(serializerEnableMaxDepthChecks=true) * * @return Response + * @param $id {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig index 35ded1b..ffbea13 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig @@ -1,4 +1,11 @@ - + /** +{% block phpdoc_method_header %} + * Get a entity or throw a exception + * + * @param $id + * @return $entity +{% endblock phpdoc_method_header %} + */ {% block method_definition %} protected function getOr404($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 15a5878..4a7c498 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -18,7 +18,7 @@ * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request - * @param $entity + * @param $id * * @return Response {% endblock phpdoc_method_header %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 7019fe7..eeb7447 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -19,7 +19,7 @@ * @View(serializerEnableMaxDepthChecks=true) * * @param Request $request - * @param $entity + * @param $id * * @return Response {% endblock phpdoc_method_header %} From 357cf75c8f410143b68b56d29179c8b6c462bf29 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Wed, 30 Mar 2016 16:07:47 +0200 Subject: [PATCH 17/46] update to composer for symfony 3 --- composer.json | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index fa2088b..c1605df 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "voryx/restgeneratorbundle", - "description": "REST API Generator for Symfony 2", + "description": "REST API Generator for Symfony", "type": "symfony-bundle", "license": "MIT", "authors": [ @@ -9,14 +9,17 @@ }, { "name": "David Dan" + }, + { + "name": "Maarten Sprakel" } ], "require": { "php": ">=5.3.0", - "sensio/generator-bundle": "~2.5", - "friendsofsymfony/rest-bundle": "~1.4", - "jms/serializer-bundle": "~1.0", - "nelmio/cors-bundle": "~1.3" + "sensio/generator-bundle": "~3.0", + "friendsofsymfony/rest-bundle": "~1.7", + "jms/serializer-bundle": "~1.1", + "nelmio/cors-bundle": "~1.4" }, "autoload": { "psr-0": { From 37fa6612f831e8f308c6779bcdb70749db4d4e3c Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Wed, 30 Mar 2016 16:59:12 +0200 Subject: [PATCH 18/46] added .idea in gitignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d938b52..d072ff3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ /vendor/ composer.lock /nbproject/private/ -nbproject/ \ No newline at end of file +nbproject/ + +.idea/ \ No newline at end of file From 189dac3d8908ace96e1bd5e8d0675b434ac5bb80 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Wed, 30 Mar 2016 23:26:21 +0200 Subject: [PATCH 19/46] create the DependencyInjection folder if it doesn't exist --- .../RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 65d501d..96cdf92 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -335,6 +335,10 @@ private function updateDIFile($fileName) $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; + if (!file_exists($this->bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection')) + { + mkdir($this->bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection'); + } $text = file_get_contents($fileName); if (strpos($text, "servicesREST.xml") == false) { From 7ab41e3faf36d55b739629b9c4f72012b7e886bf Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Wed, 30 Mar 2016 23:29:06 +0200 Subject: [PATCH 20/46] create everything including the BundleExtension.php --- .../RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 96cdf92..7dcc556 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -335,9 +335,9 @@ private function updateDIFile($fileName) $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; - if (!file_exists($this->bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection')) + if (!file_exists($fileName)) { - mkdir($this->bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection'); + mkdir($fileName, 0777, true); } $text = file_get_contents($fileName); From 12dfff625ad49dea45e6165f2f7e1dcdcdc692ec Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Thu, 31 Mar 2016 09:53:10 +0200 Subject: [PATCH 21/46] now fixed creation of the DependencyInjection the right way. also checking and creating the folder if it doesn't exist --- .../Generator/DoctrineRESTGenerator.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 7dcc556..0678757 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -332,14 +332,20 @@ public function declareService() private function updateDIFile($fileName) { + /** @var BundleInterface $bundle */ + $bundle = $this->bundle; $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; - if (!file_exists($fileName)) + $text = ''; + if (!file_exists($bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection')) + { + mkdir($bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection'); + } + if (file_exists($fileName)) { - mkdir($fileName, 0777, true); + $text = file_get_contents($fileName); } - $text = file_get_contents($fileName); if (strpos($text, "servicesREST.xml") == false) { $position = strpos($text, "}", strpos($text, "function load(")); From 9a8d0ecef55757943d1a88a502141b761dd716c8 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Thu, 31 Mar 2016 11:27:13 +0200 Subject: [PATCH 22/46] added extension bare class file when not yet created and added phpdoc to rest handler methods --- .../Generator/DoctrineRESTGenerator.php | 44 +++++++++++++++---- .../skeleton/rest/extension.php.twig | 31 +++++++++++++ .../Resources/skeleton/rest/handler.php.twig | 6 +++ .../skeleton/rest/handler/construct.php.twig | 8 ++++ .../skeleton/rest/handler/delete.php.twig | 7 +++ .../skeleton/rest/handler/extras.php.twig | 16 ++++++- .../skeleton/rest/handler/get.php.twig | 6 +++ .../skeleton/rest/handler/getAll.php.twig | 9 ++++ .../skeleton/rest/handler/patch.php.twig | 8 ++++ .../skeleton/rest/handler/post.php.twig | 7 +++ .../skeleton/rest/handler/put.php.twig | 8 ++++ 11 files changed, 141 insertions(+), 9 deletions(-) create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 0678757..682e7d4 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -78,7 +78,7 @@ public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $meta $this->setFormat('yml'); $this->generateControllerClass($forceOverwrite, $document, $resource); - $this->generateHandler($forceOverwrite); + $this->generateHandler($forceOverwrite, $document); $this->generateExceptionClass(); $this->declareService(); } @@ -186,8 +186,9 @@ protected function generateControllerClass($forceOverwrite, $document, $resource /** * Generates the Handle only. * @param bool $forceOverwrite + * @param bool $document */ - protected function generateHandler($forceOverwrite) + protected function generateHandler($forceOverwrite, $document) { /** @var BundleInterface $bundle */ $bundle = $this->bundle; @@ -225,10 +226,14 @@ protected function generateHandler($forceOverwrite) 'namespace' => $bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, + 'document' => $document ) ); } + /** + * + */ public function generateExceptionClass() { /** @var BundleInterface $bundle */ @@ -330,22 +335,24 @@ public function declareService() $this->updateDIFile($fileName); } + /** + * @param $fileName + */ private function updateDIFile($fileName) { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; $text = ''; - if (!file_exists($bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection')) + if (!file_exists(dirname($fileName))) { - mkdir($bundle->getPath().DIRECTORY_SEPARATOR.'DependencyInjection'); + mkdir(dirname($fileName), 0777, true); } - if (file_exists($fileName)) + if (!file_exists($fileName)) { - $text = file_get_contents($fileName); + $this->handleExtensionFileCreation($fileName); } + $text = file_get_contents($fileName); if (strpos($text, "servicesREST.xml") == false) { $position = strpos($text, "}", strpos($text, "function load(")); @@ -355,6 +362,27 @@ private function updateDIFile($fileName) } } + /** + * @param $fileName + */ + private function handleExtensionFileCreation($fileName) + { + /** @var BundleInterface $bundle */ + $bundle = $this->bundle; + + $parts = explode('\\', $this->entity); + $entityNamespace = implode('\\', $parts); + + $this->renderFile( + 'rest/extension.php.twig', + $fileName, + array( + 'file_name' => $fileName, + 'namespace' => $bundle->getNamespace(), + 'entity_namespace' => $entityNamespace, + ) + ); + } /** * Generates the functional test class only. diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig new file mode 100644 index 0000000..eec11b3 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig @@ -0,0 +1,31 @@ +processConfiguration($configuration, $configs); + } +{% endblock class_body %} +} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig index 0eaeace..5e23ced 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig @@ -11,6 +11,12 @@ use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Form\FormFactoryInterface; {% endblock use_statements %} +{% if document %} + /** + * Class {{ entity_class }}RESTHandler + * @package AppBundle\Handler + */ +{% endif %} {% block class_definition %} class {{ entity_class }}RESTHandler {% endblock class_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig index ca4ef08..aec2456 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig @@ -1,3 +1,11 @@ +{% if document %} + /** + * {{ entity }}RESTHandler constructor. + * @param ObjectManager $om + * @param $entityClass + * @param FormFactoryInterface $formFactory + */ +{% endif %} {% block method_definition %} public function __construct(ObjectManager $om, $entityClass, FormFactoryInterface $formFactory) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig index 8824fc8..bf48fff 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -1,3 +1,10 @@ +{% if document %} + /** + * @param {{ entity }} ${{ entity|lower }} + * @return null + * @throws \RuntimeException + */ +{% endif %} {% block method_definition %} public function delete({{ entity }} ${{ entity|lower }}) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig index 903caf5..92450d5 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -1,4 +1,13 @@ {% block extras_methods %} + {% if document %} + /** + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @param string $method + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ + {% endif %} private function processForm({{ entity }} ${{ entity|lower }}, array $parameters, $method = "PUT") { $form = $this->formFactory->create(new {{ entity }}Type(), ${{ entity|lower }}, array('method' => $method)); @@ -6,13 +15,18 @@ if ($form->isValid()) { ${{ entity|lower }} = $form->getData(); $this->om->persist(${{ entity|lower }}); - $this->om->flush(${{ entity|lower }}); + $this->om->flush(); return ${{ entity|lower }}; } throw new InvalidFormException('Invalid submitted data', $form); } + {% if document %} + /** + * @return {{ entity }} ${{ entity|lower }} + */ + {% endif %} private function create{{ entity }}() { return new $this->entityClass(); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig index 202e2e7..ce529f6 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig @@ -1,3 +1,9 @@ +{% if document %} + /** + * @param int $id + * @return {{ entity }} ${{ entity|lower }} + */ +{% endif %} {% block method_definition %} public function get($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig index d8d5bc8..bd0b557 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -1,3 +1,12 @@ +{% if document %} + /** + * @param array $filters + * @param string|null $order_by The field to order by + * @param int|null $limit The limit + * @param int|null $offset The offset from the first record + * @return {{ entity }}[] ${{ entity|lower }}s + */ +{% endif %} {% block method_definition %} public function getAll($filters = array(), $order_by = null, $limit = null, $offset = null) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig index fbe9b54..8efc558 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig @@ -1,3 +1,11 @@ +{% if document %} + /** + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ +{% endif %} {% block method_definition %} public function patch({{ entity }} ${{ entity|lower }}, array $parameters) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig index 7cfa712..a703b62 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig @@ -1,3 +1,10 @@ +{% if document %} + /** + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ +{% endif %} {% block method_definition %} public function post($parameters) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig index 5c44191..d55b4f0 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig @@ -1,3 +1,11 @@ +{% if document %} + /** + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ +{% endif %} {% block method_definition %} public function put({{ entity }} ${{ entity|lower }}, array $parameters) {% endblock method_definition %} From 591d749dd27fd372129e863e8f6418ea1d6a96db Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Thu, 31 Mar 2016 16:02:46 +0200 Subject: [PATCH 23/46] added type-fixing and fixed the extension generation --- .../Generator/DoctrineRESTGenerator.php | 68 +++++++------------ .../skeleton/rest/extension.php.twig | 7 +- 2 files changed, 29 insertions(+), 46 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 682e7d4..42fdc0a 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -24,11 +24,16 @@ */ class DoctrineRESTGenerator extends Generator { + /** @var Filesystem */ protected $filesystem; protected $routePrefix; protected $routeNamePrefix; + + /** @var BundleInterface */ protected $bundle; protected $entity; + + /** @var ClassMetadataInfo */ protected $metadata; protected $format; protected $actions; @@ -113,12 +118,9 @@ protected function generateConfiguration() return; } - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - $target = sprintf( '%s/Resources/config/routing/%s.%s', - $bundle->getPath(), + $this->bundle->getPath(), strtolower(str_replace('\\', '_', $this->entity)), $this->format ); @@ -130,7 +132,7 @@ protected function generateConfiguration() 'actions' => $this->actions, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, - 'bundle' => $bundle->getName(), + 'bundle' => $this->bundle->getName(), 'entity' => $this->entity, ) ); @@ -144,10 +146,7 @@ protected function generateConfiguration() */ protected function generateControllerClass($forceOverwrite, $document, $resource) { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - - $dir = $bundle->getPath(); + $dir = $this->bundle->getPath(); $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); @@ -171,10 +170,10 @@ protected function generateControllerClass($forceOverwrite, $document, $resource 'actions' => $this->actions, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, - 'bundle' => $bundle->getName(), + 'bundle' => $this->bundle->getName(), 'entity' => $this->entity, 'entity_class' => $entityClass, - 'namespace' => $bundle->getNamespace(), + 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, 'resource' => $resource, @@ -190,10 +189,7 @@ protected function generateControllerClass($forceOverwrite, $document, $resource */ protected function generateHandler($forceOverwrite, $document) { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - - $dir = $bundle->getPath(); + $dir = $this->bundle->getPath(); $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); @@ -220,10 +216,10 @@ protected function generateHandler($forceOverwrite, $document) array( 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, - 'bundle' => $bundle->getName(), + 'bundle' => $this->bundle->getName(), 'entity' => $this->entity, 'entity_class' => $entityClass, - 'namespace' => $bundle->getNamespace(), + 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, 'document' => $document @@ -236,10 +232,7 @@ protected function generateHandler($forceOverwrite, $document) */ public function generateExceptionClass() { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - - $dir = $bundle->getPath(); + $dir = $this->bundle->getPath(); $target = sprintf('%s/Exception/InvalidFormException.php', $dir); @@ -250,7 +243,7 @@ public function generateExceptionClass() $this->renderFile( 'rest/form_exception.php.twig', $target, - array('namespace' => $bundle->getNamespace()) + array('namespace' => $this->bundle->getNamespace()) ); } @@ -259,17 +252,14 @@ public function generateExceptionClass() */ public function declareService() { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - - $dir = $bundle->getPath(); + $dir = $this->bundle->getPath(); $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); - $namespace = $bundle->getNamespace(); + $namespace = $this->bundle->getNamespace(); - $bundleName = strtolower($bundle->getName()); + $bundleName = strtolower($this->bundle->getName()); $entityName = strtolower($this->entity); $services = sprintf( @@ -293,7 +283,7 @@ public function declareService() $fileName = sprintf( "%s/DependencyInjection/%s.php", $dir, - str_replace("Bundle", "Extension", $bundle->getName()) + str_replace("Bundle", "Extension", $this->bundle->getName()) ); if (!is_file($services)) { @@ -367,18 +357,15 @@ private function updateDIFile($fileName) */ private function handleExtensionFileCreation($fileName) { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - $parts = explode('\\', $this->entity); $entityNamespace = implode('\\', $parts); $this->renderFile( - 'rest/extension.php.twig', + 'rest//extension.php.twig', $fileName, array( - 'file_name' => $fileName, - 'namespace' => $bundle->getNamespace(), + 'class_name' => str_replace("Bundle", "Extension", $this->bundle->getName()), + 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, ) ); @@ -390,10 +377,7 @@ private function handleExtensionFileCreation($fileName) */ protected function generateTestClass() { - /** @var BundleInterface $bundle */ - $bundle = $this->bundle; - - $dir = $bundle->getPath() . '/Tests/Controller'; + $dir = $this->bundle->getPath() . '/Tests/Controller'; $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); @@ -408,12 +392,12 @@ protected function generateTestClass() 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'entity' => $this->entity, - 'bundle' => $bundle->getName(), + 'bundle' => $this->bundle->getName(), 'entity_class' => $entityClass, - 'namespace' => $bundle->getNamespace(), + 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'actions' => $this->actions, - 'form_type_name' => strtolower(str_replace('\\', '_', $bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . $entityClass . 'Type'), + 'form_type_name' => strtolower(str_replace('\\', '_', $this->bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . $entityClass . 'Type'), ) ); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig index eec11b3..c14a8ed 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig @@ -1,6 +1,6 @@ processConfiguration($configuration, $configs); + } {% endblock class_body %} } From 83b24afb7b6ed95e866ad35681c2f99a4d7465af Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Thu, 31 Mar 2016 17:13:22 +0200 Subject: [PATCH 24/46] fixed formattting issues --- .../skeleton/rest/actions/delete.php.twig | 36 +++++++-------- .../skeleton/rest/actions/getAll.php.twig | 45 ++++++++++--------- .../skeleton/rest/actions/getById.php.twig | 31 ++++++------- .../skeleton/rest/actions/getOr404.php.twig | 12 ++--- .../skeleton/rest/actions/patch.php.twig | 39 ++++++++-------- .../skeleton/rest/actions/post.php.twig | 37 +++++++-------- .../skeleton/rest/actions/put.php.twig | 41 ++++++++--------- .../skeleton/rest/extension.php.twig | 1 - .../Resources/skeleton/rest/handler.php.twig | 8 ++-- .../skeleton/rest/handler/delete.php.twig | 8 ++-- .../skeleton/rest/handler/extras.php.twig | 24 +++++----- .../skeleton/rest/handler/getAll.php.twig | 12 ++--- .../skeleton/rest/handler/patch.php.twig | 10 ++--- .../skeleton/rest/handler/post.php.twig | 8 ++-- .../skeleton/rest/handler/put.php.twig | 10 ++--- 15 files changed, 163 insertions(+), 159 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index b1ab62e..158ae04 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -1,30 +1,29 @@ - /** + /** {% block phpdoc_method_header %} - * Delete a {{ entity }} entity. - * + * Delete a {{ entity }} entity. + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Delete a {{ entity }} entity.", - * statusCodes = { - * 204 = "No content. Successfully excluded.", - * 404 = "Not found." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Delete a {{ entity }} entity.", + * statusCodes = { + * 204 = "No content. Successfully excluded.", + * 404 = "Not found." + * } + * ) {% endif %} {% endblock documentation %} - * @View(statusCode=204) - * - * @param Request $request - * @param $id - * - * @return Response + * @View(statusCode=204) + * + * @param $id + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} -*/ + */ {% block method_definition %} public function deleteAction($id) {% endblock method_definition %} @@ -40,3 +39,4 @@ {% block method_return '' %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 50e3245..34aa6b9 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -1,34 +1,34 @@ - /** + /** {% block phpdoc_method_header %} - * Get all {{ entity }} entities. - * + * Get all {{ entity }} entities. + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Get all {{ entity }} entities.", - * statusCodes = { - * 200 = "List of {{ entity }}", - * 204 = "No content. Nothing to list." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Get all {{ entity }} entities.", + * statusCodes = { + * 200 = "List of {{ entity }}", + * 204 = "No content. Nothing to list." + * } + * ) {% endif %} {% endblock documentation %} - * @View(serializerEnableMaxDepthChecks=true) - * - * @param ParamFetcherInterface $paramFetcher - * - * @return Response - * - * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.") - * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.") - * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC") - * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") + * @View(serializerEnableMaxDepthChecks=true) + * + * @param ParamFetcherInterface $paramFetcher + * + * @return Response + * + * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.") + * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.") + * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC") + * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} -*/ + */ {% block method_definition %} public function cgetAction(ParamFetcherInterface $paramFetcher) {% endblock method_definition %} @@ -48,3 +48,4 @@ {% block method_return '' %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index f6f1b42..28d3477 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -1,23 +1,23 @@ - /** + /** {% block phpdoc_method_header %} - * Get a {{ entity }} entity - * + * Get a {{ entity }} entity + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Get a {{ entity }} entity.", - * statusCodes = { - * 200 = "{{ entity }}'s object.", - * 404 = "Not Found." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Get a {{ entity }} entity.", + * statusCodes = { + * 200 = "{{ entity }}'s object.", + * 404 = "Not Found." + * } + * ) {% endif %} {% endblock documentation %} - * @View(serializerEnableMaxDepthChecks=true) - * - * @return Response - * @param $id + * @View(serializerEnableMaxDepthChecks=true) + * + * @return Response + * @param $id {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %} @@ -35,3 +35,4 @@ {% block method_return '' %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig index ffbea13..93d5d78 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig @@ -1,11 +1,11 @@ - /** + /** {% block phpdoc_method_header %} - * Get a entity or throw a exception - * - * @param $id - * @return $entity + * Get a entity or throw a exception + * + * @param $id + * @return {{ entity }} $entity {% endblock phpdoc_method_header %} - */ + */ {% block method_definition %} protected function getOr404($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 34022a7..341aa51 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -1,31 +1,31 @@ - /** + /** {% block phpdoc_method_header %} - * Partial Update to a {{ entity }} entity. - * + * Partial Update to a {{ entity }} entity. + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Partial Update to a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Partial Update to a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) {% endif %} {% endblock documentation %} - * @View(serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * @param $id - * - * @return Response + * @View(serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * @param $id + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function patchAction(Request $request, $id) {% endblock method_definition %} @@ -37,3 +37,4 @@ {% block method_return '' %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 8cadcd4..df7bb51 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -1,30 +1,30 @@ - /** + /** {% block phpdoc_method_header %} - * Create a {{ entity }} entity. - * + * Create a {{ entity }} entity. + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Create a {{ entity }} entity.", - * statusCodes = { - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Create a {{ entity }} entity.", + * statusCodes = { + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) {% endif %} {% endblock documentation %} - * @View(statusCode=201, serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * - * @return Response + * @View(statusCode=201, serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function postAction(Request $request) {% endblock method_definition %} @@ -41,3 +41,4 @@ {% endblock method_body %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index eeb7447..89aa3a9 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -1,32 +1,32 @@ - /** + /** {% block phpdoc_method_header %} - * Update a {{ entity }} entity. - * + * Update a {{ entity }} entity. + * {% block documentation %} {% if document %} - * @ApiDoc( - * resource = true, - * description = "Update a {{ entity }} entity.", - * statusCodes = { - * 200 = "Updated object.", - * 201 = "Created object.", - * 400 = "Bad Request. Verify your params.", - * 404 = "Not Found." - * } - * ) + * @ApiDoc( + * resource = true, + * description = "Update a {{ entity }} entity.", + * statusCodes = { + * 200 = "Updated object.", + * 201 = "Created object.", + * 400 = "Bad Request. Verify your params.", + * 404 = "Not Found." + * } + * ) {% endif %} {% endblock documentation %} - * @View(serializerEnableMaxDepthChecks=true) - * - * @param Request $request - * @param $id - * - * @return Response + * @View(serializerEnableMaxDepthChecks=true) + * + * @param Request $request + * @param $id + * + * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} -*/ + */ {% block method_definition %} public function putAction(Request $request, $id) {% endblock method_definition %} @@ -50,3 +50,4 @@ {% block method_return '' %} } {% block form '' %} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig index c14a8ed..0748229 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/extension.php.twig @@ -24,7 +24,6 @@ class {{ class_name }} extends Extension */ public function load(array $configs, ContainerBuilder $container) { - } {% endblock class_body %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig index 5e23ced..bdeeef3 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler.php.twig @@ -12,10 +12,10 @@ use Symfony\Component\Form\FormFactoryInterface; {% endblock use_statements %} {% if document %} - /** - * Class {{ entity_class }}RESTHandler - * @package AppBundle\Handler - */ +/** + * Class {{ entity_class }}RESTHandler + * @package AppBundle\Handler + */ {% endif %} {% block class_definition %} class {{ entity_class }}RESTHandler diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig index bf48fff..842b383 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -1,9 +1,9 @@ {% if document %} /** - * @param {{ entity }} ${{ entity|lower }} - * @return null - * @throws \RuntimeException - */ + * @param {{ entity }} ${{ entity|lower }} + * @return null + * @throws \RuntimeException + */ {% endif %} {% block method_definition %} public function delete({{ entity }} ${{ entity|lower }}) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig index 92450d5..ed715e6 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -1,13 +1,13 @@ {% block extras_methods %} - {% if document %} +{% if document %} /** - * @param {{ entity }} ${{ entity|lower }} - * @param array $parameters - * @param string $method - * @return {{ entity }} ${{ entity|lower }} - * @throws InvalidFormException - */ - {% endif %} + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @param string $method + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ +{% endif %} private function processForm({{ entity }} ${{ entity|lower }}, array $parameters, $method = "PUT") { $form = $this->formFactory->create(new {{ entity }}Type(), ${{ entity|lower }}, array('method' => $method)); @@ -22,11 +22,11 @@ throw new InvalidFormException('Invalid submitted data', $form); } - {% if document %} +{% if document %} /** - * @return {{ entity }} ${{ entity|lower }} - */ - {% endif %} + * @return {{ entity }} ${{ entity|lower }} + */ +{% endif %} private function create{{ entity }}() { return new $this->entityClass(); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig index bd0b557..32ec368 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -1,11 +1,11 @@ {% if document %} /** - * @param array $filters - * @param string|null $order_by The field to order by - * @param int|null $limit The limit - * @param int|null $offset The offset from the first record - * @return {{ entity }}[] ${{ entity|lower }}s - */ + * @param array $filters + * @param string|null $order_by The field to order by + * @param int|null $limit The limit + * @param int|null $offset The offset from the first record + * @return {{ entity }}[] ${{ entity|lower }}s + */ {% endif %} {% block method_definition %} public function getAll($filters = array(), $order_by = null, $limit = null, $offset = null) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig index 8efc558..294b18d 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig @@ -1,10 +1,10 @@ {% if document %} /** - * @param {{ entity }} ${{ entity|lower }} - * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} - * @throws InvalidFormException - */ + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ {% endif %} {% block method_definition %} public function patch({{ entity }} ${{ entity|lower }}, array $parameters) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig index a703b62..c0a94cc 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig @@ -1,9 +1,9 @@ {% if document %} /** - * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} - * @throws InvalidFormException - */ + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ {% endif %} {% block method_definition %} public function post($parameters) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig index d55b4f0..a00f39d 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig @@ -1,10 +1,10 @@ {% if document %} /** - * @param {{ entity }} ${{ entity|lower }} - * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} - * @throws InvalidFormException - */ + * @param {{ entity }} ${{ entity|lower }} + * @param array $parameters + * @return {{ entity }} ${{ entity|lower }} + * @throws InvalidFormException + */ {% endif %} {% block method_definition %} public function put({{ entity }} ${{ entity|lower }}, array $parameters) From dff4ea3186dcee243c229cd1592f88ba2df6ff11 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 09:46:16 +0200 Subject: [PATCH 25/46] more formatting fixes in docs and added ApiDoc input/output by default --- .../RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php | 2 +- .../Resources/skeleton/rest/actions/delete.php.twig | 2 +- .../Resources/skeleton/rest/actions/getAll.php.twig | 2 +- .../Resources/skeleton/rest/actions/patch.php.twig | 6 ++++-- .../Resources/skeleton/rest/actions/post.php.twig | 4 +++- .../Resources/skeleton/rest/actions/put.php.twig | 6 ++++-- 6 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 42fdc0a..c886000 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -167,7 +167,7 @@ protected function generateControllerClass($forceOverwrite, $document, $resource 'rest/controller.php.twig', $target, array( - 'actions' => $this->actions, + 'actions' => $this->actions, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'bundle' => $this->bundle->getName(), diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 158ae04..9fb9f64 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -23,7 +23,7 @@ {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function deleteAction($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 34aa6b9..2b64d1e 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -28,7 +28,7 @@ {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function cgetAction(ParamFetcherInterface $paramFetcher) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 341aa51..6ffa171 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -11,7 +11,9 @@ * 200 = "Updated object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * } + * }, + * input = "{{ namespace }}\Form\{{ entity }}Type", + * output = "{{ namespace }}\Entity\{{ entity }}" * ) {% endif %} {% endblock documentation %} @@ -25,7 +27,7 @@ {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function patchAction(Request $request, $id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index df7bb51..8acfcc0 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -11,7 +11,9 @@ * 201 = "Created object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * } + * }, + * input = "{{ namespace }}\Form\{{ entity }}Type", + * output = "{{ namespace }}\Entity\{{ entity }}" * ) {% endif %} {% endblock documentation %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 89aa3a9..5d9472b 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -12,7 +12,9 @@ * 201 = "Created object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * } + * }, + * input = "{{ namespace }}\Form\{{ entity }}Type", + * output = "{{ namespace }}\Entity\{{ entity }}" * ) {% endif %} {% endblock documentation %} @@ -26,7 +28,7 @@ {% block phpdoc_method_annotations %} {% if 'annotation' == format %}{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function putAction(Request $request, $id) {% endblock method_definition %} From 938e2682005eb85871623e4a0088cac2bcb6ba19 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 11:57:33 +0200 Subject: [PATCH 26/46] fix for re-generate form using the --overwrite option --- .../Command/GenerateDoctrineRESTCommand.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 3b46d44..0d49ea8 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -94,6 +94,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $format = "rest"; $prefix = $this->getRoutePrefix($input, $entity); + /** @var bool $forceOverwrite */ $forceOverwrite = $input->getOption('overwrite'); $questionHelper->writeSection($output, 'REST api generation'); @@ -114,7 +115,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $runner = $questionHelper->getRunner($output, $errors); // form - $this->generateForm($bundle, $entity, $metadata); + $this->generateForm($bundle, $entity, $metadata, $forceOverwrite); $output->writeln('Generating the Form code: OK'); // create route From e0e36e38d70f181878be9c352338c14b3aec54a7 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 12:48:01 +0200 Subject: [PATCH 27/46] added basic support for annotation routing format --- .../Command/GenerateDoctrineRESTCommand.php | 11 ++++++++--- .../Generator/DoctrineRESTGenerator.php | 5 +++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 0d49ea8..16415dd 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -40,6 +40,7 @@ protected function configure() array( new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), + new InputOption('format', '', InputOption::VALUE_OPTIONAL, 'The format used for generation of routing (yml or annotation)', 'yml'), new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), new InputOption('resource', '', InputOption::VALUE_NONE, 'The object will return with the resource name'), new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller'), @@ -92,7 +93,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $entity = Validators::validateEntityName($input->getOption('entity')); list($bundle, $entity) = $this->parseShortcutNotation($entity); - $format = "rest"; + $format = $input->getOption('format'); $prefix = $this->getRoutePrefix($input, $entity); /** @var bool $forceOverwrite */ $forceOverwrite = $input->getOption('overwrite'); @@ -107,7 +108,7 @@ protected function execute(InputInterface $input, OutputInterface $output) /** @var DoctrineRESTGenerator $generator */ $generator = $this->getGenerator($bundle); - $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document); + $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document, $format); $output->writeln('Generating the REST api code: OK'); @@ -119,7 +120,10 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln('Generating the Form code: OK'); // create route - $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix)); + if ($format !== 'annotation') + { + $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix)); + } $questionHelper->writeGeneratorSummary($output, $errors); } @@ -187,6 +191,7 @@ protected function interact(InputInterface $input, OutputInterface $output) * @param InputInterface $input * @param OutputInterface $output * @param BundleInterface $bundle + * @param $format * @param $entity * @param $prefix * @return array diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index c886000..d676bad 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -58,8 +58,9 @@ public function __construct(Filesystem $filesystem) * @param bool $forceOverwrite Whether or not to overwrite an existing controller * @param bool $resource * @param bool $document + * @param string $format */ - public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata,$routePrefix,$forceOverwrite,$resource,$document) + public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata,$routePrefix,$forceOverwrite,$resource,$document,$format) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = str_replace('/', '_', $routePrefix); @@ -80,7 +81,7 @@ public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $meta $this->entity = $entity; $this->bundle = $bundle; $this->metadata = $metadata; - $this->setFormat('yml'); + $this->setFormat($format); $this->generateControllerClass($forceOverwrite, $document, $resource); $this->generateHandler($forceOverwrite, $document); From 09d9215a0412ec0fa0c39204afd0498f88b59085 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 13:03:58 +0200 Subject: [PATCH 28/46] added entity name after route prefix in route annotation above controller --- .../Resources/skeleton/rest/controller.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig index 624a63c..e823942 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -38,7 +38,7 @@ use Nelmio\ApiDocBundle\Annotation\ApiDoc; * @RouteResource("{{ entity }}") {% block phpdoc_class_annotations %} {% if 'annotation' == format %} - * @Route("/{{ route_prefix }}") + * @Route("/{{ route_prefix }}/{{ entity|lower }}") {% endif %} {% endblock phpdoc_class_annotations %} */ From c5483879ca4e92359ad1e27543aed7433448c47f Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 14:39:06 +0200 Subject: [PATCH 29/46] added function route annotations for the REST controller methods and now allways generating phpdoc for handlers instead of only when run with --document --- .../Resources/skeleton/rest/actions/delete.php.twig | 8 ++++++-- .../Resources/skeleton/rest/actions/getAll.php.twig | 8 ++++++-- .../Resources/skeleton/rest/actions/getById.php.twig | 9 ++++++--- .../Resources/skeleton/rest/actions/patch.php.twig | 8 ++++++-- .../Resources/skeleton/rest/actions/post.php.twig | 6 +++++- .../Resources/skeleton/rest/actions/put.php.twig | 8 ++++++-- .../Resources/skeleton/rest/controller.php.twig | 5 +++++ .../Resources/skeleton/rest/handler/construct.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/delete.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/extras.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/get.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/getAll.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/patch.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/post.php.twig | 4 ++-- .../Resources/skeleton/rest/handler/put.php.twig | 4 ++-- 15 files changed, 56 insertions(+), 28 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index 9fb9f64..f968602 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -21,9 +21,13 @@ * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} - {% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %} + * + * @RESTDelete("/{id}.{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function deleteAction($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 2b64d1e..b29509f 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -26,9 +26,13 @@ * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} - {% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %} + * + * @RESTGet(".{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function cgetAction(ParamFetcherInterface $paramFetcher) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 28d3477..40b5ffa 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -20,10 +20,13 @@ * @param $id {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} - {% if 'annotation' == format %} - {% endif %} +{% if 'annotation' == format %} + * + * @RESTGet("/{id}.{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} -*/ + */ {% block method_definition %} public function getAction($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 6ffa171..c96ae58 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -25,9 +25,13 @@ * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} - {% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %} + * + * @RESTPatch("/{id}.{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function patchAction(Request $request, $id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 8acfcc0..0fb8ff4 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -24,7 +24,11 @@ * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} -{% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %} + * + * @RESTPost(".{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} */ {% block method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index 5d9472b..ddd77ee 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -26,9 +26,13 @@ * @return Response {% endblock phpdoc_method_header %} {% block phpdoc_method_annotations %} - {% if 'annotation' == format %}{% endif %} +{% if 'annotation' == format %} + * + * @RESTPut("/{id}.{_format}") + * +{% endif %} {% endblock phpdoc_method_annotations %} - */ + */ {% block method_definition %} public function putAction(Request $request, $id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig index e823942..3b7b258 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -18,6 +18,11 @@ use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; +use FOS\RestBundle\Controller\Annotations\Get as RESTGet; +use FOS\RestBundle\Controller\Annotations\Put as RESTPut; +use FOS\RestBundle\Controller\Annotations\Patch as RESTPatch; +use FOS\RestBundle\Controller\Annotations\Post as RESTPost; +use FOS\RestBundle\Controller\Annotations\Delete as RESTDelete; {%- endif %} use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Form; diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig index aec2456..b926fa7 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig @@ -1,11 +1,11 @@ -{% if document %} /** +{% block phpdoc_method_header %} * {{ entity }}RESTHandler constructor. * @param ObjectManager $om * @param $entityClass * @param FormFactoryInterface $formFactory +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function __construct(ObjectManager $om, $entityClass, FormFactoryInterface $formFactory) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig index 842b383..bcaf138 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -1,10 +1,10 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param {{ entity }} ${{ entity|lower }} * @return null * @throws \RuntimeException +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function delete({{ entity }} ${{ entity|lower }}) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig index ed715e6..cf91019 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -1,13 +1,13 @@ {% block extras_methods %} -{% if document %} /** +{% block phpdoc_method_header %} * @param {{ entity }} ${{ entity|lower }} * @param array $parameters * @param string $method * @return {{ entity }} ${{ entity|lower }} * @throws InvalidFormException +{% endblock phpdoc_method_header %} */ -{% endif %} private function processForm({{ entity }} ${{ entity|lower }}, array $parameters, $method = "PUT") { $form = $this->formFactory->create(new {{ entity }}Type(), ${{ entity|lower }}, array('method' => $method)); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig index ce529f6..877deeb 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig @@ -1,9 +1,9 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param int $id * @return {{ entity }} ${{ entity|lower }} + {% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function get($id) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig index 32ec368..65044e2 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -1,12 +1,12 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param array $filters * @param string|null $order_by The field to order by * @param int|null $limit The limit * @param int|null $offset The offset from the first record * @return {{ entity }}[] ${{ entity|lower }}s +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function getAll($filters = array(), $order_by = null, $limit = null, $offset = null) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig index 294b18d..ec26360 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig @@ -1,11 +1,11 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param {{ entity }} ${{ entity|lower }} * @param array $parameters * @return {{ entity }} ${{ entity|lower }} * @throws InvalidFormException +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function patch({{ entity }} ${{ entity|lower }}, array $parameters) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig index c0a94cc..9a39457 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig @@ -1,10 +1,10 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param array $parameters * @return {{ entity }} ${{ entity|lower }} * @throws InvalidFormException +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function post($parameters) {% endblock method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig index a00f39d..e241a09 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig @@ -1,11 +1,11 @@ -{% if document %} /** +{% block phpdoc_method_header %} * @param {{ entity }} ${{ entity|lower }} * @param array $parameters * @return {{ entity }} ${{ entity|lower }} * @throws InvalidFormException +{% endblock phpdoc_method_header %} */ -{% endif %} {% block method_definition %} public function put({{ entity }} ${{ entity|lower }}, array $parameters) {% endblock method_definition %} From 34a19ff919a5f578a9b8855b6bb9dca60c201785 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 15:13:33 +0200 Subject: [PATCH 30/46] added Symfony3 readme, bin/console instead of app/console --- README.Symfony3.md | 160 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 README.Symfony3.md diff --git a/README.Symfony3.md b/README.Symfony3.md new file mode 100644 index 0000000..d405b90 --- /dev/null +++ b/README.Symfony3.md @@ -0,0 +1,160 @@ +# Voryx REST Generator Bundle +[![SensioLabsInsight](https://insight.sensiolabs.com/projects/ac1842d9-4e36-45cc-8db1-b97e2e62540e/big.png)](https://insight.sensiolabs.com/projects/ac1842d9-4e36-45cc-8db1-b97e2e62540e) + +## About + +A CRUD like REST Generator + +## Features + +* Generators RESTful action from entity +* Simplifies setting up a RESTful Controller + + +## Installation +Require the "voryx/restgeneratorbundle" package in your composer.json and update your dependencies. + +```bash +$ php composer.phar require voryx/restgeneratorbundle dev-master +``` + +Add the VoryxRestGeneratorBundle to your application's kernel along with other dependencies: + +```php +public function registerBundles() +{ + $bundles = array( + //... + new Voryx\RESTGeneratorBundle\VoryxRESTGeneratorBundle(), + new FOS\RestBundle\FOSRestBundle(), + new JMS\SerializerBundle\JMSSerializerBundle($this), + new Nelmio\CorsBundle\NelmioCorsBundle(), + new Nelmio\ApiDocBundle\NelmioApiDocBundle(), + //... + ); + //... +} +``` + +## Configuration + +This bundle depends on a number of other Symfony bundles, so they need to be configured in order for the generator to work properly + +```yaml +framework: + csrf_protection: false #only use for public API + +fos_rest: + routing_loader: + default_format: json + param_fetcher_listener: true + body_listener: true + #disable_csrf_role: ROLE_USER + body_converter: + enabled: true + view: + view_response_listener: force + +nelmio_cors: + defaults: + allow_credentials: false + allow_origin: [] + allow_headers: [] + allow_methods: [] + expose_headers: [] + max_age: 0 + paths: + '^/api/': + allow_origin: ['*'] + allow_headers: ['*'] + allow_methods: ['POST', 'PUT', 'GET', 'DELETE'] + max_age: 3600 + +sensio_framework_extra: + request: { converters: true } + view: { annotations: false } + router: { annotations: true } + +nelmio_api_doc: ~ +``` + +## Generating the Controller + + +Generate the REST controller + +```bash +$ php bin/console voryx:generate:rest +``` + +This will guide you through the generator which will generate a RESTful controller for an entity. + + +## Example + +Create a new entity called 'Post': + +```bash +$ php bin/console doctrine:generate:entity --entity=AppBundle:Post --format=annotation --fields="name:string(255) description:string(255)" --no-interaction +``` + +Update the database schema: + +```bash +$ php bin/console doctrine:schema:update --force +``` + +Generate the API controller: + +```bash +$ php bin/console voryx:generate:rest --entity="AppBundle:Post" +``` + +### Using the API +If you selected the default options you'll be able to start using the API like this: + +Creating a new post (`POST`) + +```bash +$ curl -i -H "Content-Type: application/json" -X POST -d '{"name" : "Test Post", "description" : "This is a test post"}' http://localhost/app_dev.php/api/posts +``` + +Updating (`PUT`) + +```bash +$ curl -i -H "Content-Type: application/json" -X PUT -d '{"name" : "Test Post 1", "description" : "This is an updated test post"}' http://localhost/app_dev.php/api/posts/1 +``` + +Get all posts (`GET`) + +```bash +$ curl http://localhost/app_dev.php/api/posts +``` + +Get one post (`GET`) + +```bash +$ curl http://localhost/app_dev.php/api/posts/1 +``` + + +Delete (`DELETE`) + +```bash +$ curl -X DELETE http://localhost/app_dev.php/api/posts/1 +``` + + +## Related Entities + +If you want the form to be able to convert related entities into the correct entity id on POST, PUT or PATCH, use the voryx_entity form type + +```php +#Form/PostType() + + ->add( + 'user', 'voryx_entity', array( + 'class' => 'Acme\Bundle\Entity\User' + ) + ) +``` From 06b221d3fbfc3b071875b6e7a28dd296be23cd48 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 15:34:51 +0200 Subject: [PATCH 31/46] testing of nicely saving the servicesREST.xml file --- .../Generator/DoctrineRESTGenerator.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index d676bad..d698c4b 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -291,6 +291,7 @@ public function declareService() $this->renderFile("rest/service/services.xml.twig", $services, array()); } + //this could be saved more readable by using dom_import_simplexml (http://stackoverflow.com/questions/1191167/format-output-of-simplexml-asxml) $newXML = simplexml_load_file($services); if (!($servicesTag = $newXML->services)) { @@ -322,7 +323,12 @@ public function declareService() $formFactoryTag->addAttribute("id", "form.factory"); } - $newXML->saveXML($services); + $dom = new \DOMDocument("1.0"); + $dom->preserveWhiteSpace = false; + $dom->formatOutput = true; + $dom->loadXML($newXML->asXML()); + $dom->saveHTMLFile($services); + //$newXML->saveXML($services); $this->updateDIFile($fileName); } From 5c9f4392cc5a117abe5debdda53e4f80db37fe2a Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 1 Apr 2016 15:41:34 +0200 Subject: [PATCH 32/46] undid previous commit --- .../Generator/DoctrineRESTGenerator.php | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index d698c4b..f4d3de9 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -323,12 +323,7 @@ public function declareService() $formFactoryTag->addAttribute("id", "form.factory"); } - $dom = new \DOMDocument("1.0"); - $dom->preserveWhiteSpace = false; - $dom->formatOutput = true; - $dom->loadXML($newXML->asXML()); - $dom->saveHTMLFile($services); - //$newXML->saveXML($services); + $newXML->saveXML($services); $this->updateDIFile($fileName); } From 92f8fadd980b2d059f34f904766848ca89369c61 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Wed, 13 Apr 2016 08:10:25 +0200 Subject: [PATCH 33/46] removed input/output from ApiDoc which caused failures --- .../Resources/skeleton/rest/actions/patch.php.twig | 4 +--- .../Resources/skeleton/rest/actions/post.php.twig | 4 +--- .../Resources/skeleton/rest/actions/put.php.twig | 4 +--- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index c96ae58..577a85f 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -11,9 +11,7 @@ * 200 = "Updated object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * }, - * input = "{{ namespace }}\Form\{{ entity }}Type", - * output = "{{ namespace }}\Entity\{{ entity }}" + * } * ) {% endif %} {% endblock documentation %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 0fb8ff4..75b6e0a 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -11,9 +11,7 @@ * 201 = "Created object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * }, - * input = "{{ namespace }}\Form\{{ entity }}Type", - * output = "{{ namespace }}\Entity\{{ entity }}" + * } * ) {% endif %} {% endblock documentation %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index ddd77ee..dd1d49b 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -12,9 +12,7 @@ * 201 = "Created object.", * 400 = "Bad Request. Verify your params.", * 404 = "Not Found." - * }, - * input = "{{ namespace }}\Form\{{ entity }}Type", - * output = "{{ namespace }}\Entity\{{ entity }}" + * } * ) {% endif %} {% endblock documentation %} From a54d6c72638bd193263d3007ba0ce50751f8486d Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 15 Apr 2016 10:42:41 +0200 Subject: [PATCH 34/46] alpha version of test generation --- .../Command/GenerateDoctrineRESTCommand.php | 61 ++++++++++++++++++- .../Command/Validators.php | 31 ++++++++++ .../Generator/DoctrineRESTGenerator.php | 19 ++++-- .../Resources/skeleton/rest/test.php.twig | 40 ++++++++++++ .../rest/tests/base/oauthBase.php.twig | 59 ++++++++++++++++++ .../rest/tests/oauth2/delete.php.twig | 11 ++++ .../skeleton/rest/tests/oauth2/get.php.twig | 11 ++++ .../rest/tests/oauth2/getAfterDelete.php.twig | 5 ++ .../rest/tests/oauth2/getAll.php.twig | 15 +++++ .../oauth2/getAllWithoutContent.php.twig | 8 +++ .../skeleton/rest/tests/oauth2/patch.php.twig | 18 ++++++ .../skeleton/rest/tests/oauth2/post.php.twig | 13 ++++ .../skeleton/rest/tests/oauth2/put.php.twig | 18 ++++++ .../skeleton/rest/tests/oauth2/setup.php.twig | 35 +++++++++++ 14 files changed, 337 insertions(+), 7 deletions(-) create mode 100644 src/Voryx/RESTGeneratorBundle/Command/Validators.php create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/oauthBase.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 16415dd..218db83 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -41,9 +41,10 @@ protected function configure() new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), new InputOption('format', '', InputOption::VALUE_OPTIONAL, 'The format used for generation of routing (yml or annotation)', 'yml'), + new InputOption('test', '', InputOption::VALUE_OPTIONAL, 'Generate a test for the given authentication mode (oauth2, no-authentication, none, csrf)', 'none'), new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), new InputOption('resource', '', InputOption::VALUE_NONE, 'The object will return with the resource name'), - new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller'), + new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller') ) ) ->setDescription('Generates a REST api based on a Doctrine entity') @@ -97,6 +98,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $prefix = $this->getRoutePrefix($input, $entity); /** @var bool $forceOverwrite */ $forceOverwrite = $input->getOption('overwrite'); + $test = $input->getOption('test'); $questionHelper->writeSection($output, 'REST api generation'); @@ -108,9 +110,13 @@ protected function execute(InputInterface $input, OutputInterface $output) /** @var DoctrineRESTGenerator $generator */ $generator = $this->getGenerator($bundle); - $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document, $format); + $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document, $format, $test); $output->writeln('Generating the REST api code: OK'); + if ($test === 'oauth2') + { + $output->writeln('Please make sure you check the Tests/oauthBase.php and fill in a correct username/password on line 17/18 before running the test.'); + } $errors = array(); $runner = $questionHelper->getRunner($output, $errors); @@ -159,6 +165,20 @@ protected function interact(InputInterface $input, OutputInterface $output) $input->setOption('entity', $entity); list($bundle, $entity) = $this->parseShortcutNotation($entity); + //routing format + $output->writeln( + array( + '', + 'Determine the routing format.', + '' + ) + ); + $question = new Question($questionHelper->getQuestion('Routing format', $input->getOption('format'))); + $question->setValidator(array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateFormat')); + $format = $questionHelper->ask($input, $output, $question); + + $input->setOption('format',$format); + // route prefix $prefix = 'api'; $output->writeln( @@ -173,6 +193,27 @@ protected function interact(InputInterface $input, OutputInterface $output) $prefix = $questionHelper->ask($input, $output, new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix)); $input->setOption('route-prefix', $prefix); + //testing mode + $output->writeln( + array( + '', + 'Determine what kind of test you want to have generated (if any)', + '', + 'Possible values are none, no-authentication, csrf and oauth2', + '' + ) + ); + $question = new Question($questionHelper->getQuestion('What type of tests do you want to generate?', $input->getOption('test'))); + $question->setValidator(array('Voryx\RESTGeneratorBundle\Command\Validators', 'validateTestFormat')); + $test = $questionHelper->ask($input, $output, $question); + + $input->setOption('test',$test); + + if ($test === 'oauth') + { + $this->interactWithOAuthTestMode($input, $output); + } + // summary $output->writeln( array( @@ -186,6 +227,22 @@ protected function interact(InputInterface $input, OutputInterface $output) } + public function interactWithOAuthTestMode(InputInterface $input, OutputInterface $output) + { + $questionHelper = $this->getQuestionHelper(); + + $input->setOption('test_username', 'apiuser'); + $input->setOption('test_password', 'password'); + + $question = new Question($questionHelper->getQuestion('With what username should we try to authenticate using OAuth2?', $input->getOption('test_username'))); + $test_username = $questionHelper->ask($input, $output, $question); + $input->setOption('test_username', $test_username); + + $question = new Question($questionHelper->getQuestion('And what is the password for '.$test_username.'?', $input->getOption('test_password'))); + $test_password = $questionHelper->ask($input, $output, $question); + $input->setOption('test_password', $test_password); + } + /** * @param QuestionHelper $questionHelper * @param InputInterface $input diff --git a/src/Voryx/RESTGeneratorBundle/Command/Validators.php b/src/Voryx/RESTGeneratorBundle/Command/Validators.php new file mode 100644 index 0000000..4cc85a5 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Command/Validators.php @@ -0,0 +1,31 @@ + + */ +class Validators +{ + public static function validateTestFormat($format) + { + if (!$format) { + return 'none'; + } + + if ($format === 'oauth') { + $format = 'oauth2'; + } + + $format = strtolower($format); + + if (!in_array($format, array('none', 'oauth2', 'no-authentication', 'csrf'))) { + throw new \RuntimeException(sprintf('Test format "%s" is not supported, only '.implode(',',$format).' are supported.', $format)); + } + + return $format; + } +} diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index f4d3de9..0d210f0 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -57,10 +57,11 @@ public function __construct(Filesystem $filesystem) * @param string $routePrefix The route name prefix * @param bool $forceOverwrite Whether or not to overwrite an existing controller * @param bool $resource - * @param bool $document - * @param string $format + * @param bool $document Whether or not to use Nelmio api documentation + * @param string $format Format of routing + * @param string $test Test-mode (none, oauth or no-authentication) */ - public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata,$routePrefix,$forceOverwrite,$resource,$document,$format) + public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata,$routePrefix,$forceOverwrite,$resource,$document,$format, $test) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = str_replace('/', '_', $routePrefix); @@ -87,6 +88,7 @@ public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $meta $this->generateHandler($forceOverwrite, $document); $this->generateExceptionClass(); $this->declareService(); + $this->generateTestClass($test); } /** @@ -375,10 +377,15 @@ private function handleExtensionFileCreation($fileName) /** * Generates the functional test class only. - * + * @param string $format either none, no-authentication or oauth */ - protected function generateTestClass() + protected function generateTestClass($format) { + if ($format === 'none') + { + return; + } + $dir = $this->bundle->getPath() . '/Tests/Controller'; $parts = explode('\\', $this->entity); @@ -391,6 +398,8 @@ protected function generateTestClass() 'rest/tests/test.php.twig', $target, array( + 'format' => $format, + 'fields' => $this->metadata->fieldMappings, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, 'entity' => $this->entity, diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig new file mode 100644 index 0000000..1875a3d --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig @@ -0,0 +1,40 @@ +getKernel()); + $application->add(new CreateOAuthClientCommand()); + + /** @var Command $command */ + $command = $application->find('extendas:oauth-server:client:create'); + $commandTester = new CommandTester($command); + $commandTester->execute([ + 'command' => $command->getName(), + '--grant-type' => ['authorization_code', 'password', 'refresh_token', 'client_credentials'], + ]); + + $response = $commandTester->getDisplay(); + $this->assertEquals(0, strpos($response, 'Added a new client with public id')); + $keys = preg_split('/,/', $response); + $public_id_text = trim($keys[0]); + $secret_id_text = trim($keys[1]); + + $public_key_split = preg_split('/ /', $public_id_text); + $secret_key_split = preg_split('/ /', $secret_id_text); + + self::$client_id = end($public_key_split); + self::$client_secret = end($secret_key_split); + $this->assertNotEquals(self::$client_id, null); + $this->assertNotEquals(self::$client_secret, null); + + $url = "/oauth/v2/token?client_id=".self::$client_id.'&client_secret='.self::$client_secret.'&grant_type=password'. + '&username='.$this->username.'&password='.$this->password; + $crawler = $client->request('GET', $url, array(), array(), array('HTTP_ACCEPT' => 'application/json', 'HTTP_CONTENT_TYPE' => 'application/json')); + $json_object = json_decode($client->getResponse()->getContent()); + self::$access_token = $json_object->access_token; + } +} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig new file mode 100644 index 0000000..650afee --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig @@ -0,0 +1,11 @@ +public function testDelete() +{ + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig new file mode 100644 index 0000000..ef310e5 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig @@ -0,0 +1,11 @@ +public function testGet() +{ + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig new file mode 100644 index 0000000..0ce3920 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig @@ -0,0 +1,5 @@ +public function testGetOnDeletedItem() +{ + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig new file mode 100644 index 0000000..1bbc042 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig @@ -0,0 +1,15 @@ +public function testGetAllWithContent() +{ + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); + $this->assertTrue(count($obj) > 0, 'expected decoded response content to be an array with more then 0 items, got '.count($obj)); + $first = reset($obj); + $this->assertTrue(array_key_exists('id', $first), 'expected first array item to have a key id'); + self::$id = $first->id; +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig new file mode 100644 index 0000000..f4e202c --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig @@ -0,0 +1,8 @@ +public function testGetAllWithoutContent() +{ + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig new file mode 100644 index 0000000..49b2436 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig @@ -0,0 +1,18 @@ +public function testPatch() +{ + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + + $json = json_encode(self::$sample_object); + + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + //test response content + //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); + //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig new file mode 100644 index 0000000..607b36b --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig @@ -0,0 +1,13 @@ +public function testPost() +{ + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after posting to api/post.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $extra_help = 'If this test fails with a 500 status code, make sure the properties in the entity that should be required are annotated with @Symfony\Component\Validator\Constraints\NotBlank (or @Constraints\NotBlank and use Symfony\Component\Validator\Constraints;), remove this test if it doesn\'t apply to u.'; + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), "Expected a 400 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json without content, but got ".self::$client->getResponse()->getStatusCode().".\r\n".$extra_help); + + $json = json_encode(self::$sample_object); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig new file mode 100644 index 0000000..437c3e2 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig @@ -0,0 +1,18 @@ +public function testPut() +{ + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + + $json = json_encode(self::$sample_object); + + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + //test response content + //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); + //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); +} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig new file mode 100644 index 0000000..ab1fa73 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig @@ -0,0 +1,35 @@ +/** @var Client */ +private static $client; + +private static $id; + +private static $sample_object; + +public function setUp() +{ + parent::setUp(); + self::$client = static::createClient(); + + ${{ entity|lower }}_object = array(); + {%- for field, info in fields if info['id'] is not defined or info['id'] == false %} + {%- if info['type'] == 'string' %} + ${{ entity|lower }}_object['{{ field }}'] = 'test_{{ field }}'; + {%- if info['type'] == 'text' %} + ${{ entity|lower }}_object['{{ field }}'] = 'test_{{ field }}_'.substr(str_shuffle(md5(time())),0,255); + {%- elseif info['type'] == 'integer' or info['type'] == 'smallint' or info['type'] == 'bigint' %} + ${{ entity|lower }}_object['{{ field }}'] = 1; + {%- elseif info['type'] == 'decimal' or info['type'] == 'float' %} + ${{ entity|lower }}_object['{{ field }}'] = 1.11; + {%- elseif info['type'] == 'boolean' %} + ${{ entity|lower }}_object['{{ field }}'] = true; + {%- elseif info['type'] == 'date' or info['type'] == 'datetime' or info['type'] == 'datetimetz' or info['type'] == 'time' %} + ${{ entity|lower }}_object['{{ field }}'] = new \DateTime('now'); + {# implement support for array types. #} + {%- else %} + {{ field }}.{{ info.type }} + {{ dump(info) }} + {%- endif %} + {%- endfor %} + + self::$sample_object = ${{ entity|lower }}_object; +} \ No newline at end of file From 0fea7c38d1b7bb1128c002907a425d637d0e4591 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 15 Apr 2016 10:56:28 +0200 Subject: [PATCH 35/46] bug fix for wrong reference to test.php.twig --- .../RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 0d210f0..6752584 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -395,7 +395,7 @@ protected function generateTestClass($format) $target = $dir . '/' . str_replace('\\', '/', $entityNamespace) . '/' . $entityClass . 'RESTControllerTest.php'; $this->renderFile( - 'rest/tests/test.php.twig', + 'rest/test.php.twig', $target, array( 'format' => $format, From fae1f6406331e23e2cd95feb3789b597d958d798 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 15 Apr 2016 11:03:54 +0200 Subject: [PATCH 36/46] undid rendering of tests since it gave hard errors --- .../Resources/skeleton/rest/test.php.twig | 18 +++++++++--------- .../skeleton/rest/tests/oauth2/setup.php.twig | 1 - 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig index 1875a3d..a8e5ecc 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig @@ -19,22 +19,22 @@ class {{ entity_class }}RESTControllerTest{%- if format == 'oauth2' %} extends O { {% block class_body %} - {%- include 'rest/tests/'{{ format }}'/setup.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/setup.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/getAllWithoutContent.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/getAllWithoutContent.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/post.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/post.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/getAll.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/getAll.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/get.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/get.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/put.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/put.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/patch.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/patch.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/delete.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/delete.php.twig' %}#} - {%- include 'rest/tests/'{{ format }}'/getAfterDelete.php.twig' %} + {#{%- include 'rest/tests/'{{ format }}'/getAfterDelete.php.twig' %}#} {% endblock class_body %} } \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig index ab1fa73..510067f 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig @@ -27,7 +27,6 @@ public function setUp() {# implement support for array types. #} {%- else %} {{ field }}.{{ info.type }} - {{ dump(info) }} {%- endif %} {%- endfor %} From f9cb2692bf70c6a2df19d4d066539ce279747a95 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 22 Apr 2016 15:51:35 +0200 Subject: [PATCH 37/46] Develop > Master (Implemented tests and fixed interactive mode) (#2) # Implemented - automatic test generation - handling of entity constraints for tests - added yml support for service definition # Details * fixed typo * added creation of test base case * did this cause hard error? * fix for twig syntax error * fix for formatting of the included tests * fixed double if in oauth/setup.php.twig * object fields should not be put after eachother but under eachother * object fields should not be put after eachother but under eachother * added templates for no-authentication test * added friendly test mode function * added friendly test mode function * added friendly test mode function * added friendly test mode function * fixed typos in test cases * setup.php.twig format fixes * setup.php.twig format fixes * mode oauth base case command independent * added returning response content on error in tests * fixed defaults in interactive mode * removed non-working interactive mode for oauth username/password * fixed problems in oauth2 base testcase * fix for tests of oauth * added alpha version of ManyToOne support * added support for array and date internval types in testing * fixed typo in oauth setup for loop * added test version of service generation as YML format * added test version of service generation as YML format * fixed handlers so Entities in sub maps is supported * fixed handlers so Entities in sub maps is supported * fixed handlers so Entities in sub maps is supported * changed BaseTest location to be always in the root of Base * made tests independant of entity being in sub-map (AppBundle:User/User) * added usage of parameters in services.yml * made controller compatible with sub-entity (AppBundle:User\User) * fixed type in generation of serviceREST.yml file * fixed twig replace for controller actions * now using YmlLoader for loading yml instead of the XmlLoader * removed unused testing code and now adding services/params to service yml file instead of replacing them * added support of ManyToOne and OneToMany fields in oauth test case * added forgotten line closing ';' * made assoc field suffix with underscore for clarity * added a parameter overview to the readmes and fixed some layout issues in the setup for oauth test * added comments to setup * re-formatted the setup for testing and made it for both oauth and no-authentication * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * made bundle symfony dependant (added symfony to composer) and added testing version of checking constraints for fields in the test * made bundle symfony dependant (added symfony to composer) and added testing version of checking constraints for fields in the test * added constraint handling in setup template * added support for length constraint --- README.Symfony3.md | 20 ++ README.md | 21 ++ composer.json | 1 + .../Command/GenerateDoctrineRESTCommand.php | 94 ++++--- .../Command/Validators.php | 35 ++- .../Generator/DoctrineRESTGenerator.php | 172 +++++++++++-- .../skeleton/rest/actions/delete.php.twig | 4 +- .../skeleton/rest/actions/getAll.php.twig | 2 +- .../skeleton/rest/actions/getById.php.twig | 2 +- .../skeleton/rest/actions/getOr404.php.twig | 4 +- .../skeleton/rest/actions/patch.php.twig | 2 +- .../skeleton/rest/actions/post.php.twig | 2 +- .../skeleton/rest/actions/put.php.twig | 6 +- .../skeleton/rest/handler/construct.php.twig | 2 +- .../skeleton/rest/handler/delete.php.twig | 6 +- .../skeleton/rest/handler/extras.php.twig | 18 +- .../skeleton/rest/handler/get.php.twig | 2 +- .../skeleton/rest/handler/getAll.php.twig | 2 +- .../skeleton/rest/handler/patch.php.twig | 8 +- .../skeleton/rest/handler/post.php.twig | 6 +- .../skeleton/rest/handler/put.php.twig | 8 +- .../skeleton/rest/service/services.yml.twig | 3 + .../Resources/skeleton/rest/test.php.twig | 22 +- .../skeleton/rest/tests/base/csrf.php.twig | 18 ++ .../tests/base/no-authentication.php.twig | 18 ++ .../{oauthBase.php.twig => oauth2.php.twig} | 41 ++- .../tests/no-authentication/delete.php.twig | 6 + .../rest/tests/no-authentication/get.php.twig | 6 + .../no-authentication/getAfterDelete.php.twig | 6 + .../tests/no-authentication/getAll.php.twig | 13 + .../getAllWithoutContent.php.twig | 6 + .../tests/no-authentication/patch.php.twig | 13 + .../tests/no-authentication/post.php.twig | 7 + .../rest/tests/no-authentication/put.php.twig | 13 + .../tests/no-authentication/setup.php.twig | 86 +++++++ .../rest/tests/oauth2/delete.php.twig | 19 +- .../skeleton/rest/tests/oauth2/get.php.twig | 19 +- .../rest/tests/oauth2/getAfterDelete.php.twig | 11 +- .../rest/tests/oauth2/getAll.php.twig | 27 +- .../oauth2/getAllWithoutContent.php.twig | 15 +- .../skeleton/rest/tests/oauth2/patch.php.twig | 26 +- .../skeleton/rest/tests/oauth2/post.php.twig | 23 +- .../skeleton/rest/tests/oauth2/put.php.twig | 26 +- .../skeleton/rest/tests/oauth2/setup.php.twig | 240 +++++++++++++++--- 44 files changed, 842 insertions(+), 239 deletions(-) create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.yml.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/csrf.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/no-authentication.php.twig rename src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/{oauthBase.php.twig => oauth2.php.twig} (52%) create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig create mode 100644 src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/setup.php.twig diff --git a/README.Symfony3.md b/README.Symfony3.md index d405b90..b6cb203 100644 --- a/README.Symfony3.md +++ b/README.Symfony3.md @@ -110,6 +110,26 @@ Generate the API controller: $ php bin/console voryx:generate:rest --entity="AppBundle:Post" ``` +Full example with all parameters + +```bash +$ php app/console voryx:generate:rest --entity="AppBundle:Post" --document --overwrite --route-prefix="api" --route-format="yml" --service-format="yml" --test="none" +``` + +possible values for all parameters + +| Parameter | Explanation | Values | +| --------- | ----------- | ------- | +| entity | The entity for which the REST api should be generated | **AppBundle:Post**, **AppBundle:Blog\Post** +| document | Whether or not you want API's documented by Nelmio | Yes if present, else No +| overwrite | Whether or not you want to overwrite existing generated files | Yes if present, else No +| resource | - | Yes if present, else No +| route-prefix | The route to prefix the generated Controller with (default api) | Any string +| route-format | The format that routing is generated in (default yml) | **yml** or **annotation** +| service-format | The format that the service is generated in (default yml) | **yml** or **xml** +| test | The type of test that should be generated | **none**, **oauth** or **no-authentication** + + ### Using the API If you selected the default options you'll be able to start using the API like this: diff --git a/README.md b/README.md index d4fe37e..3080cc9 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,27 @@ Generate the API controller: $ php app/console voryx:generate:rest --entity="AppBundle:Post" ``` +Full example with all parameters + +```bash +$ php app/console voryx:generate:rest --entity="AppBundle:Post" --document --resource --overwrite --route-prefix="api" --route-format="yml" --service-format="yml" --test="none" +$ php app/console voryx:generate:rest --entity="AppBundle:User/Domain" --document --overwrite --route-prefix="api" --route-format="annotation" --service-format="yml" --test="oauth2" +``` + +possible values for all parameters + +| Parameter | Explanation | Values | +| --------- | ----------- | ------- | +| entity | The entity for which the REST api should be generated | **AppBundle:Post**, **AppBundle:Blog\Post** +| document | Whether or not you want API's documented by Nelmio | Yes if present, else No +| overwrite | Whether or not you want to overwrite existing generated files | Yes if present, else No +| resource | - | Yes if present, else No +| route-prefix | The route to prefix the generated Controller with (default api) | Any string +| route-format | The format that routing is generated in (default yml) | **yml** or **annotation** +| service-format | The format that the service is generated in (default yml) | **yml** or **xml** +| test | The type of test that should be generated | **none**, **oauth** or **no-authentication** + + ### Using the API If you selected the default options you'll be able to start using the API like this: diff --git a/composer.json b/composer.json index 28eb40e..23d622b 100644 --- a/composer.json +++ b/composer.json @@ -16,6 +16,7 @@ ], "require": { "php": ">=5.3.0", + "symfony/symfony": ">=2.8", "sensio/generator-bundle": "~3.0", "friendsofsymfony/rest-bundle": "~1.7", "jms/serializer-bundle": "~1.1", diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 218db83..4a6c676 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -13,9 +13,11 @@ use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; use Symfony\Component\DependencyInjection\Container; +use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper; +use Symfony\Component\Validator\Mapping\ClassMetadata; use Voryx\RESTGeneratorBundle\Generator\DoctrineRESTGenerator; use Sensio\Bundle\GeneratorBundle\Command\Validators; use Voryx\RESTGeneratorBundle\Manipulator\RoutingManipulator; @@ -40,8 +42,9 @@ protected function configure() array( new InputOption('entity', '', InputOption::VALUE_REQUIRED, 'The entity class name to initialize (shortcut notation)'), new InputOption('route-prefix', '', InputOption::VALUE_REQUIRED, 'The route prefix'), - new InputOption('format', '', InputOption::VALUE_OPTIONAL, 'The format used for generation of routing (yml or annotation)', 'yml'), - new InputOption('test', '', InputOption::VALUE_OPTIONAL, 'Generate a test for the given authentication mode (oauth2, no-authentication, none, csrf)', 'none'), + new InputOption('route-format', '', InputOption::VALUE_REQUIRED, 'The format used for generation of routing (yml or annotation)', 'yml'), + new InputOption('service-format', '', InputOption::VALUE_REQUIRED, 'The format used for generation of services (yml or xml)', 'yml'), + new InputOption('test', '', InputOption::VALUE_REQUIRED, 'Generate a test for the given authentication mode (oauth2, no-authentication, none)', 'none'), new InputOption('overwrite', '', InputOption::VALUE_NONE, 'Do not stop the generation if rest api controller already exist, thus overwriting all generated files'), new InputOption('resource', '', InputOption::VALUE_NONE, 'The object will return with the resource name'), new InputOption('document', '', InputOption::VALUE_NONE, 'Use NelmioApiDocBundle to document the controller') @@ -94,7 +97,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $entity = Validators::validateEntityName($input->getOption('entity')); list($bundle, $entity) = $this->parseShortcutNotation($entity); - $format = $input->getOption('format'); + $format = $input->getOption('route-format'); + $service_format = $input->getOption('service-format'); $prefix = $this->getRoutePrefix($input, $entity); /** @var bool $forceOverwrite */ $forceOverwrite = $input->getOption('overwrite'); @@ -107,10 +111,43 @@ protected function execute(InputInterface $input, OutputInterface $output) $bundle = $this->getContainer()->get('kernel')->getBundle($bundle); $resource = $input->getOption('resource'); $document = $input->getOption('document'); + $constraints = array(); + + $constraintMetadata = null; + try + { + /** @var \Symfony\Component\Validator\Validator\RecursiveValidator $validator */ + $validator = $this->getContainer()->get('validator'); + + /** @var ClassMetadata $constraintMetadata */ + $constraintMetadata = $validator->getMetadataFor(new $entityClass); + foreach($constraintMetadata->getConstrainedProperties() as $property) + { + //var_dump($constraint_metadata->getPropertyMetadata($property)); + $constraints[$property] = $constraintMetadata->getPropertyMetadata($property)[0]->constraints; + } + } + catch(ServiceNotFoundException $snfex) + { + //no constraints are checked + $output->writeln($snfex->getMessage()); + } + catch(\Exception $ex) + { + $output->writeln($ex->getMessage()); + } + + if ($constraintMetadata === null) + { + if ($test !== 'none') + { + $output->writeln('No class constraint metadata found for entity ' . $entityClass . ''); + } + } /** @var DoctrineRESTGenerator $generator */ $generator = $this->getGenerator($bundle); - $generator->generate($bundle, $entity, $metadata[0], $prefix, $forceOverwrite, $resource, $document, $format, $test); + $generator->generate($bundle, $entity, $metadata[0], $constraints, $prefix, $forceOverwrite, $resource, $document, $format, $service_format, $test); $output->writeln('Generating the REST api code: OK'); if ($test === 'oauth2') @@ -166,18 +203,19 @@ protected function interact(InputInterface $input, OutputInterface $output) list($bundle, $entity) = $this->parseShortcutNotation($entity); //routing format + $format = $input->getOption('route-format'); $output->writeln( array( '', - 'Determine the routing format.', + 'Determine the routing format (yml or annotation).', '' ) ); - $question = new Question($questionHelper->getQuestion('Routing format', $input->getOption('format'))); + $question = new Question($questionHelper->getQuestion('Routing format', $format), $format); $question->setValidator(array('Sensio\Bundle\GeneratorBundle\Command\Validators', 'validateFormat')); $format = $questionHelper->ask($input, $output, $question); - $input->setOption('format',$format); + $input->setOption('route-format',$format); // route prefix $prefix = 'api'; @@ -193,27 +231,36 @@ protected function interact(InputInterface $input, OutputInterface $output) $prefix = $questionHelper->ask($input, $output, new Question($questionHelper->getQuestion('Routes prefix', '/' . $prefix), '/' . $prefix)); $input->setOption('route-prefix', $prefix); + //service format + $serviceFormat = $input->getOption('service-format'); + $output->writeln( + array( + '', + 'Determine the service format (yml or xml).', + '' + ) + ); + $question = new Question($questionHelper->getQuestion('Service format', $serviceFormat), $serviceFormat); + $question->setValidator(array('Voryx\RESTGeneratorBundle\Command\Validators', 'validateServiceFormat')); + $serviceFormat = $questionHelper->ask($input, $output, $question); + + $input->setOption('service-format',$serviceFormat); + //testing mode $output->writeln( array( '', 'Determine what kind of test you want to have generated (if any)', - '', - 'Possible values are none, no-authentication, csrf and oauth2', + 'Possible values are none (no tests), no-authentication and oauth2', '' ) ); - $question = new Question($questionHelper->getQuestion('What type of tests do you want to generate?', $input->getOption('test'))); + $question = new Question($questionHelper->getQuestion('What type of tests do you want to generate?', $input->getOption('test')),$input->getOption('test')); $question->setValidator(array('Voryx\RESTGeneratorBundle\Command\Validators', 'validateTestFormat')); $test = $questionHelper->ask($input, $output, $question); $input->setOption('test',$test); - if ($test === 'oauth') - { - $this->interactWithOAuthTestMode($input, $output); - } - // summary $output->writeln( array( @@ -226,23 +273,6 @@ protected function interact(InputInterface $input, OutputInterface $output) ); } - - public function interactWithOAuthTestMode(InputInterface $input, OutputInterface $output) - { - $questionHelper = $this->getQuestionHelper(); - - $input->setOption('test_username', 'apiuser'); - $input->setOption('test_password', 'password'); - - $question = new Question($questionHelper->getQuestion('With what username should we try to authenticate using OAuth2?', $input->getOption('test_username'))); - $test_username = $questionHelper->ask($input, $output, $question); - $input->setOption('test_username', $test_username); - - $question = new Question($questionHelper->getQuestion('And what is the password for '.$test_username.'?', $input->getOption('test_password'))); - $test_password = $questionHelper->ask($input, $output, $question); - $input->setOption('test_password', $test_password); - } - /** * @param QuestionHelper $questionHelper * @param InputInterface $input diff --git a/src/Voryx/RESTGeneratorBundle/Command/Validators.php b/src/Voryx/RESTGeneratorBundle/Command/Validators.php index 4cc85a5..9451005 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/Validators.php +++ b/src/Voryx/RESTGeneratorBundle/Command/Validators.php @@ -10,6 +10,11 @@ */ class Validators { + /** + * @param string $format + * @return string + * @throws \RuntimeException + */ public static function validateTestFormat($format) { if (!$format) { @@ -22,10 +27,36 @@ public static function validateTestFormat($format) $format = strtolower($format); - if (!in_array($format, array('none', 'oauth2', 'no-authentication', 'csrf'))) { - throw new \RuntimeException(sprintf('Test format "%s" is not supported, only '.implode(',',$format).' are supported.', $format)); + $supported = array('none', 'oauth2', 'no-authentication', 'csrf'); + + if (!in_array($format, $supported)) { + throw new \RuntimeException(sprintf('Test format "%s" is not supported, only '.implode(',',$supported).' are supported.', $format)); } return $format; } + + /** + * @param string $service_format + * @return string + * @throws \RuntimeException + */ + public static function validateServiceFormat($service_format) + { + if (!$service_format) + { + return 'xml'; + } + + $service_format = strtolower($service_format); + + $supported_service_formats = array('xml', 'yml'); + + if (!in_array($service_format, $supported_service_formats)) + { + throw new \RuntimeException(sprintf('Service format "%s" is not supported, only '.implode(',',$supported_service_formats).' are supported.', $service_format)); + } + + return $service_format; + } } diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index 6752584..c50be1b 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -16,6 +16,10 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\HttpKernel\Bundle\BundleInterface; +use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Yaml\Parser; +use Symfony\Component\Yaml\Yaml; /** * Generates a REST controller. @@ -35,6 +39,7 @@ class DoctrineRESTGenerator extends Generator /** @var ClassMetadataInfo */ protected $metadata; + protected $entityConstraints; protected $format; protected $actions; @@ -54,14 +59,16 @@ public function __construct(Filesystem $filesystem) * @param BundleInterface $bundle A bundle object * @param string $entity The entity relative class name * @param ClassMetadataInfo $metadata The entity class metadata + * @param array $entityConstraints array of fields with constraints array('field' => array(Constraint, Constraint2),'field2' => array(Constraint, Constraint2)) * @param string $routePrefix The route name prefix * @param bool $forceOverwrite Whether or not to overwrite an existing controller * @param bool $resource * @param bool $document Whether or not to use Nelmio api documentation * @param string $format Format of routing + * @param string $service_format Format of service generation * @param string $test Test-mode (none, oauth or no-authentication) */ - public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata,$routePrefix,$forceOverwrite,$resource,$document,$format, $test) + public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $metadata, $entityConstraints,$routePrefix,$forceOverwrite,$resource,$document,$format, $service_format, $test) { $this->routePrefix = $routePrefix; $this->routeNamePrefix = str_replace('/', '_', $routePrefix); @@ -82,13 +89,14 @@ public function generate(BundleInterface $bundle,$entity,ClassMetadataInfo $meta $this->entity = $entity; $this->bundle = $bundle; $this->metadata = $metadata; + $this->entityConstraints = $entityConstraints; $this->setFormat($format); $this->generateControllerClass($forceOverwrite, $document, $resource); $this->generateHandler($forceOverwrite, $document); $this->generateExceptionClass(); - $this->declareService(); - $this->generateTestClass($test); + $this->declareService($service_format); + $this->generateTestClass($forceOverwrite, $test); } /** @@ -225,7 +233,7 @@ protected function generateHandler($forceOverwrite, $document) 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'format' => $this->format, - 'document' => $document + 'document' => $document, ) ); } @@ -252,21 +260,27 @@ public function generateExceptionClass() /** * Declares the handler as a service + * @param $service_format */ - public function declareService() + public function declareService($service_format) { $dir = $this->bundle->getPath(); $parts = explode('\\', $this->entity); $entityClass = array_pop($parts); $entityNamespace = implode('\\', $parts); + if (strlen($entityNamespace) > 0) + { + $entityNamespace .= '\\'; + } $namespace = $this->bundle->getNamespace(); $bundleName = strtolower($this->bundle->getName()); $entityName = strtolower($this->entity); + $entityName = str_replace('\\','.',$entityName); $services = sprintf( - "%s/Resources/config/servicesREST.xml", + "%s/Resources/config/servicesREST.".$service_format, $dir ); @@ -290,9 +304,25 @@ public function declareService() ); if (!is_file($services)) { - $this->renderFile("rest/service/services.xml.twig", $services, array()); + $this->renderFile("rest/service/services.".$service_format.".twig", $services, array()); } + switch($service_format) + { + case 'xml': + $this->handleServiceDeclarationAsXML($services,$newId, $handlerClass,$namespace,$entityNamespace,$entityClass,$fileName); + break; + case 'yml': + default: + $this->handleServiceDeclarationAsYML($services,$newId, $handlerClass,$namespace,$entityNamespace,$entityClass,$fileName); + break; + + } + $this->updateDIFile($fileName,$service_format); + } + + private function handleServiceDeclarationAsXML($services, $newId, $handlerClass,$namespace,$entityNamespace,$entityClass,$fileName) + { //this could be saved more readable by using dom_import_simplexml (http://stackoverflow.com/questions/1191167/format-output-of-simplexml-asxml) $newXML = simplexml_load_file($services); @@ -326,18 +356,64 @@ public function declareService() } $newXML->saveXML($services); - $this->updateDIFile($fileName); + } + + private function handleServiceDeclarationAsYML($services, $newId, $handlerClass,$namespace,$entityNamespace,$entityClass,$fileName) + { + $yml_file = Yaml::parse(file_get_contents($services)); + $params = $yml_file['parameters']; + $yml_file['parameters'] = + array_merge( + $params, + array( + $newId.'.handler_class' => $handlerClass, + $newId.'.entity_class' => sprintf( + "%s\\Entity\\%s%s", + $namespace, + $entityNamespace, + $entityClass + ), + ) + ); + $yml_services = $yml_file['services']; + $yml_file['services'] = + array_merge( + $yml_services, + array( + $newId => array( + 'class' => '%'.$newId.'.handler_class%', 'arguments' => array( + '@doctrine.orm.entity_manager', + '%'.$newId.'.entity_class%', + '@form.factory', + ), + ), + ) + ); + $yml_content = Yaml::dump($yml_file, 3); + file_put_contents($services, $yml_content); } /** * @param $fileName + * @param $serviceFormat */ - private function updateDIFile($fileName) + private function updateDIFile($fileName, $serviceFormat) { - $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . - "\t\t\$loader2->load('servicesREST.xml');" . PHP_EOL . "\t"; + $toInput = ''; + switch($serviceFormat) + { + case 'xml': + $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\XmlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . + "\t\t\$loader2->load('servicesREST.".$serviceFormat."');" . PHP_EOL . "\t"; + break; + case 'yml': + default: + $toInput = PHP_EOL . "\t\t\$loader2 = new Loader\\YamlFileLoader(\$container, new FileLocator(__DIR__ . '/../Resources/config'));" . PHP_EOL . + "\t\t\$loader2->load('servicesREST.".$serviceFormat."');" . PHP_EOL . "\t"; + break; + + } - $text = ''; if (!file_exists(dirname($fileName))) { mkdir(dirname($fileName), 0777, true); @@ -348,7 +424,7 @@ private function updateDIFile($fileName) } $text = file_get_contents($fileName); - if (strpos($text, "servicesREST.xml") == false) { + if (strpos($text, "servicesREST.".$serviceFormat) == false) { $position = strpos($text, "}", strpos($text, "function load(")); $newContent = substr_replace($text, $toInput, $position, 0); @@ -365,7 +441,7 @@ private function handleExtensionFileCreation($fileName) $entityNamespace = implode('\\', $parts); $this->renderFile( - 'rest//extension.php.twig', + 'rest/extension.php.twig', $fileName, array( 'class_name' => str_replace("Bundle", "Extension", $this->bundle->getName()), @@ -375,17 +451,33 @@ private function handleExtensionFileCreation($fileName) ); } + private function makeFormatUserFriendly($format) + { + $returnFormat = ''; + $parts = explode('-',$format); + foreach($parts as $part) + { + $returnFormat .= ucfirst($part); + } + + return $returnFormat; + } + /** * Generates the functional test class only. + * @param boolean $forceOverwrite whether or not to force overwriting or not * @param string $format either none, no-authentication or oauth */ - protected function generateTestClass($format) + protected function generateTestClass($forceOverwrite, $format) { if ($format === 'none') { return; } + $friendlyFormat = $this->makeFormatUserFriendly($format); + + $base_dir = $this->bundle->getPath() . '/Tests/Base'; $dir = $this->bundle->getPath() . '/Tests/Controller'; $parts = explode('\\', $this->entity); @@ -393,12 +485,61 @@ protected function generateTestClass($format) $entityNamespace = implode('\\', $parts); $target = $dir . '/' . str_replace('\\', '/', $entityNamespace) . '/' . $entityClass . 'RESTControllerTest.php'; + $base_target = $base_dir . '/' . $friendlyFormat . 'BaseCase.php'; + + if ($forceOverwrite === false && file_exists($target)) + { + throw new \RuntimeException('Unable to generate the test as it already exists.'); + } + + $this->generateBaseTestCaseIfNotExists($forceOverwrite, $format, $friendlyFormat, $base_target); $this->renderFile( 'rest/test.php.twig', $target, + array( + 'format' => $format, + 'friendly_format' => $friendlyFormat, + 'fields' => $this->metadata->fieldMappings, + 'assoc_mapping' => $this->metadata->associationMappings, + 'entity_constraints' => $this->entityConstraints, + 'base_file' => $base_target, + 'route_prefix' => $this->routePrefix, + 'route_name_prefix' => $this->routeNamePrefix, + 'entity' => $this->entity, + 'bundle' => $this->bundle->getName(), + 'entity_class' => $entityClass, + 'namespace' => $this->bundle->getNamespace(), + 'entity_namespace' => $entityNamespace, + 'actions' => $this->actions, + 'form_type_name' => strtolower(str_replace('\\', '_', $this->bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . $entityClass . 'Type'), + ) + ); + } + + /** + * @param $overwrite + * @param $format + * @param $friendlyFormat + * @param $target + */ + protected function generateBaseTestCaseIfNotExists($overwrite, $format, $friendlyFormat, $target) + { + $parts = explode('\\', $this->entity); + $entityClass = array_pop($parts); + $entityNamespace = implode('\\', $parts); + + if (file_exists($target)) + { + return; + } + + $this->renderFile( + 'rest/tests/base/'.$format.'.php.twig', + $target, array( 'format' => $format, + 'friendly_format' => $friendlyFormat, 'fields' => $this->metadata->fieldMappings, 'route_prefix' => $this->routePrefix, 'route_name_prefix' => $this->routeNamePrefix, @@ -408,7 +549,6 @@ protected function generateTestClass($format) 'namespace' => $this->bundle->getNamespace(), 'entity_namespace' => $entityNamespace, 'actions' => $this->actions, - 'form_type_name' => strtolower(str_replace('\\', '_', $this->bundle->getNamespace()) . ($parts ? '_' : '') . implode('_', $parts) . '_' . $entityClass . 'Type'), ) ); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig index f968602..39bb2e0 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/delete.php.twig @@ -33,9 +33,9 @@ {% endblock method_definition %} { {% block method_body %} - ${{ entity|lower }} = $this->getOr404($id); + ${{ entity_class|lower }} = $this->getOr404($id); try { - return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->delete(${{ entity|lower }}); + return $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->delete(${{ entity_class|lower }}); } catch (\Exception $exception) { throw new \RuntimeException("Exclusion not allowed"); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index b29509f..11115d0 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -43,7 +43,7 @@ $order_by = $paramFetcher->get('order_by'); $filters = !is_null($paramFetcher->get('filters')) ? $paramFetcher->get('filters') : array(); - $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->getAll($filters, $order_by, $limit, $offset); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->getAll($filters, $order_by, $limit, $offset); if ($answer{{ resource ? "['" ~ entity|lower ~ "']" }}) { return $answer; } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig index 40b5ffa..2a444db 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getById.php.twig @@ -32,7 +32,7 @@ {% endblock method_definition %} { {% block method_body %} - $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->getOr404($id); + $answer{{ resource ? "['" ~ entity_class|lower ~ "']" }} = $this->getOr404($id); return $answer; {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig index 93d5d78..19d2cc6 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getOr404.php.twig @@ -3,7 +3,7 @@ * Get a entity or throw a exception * * @param $id - * @return {{ entity }} $entity + * @return {{ entity_class }} $entity {% endblock phpdoc_method_header %} */ {% block method_definition %} @@ -11,7 +11,7 @@ {% endblock method_definition %} { {% block method_body %} - if (!($entity = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id))) { + if (!($entity = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->get($id))) { throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$id)); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig index 577a85f..8788060 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/patch.php.twig @@ -35,7 +35,7 @@ {% endblock method_definition %} { {% block method_body %} - $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->patch($this->getOr404($id), $request->request->all()); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->patch($this->getOr404($id), $request->request->all()); return $answer; {% endblock method_body %} {% block method_return '' %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig index 75b6e0a..9a3be5a 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/post.php.twig @@ -35,7 +35,7 @@ { {% block method_body %} try { - $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $new = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->post($request->request->all()); $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $new; return $answer; diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig index dd1d49b..b887391 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/put.php.twig @@ -37,11 +37,11 @@ { {% block method_body %} try { - if (${{ entity|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->get($id)) { - $answer{{ resource ? "['" ~ entity|lower ~ "']" }}= $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->put(${{ entity|lower }}, $request->request->all()); + if (${{ entity_class|lower }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->get($id)) { + $answer{{ resource ? "['" ~ entity|lower ~ "']" }}= $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->put(${{ entity_class|lower }}, $request->request->all()); $code = Codes::HTTP_OK; } else { - $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower }}.handler')->post($request->request->all()); + $answer{{ resource ? "['" ~ entity|lower ~ "']" }} = $this->container->get('{{ bundle|replace({'Bundle': ''})|lower}}.{{ entity|lower|replace({"\\":'.'}) }}.handler')->post($request->request->all()); $code = Codes::HTTP_CREATED; } } catch (InvalidFormException $exception) { diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig index b926fa7..96376ba 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/construct.php.twig @@ -1,6 +1,6 @@ /** {% block phpdoc_method_header %} - * {{ entity }}RESTHandler constructor. + * {{ entity_class }}RESTHandler constructor. * @param ObjectManager $om * @param $entityClass * @param FormFactoryInterface $formFactory diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig index bcaf138..aa1acbe 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/delete.php.twig @@ -1,17 +1,17 @@ /** {% block phpdoc_method_header %} - * @param {{ entity }} ${{ entity|lower }} + * @param {{ entity_class }} ${{ entity_class|lower }} * @return null * @throws \RuntimeException {% endblock phpdoc_method_header %} */ {% block method_definition %} - public function delete({{ entity }} ${{ entity|lower }}) + public function delete({{ entity_class }} ${{ entity_class|lower }}) {% endblock method_definition %} { {% block method_body %} try { - $this->om->remove(${{ entity|lower }}); + $this->om->remove(${{ entity_class|lower }}); $this->om->flush(); return null; diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig index cf91019..3d92fe3 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -1,33 +1,33 @@ {% block extras_methods %} /** {% block phpdoc_method_header %} - * @param {{ entity }} ${{ entity|lower }} + * @param {{ entity_class }} ${{ entity_class|lower }} * @param array $parameters * @param string $method - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} * @throws InvalidFormException {% endblock phpdoc_method_header %} */ - private function processForm({{ entity }} ${{ entity|lower }}, array $parameters, $method = "PUT") + private function processForm({{ entity_class }} ${{ entity_class|lower }}, array $parameters, $method = "PUT") { - $form = $this->formFactory->create(new {{ entity }}Type(), ${{ entity|lower }}, array('method' => $method)); + $form = $this->formFactory->create(new {{ entity_class }}Type(), ${{ entity_class|lower }}, array('method' => $method)); $form->submit($parameters, 'PATCH' !== $method); if ($form->isValid()) { - ${{ entity|lower }} = $form->getData(); - $this->om->persist(${{ entity|lower }}); + ${{ entity_class|lower }} = $form->getData(); + $this->om->persist(${{ entity_class|lower }}); $this->om->flush(); - return ${{ entity|lower }}; + return ${{ entity_class|lower }}; } throw new InvalidFormException('Invalid submitted data', $form); } {% if document %} /** - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} */ {% endif %} - private function create{{ entity }}() + private function create{{ entity_class }}() { return new $this->entityClass(); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig index 877deeb..f7adfb5 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/get.php.twig @@ -1,7 +1,7 @@ /** {% block phpdoc_method_header %} * @param int $id - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} {% endblock phpdoc_method_header %} */ {% block method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig index 65044e2..b1f1dad 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/getAll.php.twig @@ -4,7 +4,7 @@ * @param string|null $order_by The field to order by * @param int|null $limit The limit * @param int|null $offset The offset from the first record - * @return {{ entity }}[] ${{ entity|lower }}s + * @return {{ entity_class }}[] ${{ entity_class|lower }}s {% endblock phpdoc_method_header %} */ {% block method_definition %} diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig index ec26360..8dce3d7 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/patch.php.twig @@ -1,17 +1,17 @@ /** {% block phpdoc_method_header %} - * @param {{ entity }} ${{ entity|lower }} + * @param {{ entity_class }} ${{ entity_class|lower }} * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} * @throws InvalidFormException {% endblock phpdoc_method_header %} */ {% block method_definition %} - public function patch({{ entity }} ${{ entity|lower }}, array $parameters) + public function patch({{ entity_class }} ${{ entity_class|lower }}, array $parameters) {% endblock method_definition %} { {% block method_body %} - return $this->processForm(${{ entity|lower }}, $parameters, 'PATCH'); + return $this->processForm(${{ entity_class|lower }}, $parameters, 'PATCH'); {% endblock method_body %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig index 9a39457..6b1d84d 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/post.php.twig @@ -1,7 +1,7 @@ /** {% block phpdoc_method_header %} * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} * @throws InvalidFormException {% endblock phpdoc_method_header %} */ @@ -10,9 +10,9 @@ {% endblock method_definition %} { {% block method_body %} - ${{ entity|lower }} = $this->create{{ entity }}(); + ${{ entity_class|lower }} = $this->create{{ entity_class }}(); - return $this->processForm(${{ entity|lower }}, $parameters, 'POST'); + return $this->processForm(${{ entity_class|lower }}, $parameters, 'POST'); {% endblock method_body %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig index e241a09..7c5eddf 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/put.php.twig @@ -1,17 +1,17 @@ /** {% block phpdoc_method_header %} - * @param {{ entity }} ${{ entity|lower }} + * @param {{ entity_class }} ${{ entity_class|lower }} * @param array $parameters - * @return {{ entity }} ${{ entity|lower }} + * @return {{ entity_class }} ${{ entity_class|lower }} * @throws InvalidFormException {% endblock phpdoc_method_header %} */ {% block method_definition %} - public function put({{ entity }} ${{ entity|lower }}, array $parameters) + public function put({{ entity_class }} ${{ entity_class|lower }}, array $parameters) {% endblock method_definition %} { {% block method_body %} - return $this->processForm(${{ entity|lower }}, $parameters, 'PUT'); + return $this->processForm(${{ entity_class|lower }}, $parameters, 'PUT'); {% endblock method_body %} } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.yml.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.yml.twig new file mode 100644 index 0000000..12b6ebf --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/service/services.yml.twig @@ -0,0 +1,3 @@ +parameters: + +services: diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig index a8e5ecc..c126411 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/test.php.twig @@ -3,7 +3,7 @@ namespace {{ namespace }}\Tests\Controller{{ entity_namespace ? '\\' ~ entity_namespace : '' }}; {% block use_statements %} -use AppBundle\Tests\Base\OAuthApiTest; +use {{ namespace }}\Tests\Base\{{ friendly_format }}BaseCase; use Symfony\Bundle\FrameworkBundle\Client; {% endblock use_statements %} @@ -14,27 +14,27 @@ use Symfony\Bundle\FrameworkBundle\Client; {% endblock phpdoc_class_header %} */ {% block class_definition %} -class {{ entity_class }}RESTControllerTest{%- if format == 'oauth2' %} extends OAuthApiTest{%- endif %} +class {{ entity_class }}RESTControllerTest extends {{ friendly_format }}BaseCase {% endblock class_definition %} { {% block class_body %} - {#{%- include 'rest/tests/'{{ format }}'/setup.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/setup.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/getAllWithoutContent.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/getAllWithoutContent.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/post.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/post.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/getAll.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/getAll.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/get.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/get.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/put.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/put.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/patch.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/patch.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/delete.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/delete.php.twig' %} - {#{%- include 'rest/tests/'{{ format }}'/getAfterDelete.php.twig' %}#} + {%- include 'rest/tests/' ~ format ~ '/getAfterDelete.php.twig' %} {% endblock class_body %} } \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/csrf.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/csrf.php.twig new file mode 100644 index 0000000..1ac64e0 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/base/csrf.php.twig @@ -0,0 +1,18 @@ +username === null || $this->password === null) { die('Please make sure to fill in an API user username/password in this file (path/to/Tests/oauthBase.php)'); } parent::__construct(); $client = static::createClient(); - $application = new Application($client->getKernel()); - $application->add(new CreateOAuthClientCommand()); - - /** @var Command $command */ - $command = $application->find('extendas:oauth-server:client:create'); - $commandTester = new CommandTester($command); - $commandTester->execute([ - 'command' => $command->getName(), - '--grant-type' => ['authorization_code', 'password', 'refresh_token', 'client_credentials'], - ]); - - $response = $commandTester->getDisplay(); - $this->assertEquals(0, strpos($response, 'Added a new client with public id')); - $keys = preg_split('/,/', $response); - $public_id_text = trim($keys[0]); - $secret_id_text = trim($keys[1]); - - $public_key_split = preg_split('/ /', $public_id_text); - $secret_key_split = preg_split('/ /', $secret_id_text); - - self::$client_id = end($public_key_split); - self::$client_secret = end($secret_key_split); + $clientManager = $client->getContainer()->get('fos_oauth_server.client_manager.default'); + /** @var OAuthClient $oauth_client */ + $oauth_client = $clientManager->createClient(); + $oauth_client->setRedirectUris(array()); + $oauth_client->setAllowedGrantTypes(array('authorization_code', 'password', 'refresh_token', 'client_credentials')); + $clientManager->updateClient($oauth_client); + + $public_key_split = $oauth_client->getPublicId(); + $secret_key_split = $oauth_client->getSecret(); + + self::$client_id = $public_key_split; + self::$client_secret = $secret_key_split; $this->assertNotEquals(self::$client_id, null); $this->assertNotEquals(self::$client_secret, null); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig new file mode 100644 index 0000000..a445ad5 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig @@ -0,0 +1,6 @@ + public function testDelete() + { + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig new file mode 100644 index 0000000..55f03d4 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig @@ -0,0 +1,6 @@ + public function testGet() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig new file mode 100644 index 0000000..135dfe9 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig @@ -0,0 +1,6 @@ + public function testGetOnDeletedItem() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig new file mode 100644 index 0000000..c6ffdbc --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig @@ -0,0 +1,13 @@ + public function testGetAllWithContent() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); + $this->assertTrue(count($obj) > 0, 'expected decoded response content to be an array with more then 0 items, got '.count($obj)); + $first = reset($obj); + $this->assertTrue(array_key_exists('id', $first), 'expected first array item to have a key id'); + self::$id = $first->id; + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig new file mode 100644 index 0000000..bf83e2d --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig @@ -0,0 +1,6 @@ + public function testGetAllWithoutContent() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig new file mode 100644 index 0000000..83adfd3 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig @@ -0,0 +1,13 @@ + public function testPatch() + { + $json = json_encode(self::$sample_object); + + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + //test response content + //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); + //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig new file mode 100644 index 0000000..ec33a99 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig @@ -0,0 +1,7 @@ + public function testPost() + { + $json = json_encode(self::$sample_object); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig new file mode 100644 index 0000000..9836c97 --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig @@ -0,0 +1,13 @@ + public function testPut() + { + $json = json_encode(self::$sample_object); + + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + //test response content + //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); + //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/setup.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/setup.php.twig new file mode 100644 index 0000000..373e5bf --- /dev/null +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/setup.php.twig @@ -0,0 +1,86 @@ +/** @var Client */ +private static $client; + +private static $id; + +private static $sample_object; + +public function setUp() +{ +parent::setUp(); +self::$client = static::createClient(); +//$em = self::$client->getContainer()->get('doctrine'); + +//create assocation fields (relations from this entity) +{%- for key, assoc in assoc_mapping %} + {%- if (assoc['type'] == 4 or assoc['type'] == 8) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 4 == OneToMany, type 8 == ManyToMany #} + + $assoc_{{ key }} = array(); + $field_{{ assoc['fieldName']|capitalize }} = new \{{ assoc['targetEntity'] }}; + //set fields of $field_{{ assoc['fieldName']|capitalize }}. + $assoc_{{ key }}[] = $field_{{ assoc['fieldName']|capitalize }}; + + + {%- elseif (assoc['type'] == 1 or assoc['type'] == 2) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 1 == OneToOne, type 2 == ManyToOne #} + + $assoc_{{ key }} = new \{{ assoc['targetEntity'] }}; + + + {%- endif %} +{%- endfor %} + +//create main object +${{ entity_class|lower }}_object = array(); +{%- for field, info in fields if info['id'] is not defined or info['id'] == false -%} + {%- if info['type'] == 'string' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 'test_{{ field }}'; + + {%- elseif info['type'] == 'text' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 'test_{{ field }}_'.substr(str_shuffle(md5(time())),0,255); + + {%- elseif info['type'] == 'integer' or info['type'] == 'smallint' or info['type'] == 'bigint' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 1; + + {%- elseif info['type'] == 'decimal' or info['type'] == 'float' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 1.11; + + {%- elseif info['type'] == 'boolean' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = true; + + {%- elseif info['type'] == 'date' or info['type'] == 'datetime' or info['type'] == 'datetimetz' or info['type'] == 'time' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = new \DateTime('now'); + + {%- elseif info['type'] == 'dateinterval' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = new \DateInterval('P2Y4DT6H8M'); + + {%- elseif info['type'] == 'array' or info['type'] == 'simple_array' or info['type'] == 'json_array' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = array('{{ field }}_1','{{ field }}_2'); + + {%- else %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 'unknown_field_value'; + + {%- endif -%} +{%- endfor %} + + +//add associations to mapping +{%- for key, assoc in assoc_mapping %} + {%- if (assoc['type'] == 4 or assoc['type'] == 2) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 2 == ManyToOne, type 4 == OneToMany #} + + ${{ entity_class|lower }}_object['{{ assoc['fieldName'] }}'] = $assoc_{{ key }}; + + {%- endif %} +{%- endfor %} + +self::$sample_object = ${{ entity_class|lower }}_object; +} + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig index 650afee..663215e 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig @@ -1,11 +1,12 @@ -public function testDelete() -{ - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testDelete() + { + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + } - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig index ef310e5..c0e77f6 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig @@ -1,11 +1,12 @@ -public function testGet() -{ - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testGet() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + } - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig index 0ce3920..0cb4ffa 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig @@ -1,5 +1,6 @@ -public function testGetOnDeletedItem() -{ - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); -} \ No newline at end of file + public function testGetOnDeletedItem() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + } + diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig index 1bbc042..088bf2c 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig @@ -1,15 +1,16 @@ -public function testGetAllWithContent() -{ - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testGetAllWithContent() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); + $this->assertTrue(count($obj) > 0, 'expected decoded response content to be an array with more then 0 items, got '.count($obj)); + $first = reset($obj); + $this->assertTrue(array_key_exists('id', $first), 'expected first array item to have a key id'); + self::$id = $first->id; + } - $obj = json_decode(self::$client->getResponse()->getContent()); - $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); - $this->assertTrue(count($obj) > 0, 'expected decoded response content to be an array with more then 0 items, got '.count($obj)); - $first = reset($obj); - $this->assertTrue(array_key_exists('id', $first), 'expected first array item to have a key id'); - self::$id = $first->id; -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig index f4e202c..b0514e6 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig @@ -1,8 +1,9 @@ -public function testGetAllWithoutContent() -{ - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testGetAllWithoutContent() + { + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + } - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig index 49b2436..1b67a6c 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig @@ -1,18 +1,16 @@ -public function testPatch() -{ - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testPatch() + { + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $json = json_encode(self::$sample_object); + $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + } - $obj = json_decode(self::$client->getResponse()->getContent()); - //test response content - //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); - //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig index 607b36b..291d8ff 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig @@ -1,13 +1,14 @@ -public function testPost() -{ - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after posting to api/post.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testPost() + { + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after posting to api/post.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $extra_help = 'If this test fails with a 500 status code, make sure the properties in the entity that should be required are annotated with @Symfony\Component\Validator\Constraints\NotBlank (or @Constraints\NotBlank and use Symfony\Component\Validator\Constraints;), remove this test if it doesn\'t apply to u.'; - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), "Expected a 400 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json without content, but got ".self::$client->getResponse()->getStatusCode().".\r\n".$extra_help); + $extra_help = 'If this test fails with a 500 status code, make sure the properties in the entity that should be required are annotated with @Symfony\Component\Validator\Constraints\NotBlank (or @Constraints\NotBlank and use Symfony\Component\Validator\Constraints;), remove this test if it doesn\'t apply to u.'; + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), "Expected a 400 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json without content, but got ".self::$client->getResponse()->getStatusCode().".\r\n".$extra_help."\r\n\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $json = json_encode(self::$sample_object); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + } - $json = json_encode(self::$sample_object); - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig index 437c3e2..707d27c 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig @@ -1,18 +1,16 @@ -public function testPut() -{ - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()); + public function testPut() + { + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $json = json_encode(self::$sample_object); + $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + + $obj = json_decode(self::$client->getResponse()->getContent()); + } - $obj = json_decode(self::$client->getResponse()->getContent()); - //test response content - //$this->assertEquals($put_name, $obj->name, 'name did not change after PUT'); - //$this->assertEquals($put_description, $obj->description, 'description did not change after PUT'); -} \ No newline at end of file diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig index 510067f..427f3c2 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig @@ -1,34 +1,206 @@ -/** @var Client */ -private static $client; - -private static $id; - -private static $sample_object; - -public function setUp() -{ - parent::setUp(); - self::$client = static::createClient(); - - ${{ entity|lower }}_object = array(); - {%- for field, info in fields if info['id'] is not defined or info['id'] == false %} - {%- if info['type'] == 'string' %} - ${{ entity|lower }}_object['{{ field }}'] = 'test_{{ field }}'; - {%- if info['type'] == 'text' %} - ${{ entity|lower }}_object['{{ field }}'] = 'test_{{ field }}_'.substr(str_shuffle(md5(time())),0,255); - {%- elseif info['type'] == 'integer' or info['type'] == 'smallint' or info['type'] == 'bigint' %} - ${{ entity|lower }}_object['{{ field }}'] = 1; - {%- elseif info['type'] == 'decimal' or info['type'] == 'float' %} - ${{ entity|lower }}_object['{{ field }}'] = 1.11; - {%- elseif info['type'] == 'boolean' %} - ${{ entity|lower }}_object['{{ field }}'] = true; - {%- elseif info['type'] == 'date' or info['type'] == 'datetime' or info['type'] == 'datetimetz' or info['type'] == 'time' %} - ${{ entity|lower }}_object['{{ field }}'] = new \DateTime('now'); - {# implement support for array types. #} - {%- else %} - {{ field }}.{{ info.type }} - {%- endif %} - {%- endfor %} - - self::$sample_object = ${{ entity|lower }}_object; -} \ No newline at end of file + /** @var Client */ + private static $client; + + private static $id; + + private static $sample_object; + + public function setUp() + { + parent::setUp(); + self::$client = static::createClient(); + //$em = self::$client->getContainer()->get('doctrine'); + + //create assocation fields (relations from this entity) + {%- for key, assoc in assoc_mapping %} + {%- if (assoc['type'] == 4 or assoc['type'] == 8) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 4 == OneToMany, type 8 == ManyToMany #} + + $assoc_{{ key }} = array(); + $field_{{ assoc['fieldName']|capitalize }} = new \{{ assoc['targetEntity'] }}; + //set fields of $field_{{ assoc['fieldName']|capitalize }}. + $assoc_{{ key }}[] = $field_{{ assoc['fieldName']|capitalize }}; + + + {%- elseif (assoc['type'] == 1 or assoc['type'] == 2) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 1 == OneToOne, type 2 == ManyToOne #} + + $assoc_{{ key }} = new \{{ assoc['targetEntity'] }}; + + + {%- endif %} + {%- endfor %} + + //create main object + ${{ entity_class|lower }}_object = array(); + {%- for field, info in fields if info['id'] is not defined or info['id'] == false -%} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {# Check basic constraints #} + {%- for constraint in entity_constraints[field] %} + {%- if 'NotBlankValidator' in constraint.validatedBy() %} + {# do nothing, value will be set on type checking #} + {%- elseif 'BlankValidator' in constraint.validatedBy() %} + {%- set test_data = null %} + {%- elseif 'NotNullValidator' in constraint.validatedBy() %} + {# do nothing #} + {%- elseif 'IsNullValidator' in constraint.validatedBy() %} + {%- set test_data = null %} + {%- endif %} + {%- endfor %} + {% endif %} + + {%- if info['type'] == 'string' %} + {%- set test_data = 'test_' ~ field %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {%- if 'NotBlankValidator' in constraint.validatedBy() %} + {%- set test_data = 'test_required_field_' ~ field %} + {%- elseif 'EmailValidator' in constraint.validatedBy() %} + {%- set test_data = field ~ '@domain.com' %} + {%- elseif 'UrlValidator' in constraint.validatedBy() %} + {%- set test_data = 'http://www.' ~ field ~ '.com' %} + {%- elseif 'IpValidator' in constraint.validatedBy() %} + {%- set test_data = '192.168.1.1' %} + {%- elseif 'RegexValidator' in constraint.validatedBy() %} + {%- set test_data = 'RegexValidator_test_data' %} + {%- elseif 'IsTrueValidator' in constraint.validatedBy() %} + {%- set test_data = '1' %} + {%- elseif 'IsFalseValidator' in constraint.validatedBy() %} + {%- set test_data = '0' %} + {%- elseif 'BicValidator' in constraint.validatedBy() %} + {%- set test_data = 'RABONL2U' %} + {%- elseif 'IbanValidator' in constraint.validatedBy() %} + {%- set test_data = 'NL10RABO1234556789' %} + {%- elseif 'CountryValidator' in constraint.validatedBy() %} + {%- set test_data = 'NL' %} + {%- elseif 'LocaleValidator' in constraint.validatedBy() %} + {%- set test_data = 'nl_NL' %} + {%- elseif 'LanguageValidator' in constraint.validatedBy() %} + {%- set test_data = 'nl' %} + {%- elseif 'CurrencyValidator' in constraint.validatedBy() %} + {%- set test_data = 'EUR' %} + {%- elseif 'LengthValidator' in constraint.validatedBy() %} + {% set random_number = random(constraint.max - constraint.min) + constraint.min %} + {% set test_data = '' %} + {% for 0..random_number %} + {% set test_data = test_data ~ random('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') %} + {% endfor %} + {%- elseif 'UuidValidator' in constraint.validatedBy() %} + {#- might want to check uuid versions and strict mode? #} + {%- set test_data = '123e4567-e89b-12d3-a456-426655440000' %} + {%- endif %} + {%- endfor %} + {%- endif %} + + ${{ entity_class|lower }}_object['{{ field }}'] = '{{ test_data }}'; + + {%- elseif info['type'] == 'text' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 'test_{{ field }}_'.substr(str_shuffle(md5(time())),0,255); + + {%- elseif info['type'] == 'integer' or info['type'] == 'smallint' or info['type'] == 'bigint' %} + {%- set test_data = 1 %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {%- if 'RangeValidator' in constraint.validatedBy() %} + {%- set test_data = random(constraint.max - constraint.min) + constraint.min %} + {%- elseif 'IsTrueValidator' in constraint.validatedBy() %} + {%- set test_data = 1 %} + {%- elseif 'IsFalseValidator' in constraint.validatedBy() %} + {%- set test_data = 0 %} + {%- endif %} + {%- endfor %} + {% endif %} + + ${{ entity_class|lower }}_object['{{ field }}'] = {{ test_data }}; + + {%- elseif info['type'] == 'decimal' or info['type'] == 'float' %} + {%- set test_data = 1.11 %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {%- if 'RangeValidator' in constraint.validatedBy() %} + {%- set test_data = random(constraint.max - constraint.min) + constraint.min %} + {%- elseif 'IsTrueValidator' in constraint.validatedBy() %} + {%- set test_data = 1 %} + {%- elseif 'IsFalseValidator' in constraint.validatedBy() %} + {%- set test_data = 0 %} + {%- endif %} + {%- endfor %} + {% endif %} + + ${{ entity_class|lower }}_object['{{ field }}'] = {{ test_data }}; + + {%- elseif info['type'] == 'boolean' %} + {%- set test_data = true %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {%- if 'RangeValidator' in constraint.validatedBy() %} + {%- set test_data = random(constraint.max - constraint.min) + constraint.min %} + {%- elseif 'IsFalseValidator' in constraint.validatedBy() %} + {%- set test_data = false %} + {%- endif %} + {%- endfor %} + {% endif %} + + ${{ entity_class|lower }}_object['{{ field }}'] = {{ test_data }}; + + {%- elseif info['type'] == 'date' or info['type'] == 'datetime' or info['type'] == 'datetimetz' or info['type'] == 'time' %} + {%- set test_data = 'now' %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {%- if 'RangeValidator' in constraint.validatedBy() %} + {%- set test_data = constraint.min %} + {%- endif %} + {%- endfor %} + {% endif %} + + ${{ entity_class|lower }}_object['{{ field }}'] = new \DateTime('{{ test_data }}'); + + {%- elseif info['type'] == 'dateinterval' %} + + ${{ entity_class|lower }}_object['{{ field }}'] = new \DateInterval('P2Y4DT6H8M'); + + {%- elseif info['type'] == 'array' or info['type'] == 'simple_array' or info['type'] == 'json_array' %} + {%- set plain_test_data = 'array(' %} + {%- set test_data = [ field ~ '_1' ] %} + {%- if entity_constraints[field] is defined and entity_constraints[field]|length > 0 %} + {%- for constraint in entity_constraints[field] %} + {# the following 2 validators are incompatible at the moment #} + {%- if 'ChoiceValidator' in constraint.validatedBy() %} + {% if constraint.choices is defined and constraint.choices|length > 0 %} + {%- set test_data = constraint.choices %} + {% else %} + {# check the callback here #} + {% endif %} + {%- elseif 'CountValidator' in constraint.validatedBy() %} + {% for i in 1..constraint.min%} + {{ test_data|merge([ field ~ '_' ~ i+1 ]) }} + {% endfor %} + {%- endif %} + {%- endfor %} + {%- endif %} + {%- for array_item in test_data %} + {%- set plain_test_data = plain_test_data ~ "'" ~ array_item ~ "'," %} + {%- endfor %} + {%- set plain_test_data = plain_test_data|trim(',') ~ ')'%} + + ${{ entity_class|lower }}_object['{{ field }}'] = {{ plain_test_data }}; + + {%- else %} + + ${{ entity_class|lower }}_object['{{ field }}'] = 'unknown_field_value'; + + {%- endif -%} + {%- endfor %} + + + //add associations to mapping + {%- for key, assoc in assoc_mapping %} + {%- if (assoc['type'] == 4 or assoc['type'] == 2) and assoc['targetEntity'] is defined and assoc['targetEntity'] is not null %} {# type 2 == ManyToOne, type 4 == OneToMany #} + + ${{ entity_class|lower }}_object['{{ assoc['fieldName'] }}'] = $assoc_{{ key }}; + + {%- endif %} + {%- endfor %} + + self::$sample_object = ${{ entity_class|lower }}_object; + } + From b08b1917b0d33d0fe301ae9b88f1b9467b5fb2ac Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Mon, 25 Apr 2016 11:23:09 +0200 Subject: [PATCH 38/46] implemented/updated creating form to be compliant with symfony 2.8+ as stated by @ilario-pierbattista --- .../Resources/skeleton/rest/handler/extras.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig index 3d92fe3..2972cd3 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/handler/extras.php.twig @@ -10,7 +10,7 @@ */ private function processForm({{ entity_class }} ${{ entity_class|lower }}, array $parameters, $method = "PUT") { - $form = $this->formFactory->create(new {{ entity_class }}Type(), ${{ entity_class|lower }}, array('method' => $method)); + $form = $this->formFactory->create(get_class(new {{ entity_class }}Type()), ${{ entity_class|lower }}, array('method' => $method)); $form->submit($parameters, 'PATCH' !== $method); if ($form->isValid()) { ${{ entity_class|lower }} = $form->getData(); From 2e5f84dccfc983a59e8ad1d8be69ed0494bef0f1 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Mon, 25 Apr 2016 11:52:14 +0200 Subject: [PATCH 39/46] hotfix for generating yml service when no yml exists --- .../Generator/DoctrineRESTGenerator.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php index c50be1b..f7f1a39 100644 --- a/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php +++ b/src/Voryx/RESTGeneratorBundle/Generator/DoctrineRESTGenerator.php @@ -362,6 +362,10 @@ private function handleServiceDeclarationAsYML($services, $newId, $handlerClass, { $yml_file = Yaml::parse(file_get_contents($services)); $params = $yml_file['parameters']; + if (!is_array($params)) + { + $params = array(); + } $yml_file['parameters'] = array_merge( $params, @@ -376,6 +380,10 @@ private function handleServiceDeclarationAsYML($services, $newId, $handlerClass, ) ); $yml_services = $yml_file['services']; + if (!is_array($yml_services)) + { + $yml_services = array(); + } $yml_file['services'] = array_merge( $yml_services, From be3e8d5ea0767bf1a6d344381124434ff1bcf4cc Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Mon, 25 Apr 2016 12:03:36 +0200 Subject: [PATCH 40/46] hotfix for failing test generation on Length Validator --- .../Resources/skeleton/rest/tests/oauth2/setup.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig index 427f3c2..176a5b2 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/setup.php.twig @@ -80,7 +80,7 @@ {%- elseif 'LengthValidator' in constraint.validatedBy() %} {% set random_number = random(constraint.max - constraint.min) + constraint.min %} {% set test_data = '' %} - {% for 0..random_number %} + {% for i in 1..random_number %} {% set test_data = test_data ~ random('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890') %} {% endfor %} {%- elseif 'UuidValidator' in constraint.validatedBy() %} From 26a350c14b9db70cd373bec76d2fb3e92b06f587 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 29 Apr 2016 11:16:00 +0200 Subject: [PATCH 41/46] Develop > Master (#3) * fixed typo * added creation of test base case * did this cause hard error? * fix for twig syntax error * fix for formatting of the included tests * fixed double if in oauth/setup.php.twig * object fields should not be put after eachother but under eachother * object fields should not be put after eachother but under eachother * added templates for no-authentication test * added friendly test mode function * added friendly test mode function * added friendly test mode function * added friendly test mode function * fixed typos in test cases * setup.php.twig format fixes * setup.php.twig format fixes * mode oauth base case command independent * added returning response content on error in tests * fixed defaults in interactive mode * removed non-working interactive mode for oauth username/password * fixed problems in oauth2 base testcase * fix for tests of oauth * added alpha version of ManyToOne support * added support for array and date internval types in testing * fixed typo in oauth setup for loop * added test version of service generation as YML format * added test version of service generation as YML format * fixed handlers so Entities in sub maps is supported * fixed handlers so Entities in sub maps is supported * fixed handlers so Entities in sub maps is supported * changed BaseTest location to be always in the root of Base * made tests independant of entity being in sub-map (AppBundle:User/User) * added usage of parameters in services.yml * made controller compatible with sub-entity (AppBundle:User\User) * fixed type in generation of serviceREST.yml file * fixed twig replace for controller actions * now using YmlLoader for loading yml instead of the XmlLoader * removed unused testing code and now adding services/params to service yml file instead of replacing them * added support of ManyToOne and OneToMany fields in oauth test case * added forgotten line closing ';' * made assoc field suffix with underscore for clarity * added a parameter overview to the readmes and fixed some layout issues in the setup for oauth test * added comments to setup * re-formatted the setup for testing and made it for both oauth and no-authentication * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * testing with Entity constraints, let's check the content * made bundle symfony dependant (added symfony to composer) and added testing version of checking constraints for fields in the test * made bundle symfony dependant (added symfony to composer) and added testing version of checking constraints for fields in the test * added constraint handling in setup template * added support for length constraint * and fixed a forgotten merge conflict * now creating the YAML reference for use of annotation routing if it doesn't already exist. * now creating the YAML reference for use of annotation routing if it doesn't already exist. * now creating the YAML reference for use of annotation routing if it doesn't already exist. * now creating the YAML reference for use of annotation routing if it doesn't already exist. --- .../Command/GenerateDoctrineRESTCommand.php | 60 +++++++++++++++++-- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php index 4a6c676..6517eac 100644 --- a/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php +++ b/src/Voryx/RESTGeneratorBundle/Command/GenerateDoctrineRESTCommand.php @@ -18,6 +18,8 @@ use Symfony\Component\HttpKernel\Bundle\BundleInterface; use Sensio\Bundle\GeneratorBundle\Command\Helper\QuestionHelper; use Symfony\Component\Validator\Mapping\ClassMetadata; +use Symfony\Component\Yaml\Exception\ParseException; +use Symfony\Component\Yaml\Yaml; use Voryx\RESTGeneratorBundle\Generator\DoctrineRESTGenerator; use Sensio\Bundle\GeneratorBundle\Command\Validators; use Voryx\RESTGeneratorBundle\Manipulator\RoutingManipulator; @@ -163,10 +165,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln('Generating the Form code: OK'); // create route - if ($format !== 'annotation') - { - $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix)); - } + $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format, $entity, $prefix)); + $questionHelper->writeGeneratorSummary($output, $errors); } @@ -293,7 +293,59 @@ protected function updateRouting(QuestionHelper $questionHelper, InputInterface $output->write('Importing the REST api routes: '); $this->getContainer()->get('filesystem')->mkdir($bundle->getPath() . '/Resources/config/'); + + if ($format === 'annotation') + { + $bundle_name = str_replace("Bundle", "", $bundle->getName()); + $route_name = strtolower($bundle_name); + $yml_file_location = $this->getContainer()->getParameter('kernel.root_dir') . '/config/routing.yml'; + try + { + $yml_file = Yaml::parse(file_get_contents($yml_file_location)); + } + catch(ParseException $pex) + { + return array( + 'Could not read yaml file '.$yml_file_location.'', + 'On line', + 'parsed line: '.$pex->getParsedLine() . ' and current line '. $pex->getLine(), + 'With snippet '.$pex->getSnippet(), + 'Exception message:', + ''.$pex->getMessage().'' + ); + } + $resource_location = sprintf('@%s/Controller/', $bundle->getName()); + + $bundle_routing = null; + if (array_key_exists($route_name, $yml_file)) + { + $bundle_routing = $yml_file[$route_name]; + } + + if (is_array($bundle_routing)) + { + if (array_key_exists('type',$bundle_routing) && array_key_exists('resource',$bundle_routing) && $bundle_routing['type'] === $format && $bundle_routing['resource'] === $resource_location) + { + //all is good + return array(); + } + } + + $bundle_routing = array( + 'resource' => $resource_location, + 'type' => $format + ); + + $yml_file[$route_name] = $bundle_routing; + + $yml_content = Yaml::dump($yml_file, 2); + file_put_contents($yml_file_location, $yml_content); + + return array(); + } + $routing = new RoutingManipulator($this->getContainer()->getParameter('kernel.root_dir') . '/config/routing.yml'); + try { $ret = $auto ? $routing->addResource($bundle->getName(), '/' . $prefix, $entity) : false; } catch (\RuntimeException $exc) { From 13e383ee797968955f18a2cf777a0086fe3fd920 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Thu, 12 May 2016 15:57:48 +0200 Subject: [PATCH 42/46] fixed routing issues for generation of sub-entities (#4) * fixed routing issues for generation of sub-entities --- .../Resources/skeleton/rest/controller.php.twig | 5 +++-- .../rest/tests/no-authentication/delete.php.twig | 4 ++-- .../rest/tests/no-authentication/get.php.twig | 4 ++-- .../tests/no-authentication/getAfterDelete.php.twig | 4 ++-- .../rest/tests/no-authentication/getAll.php.twig | 4 ++-- .../no-authentication/getAllWithoutContent.php.twig | 4 ++-- .../rest/tests/no-authentication/patch.php.twig | 4 ++-- .../rest/tests/no-authentication/post.php.twig | 4 ++-- .../rest/tests/no-authentication/put.php.twig | 4 ++-- .../skeleton/rest/tests/oauth2/delete.php.twig | 12 ++++++------ .../skeleton/rest/tests/oauth2/get.php.twig | 12 ++++++------ .../rest/tests/oauth2/getAfterDelete.php.twig | 4 ++-- .../skeleton/rest/tests/oauth2/getAll.php.twig | 8 ++++---- .../rest/tests/oauth2/getAllWithoutContent.php.twig | 8 ++++---- .../skeleton/rest/tests/oauth2/patch.php.twig | 12 ++++++------ .../skeleton/rest/tests/oauth2/post.php.twig | 10 +++++----- .../skeleton/rest/tests/oauth2/put.php.twig | 12 ++++++------ 17 files changed, 58 insertions(+), 57 deletions(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig index 3b7b258..57638d5 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/controller.php.twig @@ -24,6 +24,7 @@ use FOS\RestBundle\Controller\Annotations\Patch as RESTPatch; use FOS\RestBundle\Controller\Annotations\Post as RESTPost; use FOS\RestBundle\Controller\Annotations\Delete as RESTDelete; {%- endif %} + use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; @@ -38,12 +39,12 @@ use Nelmio\ApiDocBundle\Annotation\ApiDoc; /** {% block phpdoc_class_header %} - * {{ entity }} controller. + * {{ entity|replace({"\\":'/'}) }} controller. {% endblock phpdoc_class_header %} * @RouteResource("{{ entity }}") {% block phpdoc_class_annotations %} {% if 'annotation' == format %} - * @Route("/{{ route_prefix }}/{{ entity|lower }}") + * @Route("/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}") {% endif %} {% endblock phpdoc_class_annotations %} */ diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig index a445ad5..5dae00d 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/delete.php.twig @@ -1,6 +1,6 @@ public function testDelete() { - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig index 55f03d4..3b829be 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/get.php.twig @@ -1,6 +1,6 @@ public function testGet() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig index 135dfe9..a49ddb1 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAfterDelete.php.twig @@ -1,6 +1,6 @@ public function testGetOnDeletedItem() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig index c6ffdbc..c90c8d5 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAll.php.twig @@ -1,7 +1,7 @@ public function testGetAllWithContent() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json'); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json, got '.self::$client->getResponse()->getStatusCode()); $obj = json_decode(self::$client->getResponse()->getContent()); $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig index bf83e2d..c722193 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/getAllWithoutContent.php.twig @@ -1,6 +1,6 @@ public function testGetAllWithoutContent() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json'); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json, got '.self::$client->getResponse()->getStatusCode()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig index 83adfd3..cef4543 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/patch.php.twig @@ -2,8 +2,8 @@ { $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); $obj = json_decode(self::$client->getResponse()->getContent()); //test response content diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig index ec33a99..f87aa36 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/post.php.twig @@ -1,7 +1,7 @@ public function testPost() { $json = json_encode(self::$sample_object); - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json with content, but got ".self::$client->getResponse()->getStatusCode()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig index 9836c97..39a8c9b 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/no-authentication/put.php.twig @@ -2,8 +2,8 @@ { $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json', array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()); $obj = json_decode(self::$client->getResponse()->getContent()); //test response content diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig index 663215e..6142af9 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/delete.php.twig @@ -1,12 +1,12 @@ public function testDelete() { - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('DELETE', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting DELETE /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig index c0e77f6..ed5239f 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/get.php.twig @@ -1,12 +1,12 @@ public function testGet() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig index 0cb4ffa..81cce64 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAfterDelete.php.twig @@ -1,6 +1,6 @@ public function testGetOnDeletedItem() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig index 088bf2c..91eb314 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAll.php.twig @@ -1,10 +1,10 @@ public function testGetAllWithContent() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json?access_token='.self::$access_token); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $obj = json_decode(self::$client->getResponse()->getContent()); $this->assertTrue(is_array($obj), 'expected decoded response content to be array, got '.gettype($obj)); diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig index b0514e6..aaa5e31 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/getAllWithoutContent.php.twig @@ -1,9 +1,9 @@ public function testGetAllWithoutContent() { - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('GET', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json?access_token='.self::$access_token); + $this->assertEquals(204, self::$client->getResponse()->getStatusCode(), 'Expected a 204 response status after requesting /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig index 1b67a6c..4d58134 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/patch.php.twig @@ -1,15 +1,15 @@ public function testPatch() { - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json?access_token='.self::$access_token); + $this->assertEquals(404, self::$client->getResponse()->getStatusCode(), 'Expected a 404 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PATCH', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PATCH /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $obj = json_decode(self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig index 291d8ff..8c7b81b 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/post.php.twig @@ -1,14 +1,14 @@ public function testPost() { - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json'); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json'); $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after posting to api/post.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $extra_help = 'If this test fails with a 500 status code, make sure the properties in the entity that should be required are annotated with @Symfony\Component\Validator\Constraints\NotBlank (or @Constraints\NotBlank and use Symfony\Component\Validator\Constraints;), remove this test if it doesn\'t apply to u.'; - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token); - $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), "Expected a 400 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json without content, but got ".self::$client->getResponse()->getStatusCode().".\r\n".$extra_help."\r\n\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), "Expected a 400 response status after posting to /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json without content, but got ".self::$client->getResponse()->getStatusCode().".\r\n".$extra_help."\r\n\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $json = json_encode(self::$sample_object); - $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower }}.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower }}.json with content, but got ".self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('POST', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(201, self::$client->getResponse()->getStatusCode(), "Expected a 201 response status after posting to /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}.json with content, but got ".self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); } diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig index 707d27c..6534038 100644 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/tests/oauth2/put.php.twig @@ -1,15 +1,15 @@ public function testPut() { - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json'); - $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json'); + $this->assertEquals(401, self::$client->getResponse()->getStatusCode(), 'Expected a 401 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json without access token, but got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/999.json?access_token='.self::$access_token); - $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json?access_token='.self::$access_token); + $this->assertEquals(400, self::$client->getResponse()->getStatusCode(), 'Expected a 400 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/999.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $json = json_encode(self::$sample_object); - $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); - $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); + $crawler = self::$client->request('PUT', '/{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json?access_token='.self::$access_token, array(), array(), ['HTTP_CONTENT_TYPE' => 'application/json', 'CONTENT_TYPE' => 'application/json'], $json); + $this->assertEquals(200, self::$client->getResponse()->getStatusCode(), 'Expected a 200 response status after requesting PUT /{{ route_prefix }}/{{ entity|lower|replace({"\\":'/'}) }}/'.self::$id.'.json, got '.self::$client->getResponse()->getStatusCode()."\r\nResponse:\r\n".self::$client->getResponse()->getContent()); $obj = json_decode(self::$client->getResponse()->getContent()); } From 0132d8be0277b5ae7713aeb258a765add2bbb558 Mon Sep 17 00:00:00 2001 From: Maarten Sprakel Date: Fri, 13 May 2016 16:22:21 +0200 Subject: [PATCH 43/46] fixed minor typo in cgetAction api doc block --- .../Resources/skeleton/rest/actions/getAll.php.twig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig index 11115d0..813f72d 100755 --- a/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig +++ b/src/Voryx/RESTGeneratorBundle/Resources/skeleton/rest/actions/getAll.php.twig @@ -21,7 +21,7 @@ * @return Response * * @QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing notes.") - * @QueryParam(name="limit", requirements="\d+", default="20", description="How many notes to return.") + * @QueryParam(name="limit", requirements="\d+", default="20", description="How many {{ entity_class }} to return.") * @QueryParam(name="order_by", nullable=true, array=true, description="Order by fields. Must be an array ie. &order_by[name]=ASC&order_by[description]=DESC") * @QueryParam(name="filters", nullable=true, array=true, description="Filter by fields. Must be an array ie. &filters[id]=3") {% endblock phpdoc_method_header %} From efbcb07d06b6ea059348dd527b97c4efeb9fc850 Mon Sep 17 00:00:00 2001 From: Wojciech Zylinski Date: Wed, 6 Jul 2016 00:23:39 +0100 Subject: [PATCH 44/46] Fix to support Symfony >=2.8 --- README.Symfony3.md | 4 +++- README.md | 6 ++++-- .../Form/Type/VoryxEntityType.php | 14 +++----------- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/README.Symfony3.md b/README.Symfony3.md index b6cb203..717d1a8 100644 --- a/README.Symfony3.md +++ b/README.Symfony3.md @@ -170,10 +170,12 @@ $ curl -X DELETE http://localhost/app_dev.php/api/posts/1 If you want the form to be able to convert related entities into the correct entity id on POST, PUT or PATCH, use the voryx_entity form type ```php +use Voryx\RESTGeneratorBundle\Form\Type\VoryxEntityType; + #Form/PostType() ->add( - 'user', 'voryx_entity', array( + 'user', VoryxEntityType:class, array( 'class' => 'Acme\Bundle\Entity\User' ) ) diff --git a/README.md b/README.md index 3080cc9..4dcd25f 100644 --- a/README.md +++ b/README.md @@ -171,10 +171,12 @@ $ curl -X DELETE http://localhost/app_dev.php/api/posts/1 If you want the form to be able to convert related entities into the correct entity id on POST, PUT or PATCH, use the voryx_entity form type ```php -#Form/PostType() +use Voryx\RESTGeneratorBundle\Form\Type\VoryxEntityType; + +// ... ->add( - 'user', 'voryx_entity', array( + 'user', VoryxEntityType:class, array( 'class' => 'Acme\Bundle\Entity\User' ) ) diff --git a/src/Voryx/RESTGeneratorBundle/Form/Type/VoryxEntityType.php b/src/Voryx/RESTGeneratorBundle/Form/Type/VoryxEntityType.php index 5fe1011..908239c 100644 --- a/src/Voryx/RESTGeneratorBundle/Form/Type/VoryxEntityType.php +++ b/src/Voryx/RESTGeneratorBundle/Form/Type/VoryxEntityType.php @@ -6,7 +6,7 @@ use Doctrine\ORM\EntityManager; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\OptionsResolver\OptionsResolverInterface; +use Symfony\Component\OptionsResolver\OptionsResolver; use Voryx\RESTGeneratorBundle\Form\DataTransformer\ArrayToIdTransformer; /** @@ -44,7 +44,7 @@ public function buildForm(FormBuilderInterface $builder, array $options) /** * @param OptionsResolverInterface $resolver */ - public function setDefaultOptions(OptionsResolverInterface $resolver) + public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( array( @@ -58,14 +58,6 @@ public function setDefaultOptions(OptionsResolverInterface $resolver) */ public function getParent() { - return 'entity'; - } - - /** - * @return string - */ - public function getName() - { - return 'voryx_entity'; + return EntityType::class; } } From bbf1a4ed264bb111607bf5797592bcf8f760c60a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wesley=20Berr=C3=AAdo?= Date: Fri, 24 Feb 2017 11:03:02 -0400 Subject: [PATCH 45/46] Update README.md Explain resource parameter --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 3080cc9..9525318 100644 --- a/README.md +++ b/README.md @@ -121,14 +121,14 @@ possible values for all parameters | Parameter | Explanation | Values | | --------- | ----------- | ------- | -| entity | The entity for which the REST api should be generated | **AppBundle:Post**, **AppBundle:Blog\Post** -| document | Whether or not you want API's documented by Nelmio | Yes if present, else No -| overwrite | Whether or not you want to overwrite existing generated files | Yes if present, else No -| resource | - | Yes if present, else No -| route-prefix | The route to prefix the generated Controller with (default api) | Any string -| route-format | The format that routing is generated in (default yml) | **yml** or **annotation** -| service-format | The format that the service is generated in (default yml) | **yml** or **xml** -| test | The type of test that should be generated | **none**, **oauth** or **no-authentication** +| entity | The entity for which the REST api should be generated | **AppBundle:Post**, **AppBundle:Blog\Post** +| document | Whether or not you want API's documented by Nelmio | Yes if present, else No +| overwrite | Whether or not you want to overwrite existing generated files | Yes if present, else No +| resource | Whether or not you want the resource name encapsulating the response | Yes if present, else No +| route-prefix | The route to prefix the generated Controller with (default api) | Any string +| route-format | The format that routing is generated in (default yml) | **yml** or **annotation** +| service-format | The format that the service is generated in (default yml) | **yml** or **xml** +| test | The type of test that should be generated | **none**, **oauth** or **no-authentication** ### Using the API From 55260df8921d6ea967578d2dda0608bc0d064e6b Mon Sep 17 00:00:00 2001 From: sujayjaju Date: Wed, 5 Jul 2017 11:05:10 +0530 Subject: [PATCH 46/46] Updated Dependencies --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 23d622b..3d6c22e 100644 --- a/composer.json +++ b/composer.json @@ -15,12 +15,12 @@ } ], "require": { - "php": ">=5.3.0", + "php": ">=5.5.9", "symfony/symfony": ">=2.8", "sensio/generator-bundle": "~3.0", - "friendsofsymfony/rest-bundle": "~1.7", - "jms/serializer-bundle": "~1.1", - "nelmio/cors-bundle": "~1.4", + "friendsofsymfony/rest-bundle": "^2.2", + "jms/serializer-bundle": "^2.0", + "nelmio/cors-bundle": "~1.5", "nelmio/api-doc-bundle": "~2.7", "doctrine/orm": ">=2.0" },