From 350be1bb443f900c8a1cc481a6f58c59ac487d22 Mon Sep 17 00:00:00 2001 From: Wim Vandersmissen Date: Wed, 18 Mar 2015 17:27:19 +0100 Subject: [PATCH] fix form submissions export code cleanup / refactor / add some tests scrutinizer --- .../AdminListBundle/AdminList/AdminList.php | 4 +- .../AbstractAdminListConfigurator.php | 92 ++++++++----- ...tractDoctrineDBALAdminListConfigurator.php | 22 ++-- ...stractDoctrineORMAdminListConfigurator.php | 20 +-- .../AdminListConfiguratorInterface.php | 7 - .../AdminListBundle/AdminList/ExportList.php | 9 +- .../AdminList/ExportableInterface.php | 14 +- .../Controller/AdminListController.php | 38 ++++-- .../AdminListBundle/Service/ExportService.php | 94 ++++++++++---- .../Tests/AdminList/AdminListFactoryTest.php | 14 +- .../Tests/AdminList/ExportListTest.php | 93 +++++++++++++ .../Controller/DefaultControllerTest.php | 17 --- .../Tests/Service/ExportServiceTest.php | 122 ++++++++++++++++++ .../FormPageAdminListConfigurator.php | 24 ++-- .../FormSubmissionExportListConfigurator.php | 81 +++++++++--- .../Controller/FormSubmissionsController.php | 54 ++++---- .../FormPageAdminListConfiguratorTest.php | 2 - 17 files changed, 533 insertions(+), 174 deletions(-) create mode 100644 src/Kunstmaan/AdminListBundle/Tests/AdminList/ExportListTest.php delete mode 100644 src/Kunstmaan/AdminListBundle/Tests/Controller/DefaultControllerTest.php create mode 100644 src/Kunstmaan/AdminListBundle/Tests/Service/ExportServiceTest.php diff --git a/src/Kunstmaan/AdminListBundle/AdminList/AdminList.php b/src/Kunstmaan/AdminListBundle/AdminList/AdminList.php index 4f9ae4783b..0d36a4272e 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/AdminList.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/AdminList.php @@ -97,9 +97,9 @@ public function getItems() * * @return \Iterator */ - public function getAllIterator() + public function getIterator() { - return $this->configurator->getAllIterator(); + return $this->configurator->getIterator(); } /** diff --git a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractAdminListConfigurator.php b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractAdminListConfigurator.php index 2b2e80f92b..09ae67e63a 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractAdminListConfigurator.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractAdminListConfigurator.php @@ -15,12 +15,13 @@ use Symfony\Component\HttpFoundation\Request; /** - * Abstract admin list configurator, this implements the most common functionality from the AdminListConfiguratorInterface + * Abstract admin list configurator, this implements the most common functionality from the + * AdminListConfiguratorInterface and ExportListConfiguratorInterface */ -abstract class AbstractAdminListConfigurator implements AdminListConfiguratorInterface +abstract class AbstractAdminListConfigurator implements AdminListConfiguratorInterface, ExportListConfiguratorInterface { - const SUFFIX_ADD = 'add'; - const SUFFIX_EDIT = 'edit'; + const SUFFIX_ADD = 'add'; + const SUFFIX_EDIT = 'edit'; const SUFFIX_EXPORT = 'export'; const SUFFIX_DELETE = 'delete'; @@ -139,16 +140,30 @@ public function buildListActions() { } + /** + * Configure the export fields + */ + public function buildExportFields() + { + } + + /** + * Build iterator (if needed) + */ + public function buildIterator() + { + } + /** * Reset all built members */ public function resetBuilds() { - $this->fields = array(); - $this->exportFields = array(); + $this->fields = array(); + $this->exportFields = array(); $this->filterBuilder = null; - $this->itemActions = array(); - $this->listActions = array(); + $this->itemActions = array(); + $this->listActions = array(); } /** @@ -162,15 +177,17 @@ public function getAddUrlFor(array $params = array()) { $params = array_merge($params, $this->getExtraParameters()); - $friendlyName = explode("\\", $this->getEntityName()); - $friendlyName = array_pop($friendlyName); - $re = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/'; - $a = preg_split($re, $friendlyName); + $friendlyName = explode("\\", $this->getEntityName()); + $friendlyName = array_pop($friendlyName); + $re = '/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/'; + $a = preg_split($re, $friendlyName); $superFriendlyName = implode(' ', $a); return array( - $superFriendlyName => array('path' => $this->getPathByConvention($this::SUFFIX_ADD), - 'params' => $params) + $superFriendlyName => array( + 'path' => $this->getPathByConvention($this::SUFFIX_ADD), + 'params' => $params + ) ); } @@ -184,7 +201,7 @@ public function getExportUrl() $params = $this->getExtraParameters(); return array( - 'path' => $this->getPathByConvention($this::SUFFIX_EXPORT), + 'path' => $this->getPathByConvention($this::SUFFIX_EXPORT), 'params' => array_merge(array('_format' => 'csv'), $params) ); } @@ -199,7 +216,7 @@ public function getIndexUrl() $params = $this->getExtraParameters(); return array( - 'path' => $this->getPathByConvention(), + 'path' => $this->getPathByConvention(), 'params' => $params ); } @@ -217,13 +234,14 @@ public function getAdminType($entity) return $this->type; } - if (method_exists($entity, "getAdminType")) { + if (method_exists($entity, 'getAdminType')) { return $entity->getAdminType(); } - throw new InvalidArgumentException("You need to implement the getAdminType method in " . get_class( - $this - ) . " or " . get_class($entity)); + throw new InvalidArgumentException( + 'You need to implement the getAdminType method in ' . + get_class($this) . ' or ' . get_class($entity) + ); } /** @@ -317,8 +335,12 @@ public function addExportField($name, $header, $template = null) * * @return AbstractAdminListConfigurator */ - public function addFilter($columnName, FilterTypeInterface $type = null, $filterName = null, array $options = array()) - { + public function addFilter( + $columnName, + FilterTypeInterface $type = null, + $filterName = null, + array $options = array() + ) { $this->getFilterBuilder()->add($columnName, $type, $filterName, $options); return $this; @@ -369,7 +391,8 @@ public function getExportFields() /** * @param string $label The label, only used when the template equals null - * @param callable $routeGenerator The generator used to generate the url of an item, when generating the item will be provided + * @param callable $routeGenerator The generator used to generate the url of an item, when generating the item will + * be provided * @param string $icon The icon, only used when the template equals null * @param string $template The template, when not specified the label is shown * @@ -663,15 +686,15 @@ public function setFilterBuilder(FilterBuilder $filterBuilder) */ public function bindRequest(Request $request) { - $query = $request->query; - $session = $request->getSession(); + $query = $request->query; + $session = $request->getSession(); $adminListName = 'listconfig_' . $request->get('_route'); - $this->page = $request->query->getInt('page', 1); + $this->page = $request->query->getInt('page', 1); // Allow alphanumeric, _ & . in order by parameter! - $this->orderBy = preg_replace('/[^[a-zA-Z0-9\_\.]]/', '', $request->query->get('orderBy', '')); - $this->orderDirection = $request->query->getAlpha('orderDirection', ''); + $this->orderBy = preg_replace('/[^[a-zA-Z0-9\_\.]]/', '', $request->query->get('orderBy', '')); + $this->orderDirection = $request->query->getAlpha('orderDirection', ''); // there is a session and the filter param is not set if ($session->has($adminListName) && !$query->has('filter')) { @@ -690,11 +713,14 @@ public function bindRequest(Request $request) } // save current parameters - $session->set($adminListName, array( - 'page' => $this->page, - 'orderBy' => $this->orderBy, - 'orderDirection' => $this->orderDirection, - )); + $session->set( + $adminListName, + array( + 'page' => $this->page, + 'orderBy' => $this->orderBy, + 'orderDirection' => $this->orderDirection, + ) + ); $this->getFilterBuilder()->bindRequest($request); diff --git a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineDBALAdminListConfigurator.php b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineDBALAdminListConfigurator.php index c19da06d40..8a8ca3589f 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineDBALAdminListConfigurator.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineDBALAdminListConfigurator.php @@ -2,13 +2,11 @@ namespace Kunstmaan\AdminListBundle\AdminList\Configurator; +use Doctrine\DBAL\Statement; use Traversable; - use Doctrine\DBAL\Connection; use Doctrine\DBAL\Query\QueryBuilder; - use Pagerfanta\Pagerfanta; - use Kunstmaan\AdminListBundle\AdminList\Configurator\AbstractAdminListConfigurator; use Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL\AbstractDBALFilterType; use Kunstmaan\AdminListBundle\Helper\DoctrineDBALAdapter; @@ -93,7 +91,11 @@ public function getDeleteUrlFor($item) public function getPagerfanta() { if (is_null($this->pagerfanta)) { - $adapter = new DoctrineDBALAdapter($this->getQueryBuilder(), $this->getCountField(), $this->getUseDistinctCount()); + $adapter = new DoctrineDBALAdapter( + $this->getQueryBuilder(), + $this->getCountField(), + $this->getUseDistinctCount() + ); $this->pagerfanta = new Pagerfanta($adapter); $this->pagerfanta->setCurrentPage($this->getPage()); $this->pagerfanta->setMaxPerPage($this->getLimit()); @@ -105,8 +107,11 @@ public function getPagerfanta() /** * @param array $params */ - public function adaptQueryBuilder(QueryBuilder $queryBuilder, /** @noinspection PhpUnusedParameterInspection */ array $params = array()) - { + public function adaptQueryBuilder( + QueryBuilder $queryBuilder, + /** @noinspection PhpUnusedParameterInspection */ + array $params = array() + ) { $queryBuilder->where('1=1'); } @@ -131,9 +136,9 @@ public function getItems() * * @return \Iterator */ - public function getAllIterator() + public function getIterator() { - /*@var Statement $statement*/ + /** @var Statement $statement*/ $statement = $this->getQueryBuilder()->execute(); return $statement; @@ -191,7 +196,6 @@ public function getCountField() return $this->countField; } - /** * When doing the count you can turn the distinct on or off. * diff --git a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineORMAdminListConfigurator.php b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineORMAdminListConfigurator.php index 31061fdc2c..33f9e863bf 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineORMAdminListConfigurator.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AbstractDoctrineORMAdminListConfigurator.php @@ -3,17 +3,14 @@ namespace Kunstmaan\AdminListBundle\AdminList\Configurator; use Traversable; - use Doctrine\ORM\EntityManager; use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\Query; - use Kunstmaan\AdminBundle\Helper\Security\Acl\AclHelper; use Kunstmaan\AdminBundle\Helper\Security\Acl\Permission\PermissionDefinition; use Kunstmaan\AdminListBundle\AdminList\FilterType\ORM\AbstractORMFilterType; use Kunstmaan\AdminListBundle\AdminList\Configurator\AbstractAdminListConfigurator; use Kunstmaan\AdminListBundle\AdminList\Filter; - use Pagerfanta\Pagerfanta; use Pagerfanta\Adapter\DoctrineORMAdapter; @@ -53,7 +50,7 @@ abstract class AbstractDoctrineORMAdminListConfigurator extends AbstractAdminLis */ public function __construct(EntityManager $em, AclHelper $aclHelper = null) { - $this->em = $em; + $this->em = $em; $this->aclHelper = $aclHelper; } @@ -70,7 +67,7 @@ public function getEditUrlFor($item) $params = array_merge($params, $this->getExtraParameters()); return array( - 'path' => $this->getPathByConvention($this::SUFFIX_EDIT), + 'path' => $this->getPathByConvention($this::SUFFIX_EDIT), 'params' => $params ); } @@ -88,7 +85,7 @@ public function getDeleteUrlFor($item) $params = array_merge($params, $this->getExtraParameters()); return array( - 'path' => $this->getPathByConvention($this::SUFFIX_DELETE), + 'path' => $this->getPathByConvention($this::SUFFIX_DELETE), 'params' => $params ); } @@ -99,7 +96,7 @@ public function getDeleteUrlFor($item) public function getPagerfanta() { if (is_null($this->pagerfanta)) { - $adapter = new DoctrineORMAdapter($this->getQuery()); + $adapter = new DoctrineORMAdapter($this->getQuery()); $this->pagerfanta = new Pagerfanta($adapter); $this->pagerfanta->setNormalizeOutOfRangePages(true); $this->pagerfanta->setCurrentPage($this->getPage()); @@ -138,7 +135,7 @@ public function getItems() * * @return \Iterator */ - public function getAllIterator() + public function getIterator() { return $this->getQuery()->iterate(); } @@ -190,6 +187,7 @@ protected function getQueryBuilder() $queryBuilder = $this->em ->getRepository($this->getRepositoryName()) ->createQueryBuilder('b'); + return $queryBuilder; } @@ -208,7 +206,7 @@ public function getPermissionDefinition() * * @param PermissionDefinition $permissionDef * - * @return AbstractAdminListConfigurator|AbstractDoctrineORMAdminListConfigurator + * @return AbstractDoctrineORMAdminListConfigurator */ public function setPermissionDefinition(PermissionDefinition $permissionDef) { @@ -219,10 +217,13 @@ public function setPermissionDefinition(PermissionDefinition $permissionDef) /** * @param EntityManager $em + * + * @return AbstractDoctrineORMAdminListConfigurator */ public function setEntityManager($em) { $this->em = $em; + return $this; } @@ -233,5 +234,4 @@ public function getEntityManager() { return $this->em; } - } diff --git a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AdminListConfiguratorInterface.php b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AdminListConfiguratorInterface.php index 94d1a41ef3..ac677bdeae 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AdminListConfiguratorInterface.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/Configurator/AdminListConfiguratorInterface.php @@ -221,13 +221,6 @@ public function getCount(); */ public function getItems(); - /** - * Return an iterator for all items that matches the current filtering - * - * @return \Iterator - */ - public function getAllIterator(); - /** * Bind request * diff --git a/src/Kunstmaan/AdminListBundle/AdminList/ExportList.php b/src/Kunstmaan/AdminListBundle/AdminList/ExportList.php index 4fb57eeaf9..6c8cfcf21c 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/ExportList.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/ExportList.php @@ -2,11 +2,16 @@ namespace Kunstmaan\AdminListBundle\AdminList; +use Kunstmaan\AdminListBundle\AdminList\Configurator\ExportListConfiguratorInterface; + class ExportList implements ExportableInterface { + /** + * @var ExportListConfiguratorInterface + */ private $configurator; - public function __construct($configurator) + public function __construct(ExportListConfiguratorInterface $configurator) { $this->configurator = $configurator; $this->configurator->buildExportFields(); @@ -18,7 +23,7 @@ public function getExportColumns() return $this->configurator->getExportFields(); } - public function getAllIterator() + public function getIterator() { return $this->configurator->getIterator(); } diff --git a/src/Kunstmaan/AdminListBundle/AdminList/ExportableInterface.php b/src/Kunstmaan/AdminListBundle/AdminList/ExportableInterface.php index 36015803ce..603a75458e 100644 --- a/src/Kunstmaan/AdminListBundle/AdminList/ExportableInterface.php +++ b/src/Kunstmaan/AdminListBundle/AdminList/ExportableInterface.php @@ -4,9 +4,21 @@ interface ExportableInterface { + /** + * @return array + */ public function getExportColumns(); - public function getAllIterator(); + /** + * @return \Iterator + */ + public function getIterator(); + /** + * @param array|object $item + * @param string $columnName + * + * @return string + */ public function getStringValue($item, $columnName); } diff --git a/src/Kunstmaan/AdminListBundle/Controller/AdminListController.php b/src/Kunstmaan/AdminListBundle/Controller/AdminListController.php index 8edd25e68b..28e4314358 100644 --- a/src/Kunstmaan/AdminListBundle/Controller/AdminListController.php +++ b/src/Kunstmaan/AdminListBundle/Controller/AdminListController.php @@ -31,6 +31,7 @@ protected function getEntityManager() * Shows the list of entities * * @param AbstractAdminListConfigurator $configurator + * @param null|Request $request * * @return array */ @@ -40,14 +41,14 @@ protected function doIndexAction(AbstractAdminListConfigurator $configurator, Re if (is_null($request)) { $request = $this->getRequest(); } - /* @var AdminList $adminlist */ - $adminlist = $this->get("kunstmaan_adminlist.factory")->createList($configurator, $em); - $adminlist->bindRequest($request); + /* @var AdminList $adminList */ + $adminList = $this->get("kunstmaan_adminlist.factory")->createList($configurator, $em); + $adminList->bindRequest($request); return new Response( $this->renderView( $configurator->getListTemplate(), - array('adminlist' => $adminlist, 'adminlistconfigurator' => $configurator, 'addparams' => array()) + array('adminlist' => $adminList, 'adminlistconfigurator' => $configurator, 'addparams' => array()) ) ); } @@ -57,6 +58,9 @@ protected function doIndexAction(AbstractAdminListConfigurator $configurator, Re * * @param AbstractAdminListConfigurator $configurator The adminlist configurator * @param string $_format The format to export to + * @param null|Request $request + * + * @throws AccessDeniedHttpException * * @return array */ @@ -67,14 +71,11 @@ protected function doExportAction(AbstractAdminListConfigurator $configurator, $ } $em = $this->getEntityManager(); - if (is_null($request)) { - $request = $this->getRequest(); - } - /* @var AdminList $adminlist */ - $adminlist = $this->get("kunstmaan_adminlist.factory")->createList($configurator, $em); - $adminlist->bindRequest($request); - return $this->get("kunstmaan_adminlist.service.export")->getDownloadableResponse($adminlist, $_format); + /* @var AdminList $adminList */ + $adminList = $this->get("kunstmaan_adminlist.factory")->createExportList($configurator, $em); + + return $this->get("kunstmaan_adminlist.service.export")->getDownloadableResponse($adminList, $_format); } /** @@ -82,6 +83,9 @@ protected function doExportAction(AbstractAdminListConfigurator $configurator, $ * * @param AbstractAdminListConfigurator $configurator The adminlist configurator * @param string $type The type to add + * @param null|Request $request + * + * @throws AccessDeniedHttpException * * @return array */ @@ -110,7 +114,7 @@ protected function doAddAction(AbstractAdminListConfigurator $configurator, $typ $helper = $configurator->decorateNewEntity($helper); $form = $this->createForm($configurator->getAdminType($helper), $helper); - if ('POST' == $request->getMethod()) { + if ($request->isMethod('POST')) { $form->submit($request); if ($form->isValid()) { $em->persist($helper); @@ -136,8 +140,11 @@ protected function doAddAction(AbstractAdminListConfigurator $configurator, $typ * * @param AbstractAdminListConfigurator $configurator The adminlist configurator * @param string $entityId The id of the entity that will be edited + * @param null|Request $request * * @throws NotFoundHttpException + * @throws AccessDeniedHttpException + * * @return Response */ protected function doEditAction(AbstractAdminListConfigurator $configurator, $entityId, Request $request = null) @@ -158,7 +165,7 @@ protected function doEditAction(AbstractAdminListConfigurator $configurator, $en $form = $this->createForm($configurator->getAdminType($helper), $helper); - if ('POST' == $request->getMethod()) { + if ($request->isMethod('POST')) { $form->submit($request); if ($form->isValid()) { $em->persist($helper); @@ -186,8 +193,11 @@ protected function doEditAction(AbstractAdminListConfigurator $configurator, $en * * @param AbstractAdminListConfigurator $configurator The adminlist configurator * @param integer $entityId The id to delete + * @param null|Request $request * * @throws NotFoundHttpException + * @throws AccessDeniedHttpException + * * @return Response */ protected function doDeleteAction(AbstractAdminListConfigurator $configurator, $entityId, Request $request = null) @@ -206,7 +216,7 @@ protected function doDeleteAction(AbstractAdminListConfigurator $configurator, $ } $indexUrl = $configurator->getIndexUrl(); - if ('POST' == $request->getMethod()) { + if ($request->isMethod('POST')) { $em->remove($helper); $em->flush(); } diff --git a/src/Kunstmaan/AdminListBundle/Service/ExportService.php b/src/Kunstmaan/AdminListBundle/Service/ExportService.php index dc2b25dce4..c63bbe7a8d 100644 --- a/src/Kunstmaan/AdminListBundle/Service/ExportService.php +++ b/src/Kunstmaan/AdminListBundle/Service/ExportService.php @@ -3,25 +3,35 @@ namespace Kunstmaan\AdminListBundle\Service; use Kunstmaan\AdminListBundle\AdminList\AdminList; +use Kunstmaan\AdminListBundle\AdminList\ExportableInterface; +use Kunstmaan\AdminListBundle\AdminList\ExportList; +use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; +use Symfony\Bundle\TwigBundle\TwigEngine; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; class ExportService { + /** + * @var EngineInterface + */ private $renderer; - const EXT_CSV = 'csv'; + const EXT_CSV = 'csv'; const EXT_EXCEL = 'xlsx'; + /** + * @return array + */ public static function getSupportedExtensions() { - $rfl = new \ReflectionClass(new self()); + $rfl = new \ReflectionClass(new self()); $data = $rfl->getConstants(); $extensions = array(); foreach ($data as $name => $ext) { if (strpos($name, 'EXT_') !== false) { - $key = ucfirst(strtolower(str_replace('EXT_', '', $name))); + $key = ucfirst(strtolower(str_replace('EXT_', '', $name))); $extensions[$key] = $ext; } } @@ -29,44 +39,68 @@ public static function getSupportedExtensions() return $extensions; } - public function getDownloadableResponse(AdminList $adminlist, $_format, $template = null) + /** + * @param ExportableInterface $adminList + * @param string $_format + * @param string|null $template + * + * @return Response|StreamedResponse + * + * @throws \Exception + */ + public function getDownloadableResponse(ExportableInterface $adminList, $_format, $template = null) { switch ($_format) { case self::EXT_EXCEL: - $writer = $this->createExcelSheet($adminlist); + $writer = $this->createExcelSheet($adminList); $response = $this->createResponseForExcel($writer); break; default: - $content = $this->createFromTemplate($adminlist, $_format, $template); + $content = $this->createFromTemplate($adminList, $_format, $template); $response = $this->createResponse($content, $_format); break; } $filename = sprintf('entries.%s', $_format); $response->headers->set('Content-Disposition', sprintf('attachment; filename=%s', $filename)); + return $response; } - public function createFromTemplate(AdminList $adminlist, $_format, $template = null){ - if($template === null) { + /** + * @param ExportableInterface $adminList + * @param string $_format + * @param string|null $template + * + * @return string + */ + public function createFromTemplate(ExportableInterface $adminList, $_format, $template = null) + { + if ($template === null) { $template = sprintf("KunstmaanAdminListBundle:Default:export.%s.twig", $_format); } - $allIterator = $adminlist->getAllIterator(); - return $this->renderer->render($template, array( - "iterator" => $allIterator, - "adminlist" => $adminlist, - "queryparams" => array() - )); + $iterator = $adminList->getIterator(); + + return $this->renderer->render( + $template, + array( + 'iterator' => $iterator, + 'adminlist' => $adminList, + 'queryparams' => array() + ) + ); } /** - * @param $adminlist + * @param ExportableInterface $adminList + * * @return \PHPExcel_Writer_Excel2007 + * * @throws \Exception * @throws \PHPExcel_Exception */ - public function createExcelSheet(AdminList $adminlist) + public function createExcelSheet(ExportableInterface $adminList) { $objPHPExcel = new \PHPExcel(); @@ -75,13 +109,13 @@ public function createExcelSheet(AdminList $adminlist) $number = 1; $row = array(); - foreach ($adminlist->getExportColumns() as $column) { + foreach ($adminList->getExportColumns() as $column) { $row[] = $column->getHeader(); } $objWorksheet->fromArray($row, null, 'A' . $number++); - $allIterator = $adminlist->getAllIterator(); - foreach($allIterator as $item) { + $iterator = $adminList->getIterator(); + foreach ($iterator as $item) { if (array_key_exists(0, $item)) { $itemObject = $item[0]; } else { @@ -89,14 +123,14 @@ public function createExcelSheet(AdminList $adminlist) } $row = array(); - foreach ($adminlist->getExportColumns() as $column) { - $data = $adminlist->getStringValue($itemObject, $column->getName()); + foreach ($adminList->getExportColumns() as $column) { + $data = $adminList->getStringValue($itemObject, $column->getName()); if (is_object($data)) { if (!$this->renderer->exists($column->getTemplate())) { throw new \Exception('No export template defined for ' . get_class($data)); } - $data = $this->renderer->render($column->getTemplate(), array("object" => $data)); + $data = $this->renderer->render($column->getTemplate(), array('object' => $data)); } $row[] = $data; @@ -109,6 +143,12 @@ public function createExcelSheet(AdminList $adminlist) return $objWriter; } + /** + * @param string $content + * @param string $_format + * + * @return Response + */ public function createResponse($content, $_format) { $response = new Response(); @@ -118,7 +158,12 @@ public function createResponse($content, $_format) return $response; } - public function createResponseForExcel($writer) + /** + * @param \PHPExcel_Writer_IWriter $writer + * + * @return StreamedResponse + */ + public function createResponseForExcel(\PHPExcel_Writer_IWriter $writer) { $response = new StreamedResponse( function () use ($writer) { @@ -131,6 +176,9 @@ function () use ($writer) { return $response; } + /** + * @param EngineInterface $renderer + */ public function setRenderer($renderer) { $this->renderer = $renderer; diff --git a/src/Kunstmaan/AdminListBundle/Tests/AdminList/AdminListFactoryTest.php b/src/Kunstmaan/AdminListBundle/Tests/AdminList/AdminListFactoryTest.php index addba67e61..13ad7ffd0d 100644 --- a/src/Kunstmaan/AdminListBundle/Tests/AdminList/AdminListFactoryTest.php +++ b/src/Kunstmaan/AdminListBundle/Tests/AdminList/AdminListFactoryTest.php @@ -2,8 +2,8 @@ namespace Kunstmaan\AdminListBundle\Tests\AdminList; use Kunstmaan\AdminListBundle\AdminList\AdminListFactory; - use Kunstmaan\AdminListBundle\AdminList\Configurator\AdminListConfiguratorInterface; +use Kunstmaan\AdminListBundle\AdminList\Configurator\ExportListConfiguratorInterface; /** * Generated by PHPUnit_SkeletonGenerator on 2012-09-26 at 13:21:32. @@ -43,4 +43,16 @@ public function testCreateList() $this->assertInstanceOf('Kunstmaan\AdminListBundle\AdminList\AdminList', $list); } + + /** + * @covers Kunstmaan\AdminListBundle\AdminList\AdminListFactory::createExportList + */ + public function testCreateExportList() + { + /* @var ExportListConfiguratorInterface $mockConfig */ + $mockConfig = $this->getMock('Kunstmaan\AdminListBundle\AdminList\Configurator\ExportListConfiguratorInterface'); + $list = $this->object->createExportList($mockConfig); + + $this->assertInstanceOf('Kunstmaan\AdminListBundle\AdminList\ExportList', $list); + } } diff --git a/src/Kunstmaan/AdminListBundle/Tests/AdminList/ExportListTest.php b/src/Kunstmaan/AdminListBundle/Tests/AdminList/ExportListTest.php new file mode 100644 index 0000000000..2611ad2ffe --- /dev/null +++ b/src/Kunstmaan/AdminListBundle/Tests/AdminList/ExportListTest.php @@ -0,0 +1,93 @@ +configurator = $this->getMock('Kunstmaan\AdminListBundle\AdminList\Configurator\ExportListConfiguratorInterface'); + $this->configurator + ->expects($this->once()) + ->method('buildExportFields'); + $this->configurator + ->expects($this->once()) + ->method('buildIterator'); + + $this->object = new ExportList($this->configurator); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + /** + * @covers Kunstmaan\AdminListBundle\AdminList\ExportList::__construct + * @covers Kunstmaan\AdminListBundle\AdminList\ExportList::getExportColumns + */ + public function testGetExportColumns() + { + $fields = array('field1', 'field2', 'field3'); + $this->configurator + ->expects($this->once()) + ->method('getExportFields') + ->willReturn($fields); + + $this->assertEquals($fields, $this->object->getExportColumns()); + } + + /** + * @covers Kunstmaan\AdminListBundle\AdminList\ExportList::getIterator + */ + public function testGetIterator() + { + $iterator = $this->getMock('\Iterator'); + $this->configurator + ->expects($this->once()) + ->method('getIterator') + ->willReturn($iterator); + + $this->assertInstanceOf('\Iterator', $iterator); + $this->assertEquals($iterator, $this->object->getIterator()); + } + + /** + * @covers Kunstmaan\AdminListBundle\AdminList\ExportList::getStringValue + */ + public function testGetStringValue() + { + $item = array('id' => 1); + + $this->configurator + ->expects($this->once()) + ->method('getStringValue') + ->with($item, 'id') + ->willReturn($item['id']); + + $this->assertEquals(1, $this->object->getStringValue($item, 'id')); + } +} diff --git a/src/Kunstmaan/AdminListBundle/Tests/Controller/DefaultControllerTest.php b/src/Kunstmaan/AdminListBundle/Tests/Controller/DefaultControllerTest.php deleted file mode 100644 index 61451010cf..0000000000 --- a/src/Kunstmaan/AdminListBundle/Tests/Controller/DefaultControllerTest.php +++ /dev/null @@ -1,17 +0,0 @@ -object = new ExportService; + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + /** + * @covers Kunstmaan\AdminListBundle\Service\ExportService::getSupportedExtensions + */ + public function testGetSupportedExtensions() + { + $extensions = ExportService::getSupportedExtensions(); + $this->assertEquals(array('Csv' => 'csv', 'Excel' => 'xlsx'), $extensions); + } + + /** + * @covers Kunstmaan\AdminListBundle\Service\ExportService::getDownloadableResponse + * @todo Implement testGetDownloadableResponse(). + */ + public function testGetDownloadableResponse() + { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @dataProvider createFromTemplateProvider + * + * @covers Kunstmaan\AdminListBundle\Service\ExportService::createFromTemplate + * @covers Kunstmaan\AdminListBundle\Service\ExportService::setRenderer + */ + public function testCreateFromTemplate($template = null) + { + $adminList = $this->getMock('Kunstmaan\AdminListBundle\AdminList\ExportableInterface'); + $iterator = $this->getMock('\Iterator'); + $adminList->expects($this->once())->method('getIterator')->willReturn($iterator); + + $templateName = is_null($template) ? 'KunstmaanAdminListBundle:Default:export.csv.twig' : $template; + $renderer = $this->getMock('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface'); + $renderer->expects($this->once()) + ->method('render') + ->with($templateName, + array( + 'iterator' => $iterator, + 'adminlist' => $adminList, + 'queryparams' => array() + ) + ); + + $this->object->setRenderer($renderer); + $this->object->createFromTemplate($adminList, ExportService::EXT_CSV, $template); + } + + public function createFromTemplateProvider() + { + return array( + array(null), + array('MyBundle:Default:export.csv.twig'), + ); + } + + /** + * @covers Kunstmaan\AdminListBundle\Service\ExportService::createExcelSheet + * @todo Implement testCreateExcelSheet(). + */ + public function testCreateExcelSheet() + { + // Remove the following lines when you implement this test. + $this->markTestIncomplete( + 'This test has not been implemented yet.' + ); + } + + /** + * @covers Kunstmaan\AdminListBundle\Service\ExportService::createResponse + */ + public function testCreateResponse() + { + $response = $this->object->createResponse('content', ExportService::EXT_CSV); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); + } + + /** + * @covers Kunstmaan\AdminListBundle\Service\ExportService::createResponseForExcel + */ + public function testCreateResponseForExcel() + { + $writer = $this->getMock('\PHPExcel_Writer_IWriter'); + $response = $this->object->createResponseForExcel($writer); + $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); + } +} diff --git a/src/Kunstmaan/FormBundle/AdminList/FormPageAdminListConfigurator.php b/src/Kunstmaan/FormBundle/AdminList/FormPageAdminListConfigurator.php index 997fd41f87..7c3c56d391 100644 --- a/src/Kunstmaan/FormBundle/AdminList/FormPageAdminListConfigurator.php +++ b/src/Kunstmaan/FormBundle/AdminList/FormPageAdminListConfigurator.php @@ -16,7 +16,6 @@ */ class FormPageAdminListConfigurator extends AbstractDoctrineORMAdminListConfigurator { - /** * @var string */ @@ -41,8 +40,8 @@ public function __construct(EntityManager $em, AclHelper $aclHelper, $permission public function buildFilters() { $builder = $this->getFilterBuilder(); - $builder->add('title', new StringFilterType("title"), "Title") - ->add('online', new BooleanFilterType('online'), 'Online'); + $builder->add('title', new StringFilterType('title'), 'Title') + ->add('online', new BooleanFilterType('online'), 'Online'); } /** @@ -50,14 +49,14 @@ public function buildFilters() */ public function buildFields() { - $this->addField("title", "Title", true) - ->addField("lang", "Language", true) - ->addField("url", "Form path", true); + $this->addField('title', 'Title', true) + ->addField('lang', 'Language', true) + ->addField('url', 'Form path', true); } - /* - * Add a view action. - */ + /** + * Add a view action. + */ public function buildItemActions() { $create_route = function (EntityInterface $item) { @@ -66,7 +65,11 @@ public function buildItemActions() 'params' => array('nodeTranslationId' => $item->getId()) ); }; - $ia = new \Kunstmaan\AdminListBundle\AdminList\ItemAction\SimpleItemAction($create_route, "eye-open", "View"); + $ia = new \Kunstmaan\AdminListBundle\AdminList\ItemAction\SimpleItemAction( + $create_route, + 'eye-open', + 'View' + ); $this->addItemAction($ia); } @@ -184,5 +187,4 @@ public function adaptQueryBuilder(QueryBuilder $queryBuilder) ) ->addOrderBy('n.sequenceNumber', 'DESC'); } - } diff --git a/src/Kunstmaan/FormBundle/AdminList/FormSubmissionExportListConfigurator.php b/src/Kunstmaan/FormBundle/AdminList/FormSubmissionExportListConfigurator.php index 6992740689..b6e06882af 100644 --- a/src/Kunstmaan/FormBundle/AdminList/FormSubmissionExportListConfigurator.php +++ b/src/Kunstmaan/FormBundle/AdminList/FormSubmissionExportListConfigurator.php @@ -3,43 +3,69 @@ namespace Kunstmaan\FormBundle\AdminList; use Doctrine\Common\Collections\ArrayCollection; -use Doctrine\ORM\EntityManager; +use Doctrine\ORM\EntityManagerInterface; use Kunstmaan\AdminListBundle\AdminList\Configurator\ExportListConfiguratorInterface; use Kunstmaan\AdminListBundle\AdminList\Field; +use Kunstmaan\FormBundle\Entity\FormSubmission; use Kunstmaan\NodeBundle\Entity\NodeTranslation; +use Symfony\Component\Translation\TranslatorInterface; /** - * Exportlist configuration to list all the form submissions for a given NodeTranslation + * Export list configuration to list all the form submissions for a given NodeTranslation */ class FormSubmissionExportListConfigurator implements ExportListConfiguratorInterface { - /** * @var NodeTranslation */ protected $nodeTranslation; + + /** + * @var EntityManagerInterface + */ protected $em; + + /** + * @var array + */ protected $exportFields; + + /** + * @var \Iterator + */ protected $iterator; + + /** + * @var TranslatorInterface + */ protected $translator; /** - * @param EntityManager $em The entity manager - * @param NodeTranslation $nodeTranslation The node translation - * @param Translatior $translator The translator service + * @param EntityManagerInterface $em The entity manager + * @param NodeTranslation $nodeTranslation The node translation + * @param TranslatorInterface $translator The translator service */ - public function __construct(EntityManager $em, $nodeTranslation, $translator) + public function __construct(EntityManagerInterface $em, $nodeTranslation, $translator) { $this->nodeTranslation = $nodeTranslation; - $this->em = $em; - $this->translator = $translator; + $this->em = $em; + $this->translator = $translator; } + /** + * @return array + */ public function getExportFields() { return $this->exportFields; } + /** + * @param string $name + * @param string $header + * + * @return FormSubmissionExportListConfigurator + */ public function addExportField($name, $header) { $this->exportFields[] = new Field($name, $header, false, null); @@ -47,18 +73,29 @@ public function addExportField($name, $header) return $this; } + /** + * Build export fields + */ public function buildExportFields() { - $this->addExportField('id', $this->translator->trans("Id")) - ->addExportField('date', $this->translator->trans("Date")) - ->addExportField('language', $this->translator->trans("Language")); + $this->addExportField('id', $this->translator->trans('Id')) + ->addExportField('date', $this->translator->trans('Date')) + ->addExportField('language', $this->translator->trans('Language')); } + /** + * @return \Iterator + */ public function getIterator() { return $this->iterator; } + /** + * Build iterator + * + * NOTE : The submission fields are added as export fields as well ... + */ public function buildIterator() { $qb = $this->em->createQueryBuilder(); @@ -71,16 +108,20 @@ public function buildIterator() ->setParameter('node', $this->nodeTranslation->getNode()->getId()) ->setParameter('lang', $this->nodeTranslation->getLang()) ->addOrderBy('fs.created', 'DESC'); - $iterableResult = $qb->getQuery()->iterate(); + $iterableResult = $qb->getQuery()->iterate(); $isHeaderWritten = false; - $iterator = new ArrayCollection(); + $collection = new ArrayCollection(); foreach ($iterableResult as $row) { - /* @var $submission FormSubmission */ + /* @var FormSubmission $submission */ $submission = $row[0]; // Write row data - $data = array('id' => $submission->getId(), 'date' => $submission->getCreated()->format('d/m/Y H:i:s'), 'language' => $submission->getLang()); + $data = array( + 'id' => $submission->getId(), + 'date' => $submission->getCreated()->format('d/m/Y H:i:s'), + 'language' => $submission->getLang() + ); foreach ($submission->getFields() as $field) { $header = $this->translator->trans($field->getLabel()); if (!$isHeaderWritten) { @@ -89,15 +130,15 @@ public function buildIterator() $data[$header] = $field->__toString(); } $isHeaderWritten = true; - $iterator->add(array($data)); + $collection->add(array($data)); } - $this->iterator = $iterator; + $this->iterator = $collection->getIterator(); } /** - * @param array|object $item The item - * @param string $columnName The column name + * @param array $item The item + * @param string $columnName The column name * * @return string */ diff --git a/src/Kunstmaan/FormBundle/Controller/FormSubmissionsController.php b/src/Kunstmaan/FormBundle/Controller/FormSubmissionsController.php index d15026a32b..b3791898d6 100644 --- a/src/Kunstmaan/FormBundle/Controller/FormSubmissionsController.php +++ b/src/Kunstmaan/FormBundle/Controller/FormSubmissionsController.php @@ -11,6 +11,7 @@ use Kunstmaan\FormBundle\AdminList\FormSubmissionExportListConfigurator; use Kunstmaan\NodeBundle\Entity\NodeTranslation; use Symfony\Bundle\FrameworkBundle\Controller\Controller; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; @@ -30,14 +31,17 @@ class FormSubmissionsController extends Controller * * @return array */ - public function indexAction() + public function indexAction(Request $request) { /* @var EntityManager $em */ - $em = $this->getDoctrine()->getManager(); - $request = $this->getRequest(); + $em = $this->getDoctrine()->getManager(); $aclHelper = $this->container->get('kunstmaan_admin.acl.helper'); - /* @var $adminList AdminList */ - $adminList = $this->get('kunstmaan_adminlist.factory')->createList(new FormPageAdminListConfigurator($em, $aclHelper, PermissionMap::PERMISSION_VIEW), $em); + + /* @var AdminList $adminList */ + $adminList = $this->get('kunstmaan_adminlist.factory')->createList( + new FormPageAdminListConfigurator($em, $aclHelper, PermissionMap::PERMISSION_VIEW), + $em + ); $adminList->bindRequest($request); return array('adminlist' => $adminList); @@ -48,19 +52,23 @@ public function indexAction() * * @param int $nodeTranslationId * - * @Route("/list/{nodeTranslationId}", requirements={"nodeTranslationId" = "\d+"}, name="KunstmaanFormBundle_formsubmissions_list") + * @Route("/list/{nodeTranslationId}", requirements={"nodeTranslationId" = "\d+"}, + * name="KunstmaanFormBundle_formsubmissions_list") * @Method({"GET", "POST"}) * @Template() * * @return array */ - public function listAction($nodeTranslationId) + public function listAction(Request $request, $nodeTranslationId) { - $em = $this->getDoctrine()->getManager(); - $request = $this->getRequest(); + $em = $this->getDoctrine()->getManager(); $nodeTranslation = $em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($nodeTranslationId); - /* @var $adminList AdminList */ - $adminList = $this->get("kunstmaan_adminlist.factory")->createList(new FormSubmissionAdminListConfigurator($em, $nodeTranslation), $em); + + /** @var AdminList $adminList */ + $adminList = $this->get('kunstmaan_adminlist.factory')->createList( + new FormSubmissionAdminListConfigurator($em, $nodeTranslation), + $em + ); $adminList->bindRequest($request); return array('nodetranslation' => $nodeTranslation, 'adminlist' => $adminList); @@ -70,9 +78,10 @@ public function listAction($nodeTranslationId) * The edit action will be used to edit a given submission * * @param int $nodeTranslationId The node translation id - * @param int $submissionId The submission id + * @param int $submissionId The submission id * - * @Route("/list/{nodeTranslationId}/{submissionId}", requirements={"nodeTranslationId" = "\d+", "submissionId" = "\d+"}, name="KunstmaanFormBundle_formsubmissions_list_edit") + * @Route("/list/{nodeTranslationId}/{submissionId}", requirements={"nodeTranslationId" = "\d+", "submissionId" = + * "\d+"}, name="KunstmaanFormBundle_formsubmissions_list_edit") * @Method({"GET", "POST"}) * @Template() * @@ -80,11 +89,11 @@ public function listAction($nodeTranslationId) */ public function editAction($nodeTranslationId, $submissionId) { - $em = $this->getDoctrine()->getManager(); + $em = $this->getDoctrine()->getManager(); $nodeTranslation = $em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($nodeTranslationId); - $formSubmission = $em->getRepository('KunstmaanFormBundle:FormSubmission')->find($submissionId); + $formSubmission = $em->getRepository('KunstmaanFormBundle:FormSubmission')->find($submissionId); - return array('nodetranslation' => $nodeTranslation, 'formsubmission' => $formSubmission,); + return array('nodetranslation' => $nodeTranslation, 'formsubmission' => $formSubmission); } /** @@ -92,7 +101,8 @@ public function editAction($nodeTranslationId, $submissionId) * * @param int $nodeTranslationId * - * @Route("/export/{nodeTranslationId}.{_format}", requirements={"nodeTranslationId" = "\d+","_format" = "csv|xlsx"}, name="KunstmaanFormBundle_formsubmissions_export") + * @Route("/export/{nodeTranslationId}.{_format}", requirements={"nodeTranslationId" = "\d+","_format" = + * "csv|xlsx"}, name="KunstmaanFormBundle_formsubmissions_export") * @Method({"GET"}) * * @return Response @@ -100,14 +110,14 @@ public function editAction($nodeTranslationId, $submissionId) public function exportAction($nodeTranslationId, $_format) { $em = $this->getDoctrine()->getManager(); - /* @var $nodeTranslation NodeTranslation */ + /** @var NodeTranslation $nodeTranslation */ $nodeTranslation = $em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($nodeTranslationId); - $translator = $this->get('translator'); + $translator = $this->get('translator'); - /* @var ExportList $exportlist */ + /** @var ExportList $exportList */ $configurator = new FormSubmissionExportListConfigurator($em, $nodeTranslation, $translator); - $exportlist = $this->get("kunstmaan_adminlist.factory")->createExportList($configurator); + $exportList = $this->get('kunstmaan_adminlist.factory')->createExportList($configurator); - return $this->get("kunstmaan_adminlist.service.export")->getDownloadableResponse($exportlist, $_format); + return $this->get('kunstmaan_adminlist.service.export')->getDownloadableResponse($exportList, $_format); } } diff --git a/src/Kunstmaan/FormBundle/Tests/AdminList/FormPageAdminListConfiguratorTest.php b/src/Kunstmaan/FormBundle/Tests/AdminList/FormPageAdminListConfiguratorTest.php index 5d65d5b0aa..9fb05e22bb 100644 --- a/src/Kunstmaan/FormBundle/Tests/AdminList/FormPageAdminListConfiguratorTest.php +++ b/src/Kunstmaan/FormBundle/Tests/AdminList/FormPageAdminListConfiguratorTest.php @@ -5,7 +5,6 @@ use Kunstmaan\FormBundle\AdminList\FormPageAdminListConfigurator; use Kunstmaan\NodeBundle\Tests\Stubs\TestRepository; use Kunstmaan\FormBundle\Tests\Stubs\TestConfiguration; - use Doctrine\ORM\QueryBuilder; /** @@ -90,5 +89,4 @@ public function testAdaptQueryBuilder() /* @var $queryBuilder QueryBuilder */ $this->object->adaptQueryBuilder($queryBuilder); } - }