Simplify class names and structure, new repositories

This commit is contained in:
Paweł Jędrzejewski 2012-11-12 21:18:25 +01:00
parent d061c51eab
commit 9b332c6fd3
21 changed files with 317 additions and 553 deletions

View file

@ -6,5 +6,7 @@ php:
before_script: composer install --dev before_script: composer install --dev
script: php bin/phpspec run
notifications: notifications:
email: travis-ci@sylius.org email: travis-ci@sylius.org

View file

@ -0,0 +1,107 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Controller;
use FOS\RestBundle\View\View;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* Request fetcher.
*
* This service knows how to fetch resource handling
* configuration from the request object.
*
* @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
*/
class RequestFetcher
{
protected $request;
protected $configuration;
public function __construct(Request $request)
{
$this->request = $request;
$this->configuration = $request->attributes->get('_sylius.resource', $this->getDefaultConfiguration());
}
public function getCriteria()
{
return $this->get('criteria', array());
}
public function getSorting()
{
return $this->get('sorting', array());
}
public function getRedirect()
{
return $this->get('redirect');
}
public function getFormType()
{
return $this->get('form');
}
public function getIdentifierCriteria()
{
return array(
$this->getIdentifierName() => $this->getIdentifierValue()
);
}
public function getIdentifierName()
{
return $this->get('identifier', 'id');
}
public function getIdentifierValue()
{
return $this->get($this->getIdentifierName(), 'id');
}
public function isCollectionPaginated()
{
return (Boolean) $this->get('paginate', true);
}
public function getPaginationMaxPerPage()
{
if (!$this->isCollectionPaginated()) {
throw new \BadMethodCallException('The current request configuration does not paginate the resources');
}
return $this->get('paginate', 10);
}
public function getTemplate()
{
return $this->get('template');
}
public function isHtmlRequest()
{
return 'html' === $this->request->getRequestFormat();
}
protected function get($name, $default = null)
{
return isset($this->configuration[$name]) ? $this->configuration[$name] : $default;
}
protected function getDefaultConfiguration()
{
return array();
}
}

View file

@ -16,9 +16,7 @@ use FOS\RestBundle\View\RouteRedirectView;
use FOS\RestBundle\View\View; use FOS\RestBundle\View\View;
use Sylius\Bundle\ResourceBundle\Model\ResourceInterface; use Sylius\Bundle\ResourceBundle\Model\ResourceInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/** /**
@ -26,7 +24,7 @@ use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
* *
* @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl> * @author Paweł Jędrzejewski <pjedrzejewski@sylius.pl>
*/ */
class ResourceController extends Controller implements ResourceControllerInterface class ResourceController extends Controller
{ {
protected $bundlePrefix; protected $bundlePrefix;
protected $resourceName; protected $resourceName;
@ -40,18 +38,20 @@ class ResourceController extends Controller implements ResourceControllerInterfa
} }
/** /**
* Get single resource. * Get single resource by its identifier.
*/ */
public function getAction(Request $request) public function getAction(Request $request)
{ {
$criteria = $this->getCriteria(); $criteria = $this
$criteria[$this->getIdentifierName()] = $this->getIdentifierValue(); ->getRequestFetcher()
->getIdentifierCriteria()
;
$resource = $this->findResourceOr404($criteria); $resource = $this->findResourceOr404($criteria);
$view = View::create() $view = View::create()
->setTemplate($this->getFullTemplateName('show.html')) ->setTemplate($this->getFullTemplateName('show.html'))
->setTemplateVar($this->getResourceName()) ->setTemplateVar($this->resourceName)
->setData($resource) ->setData($resource)
; ;
@ -63,49 +63,50 @@ class ResourceController extends Controller implements ResourceControllerInterfa
*/ */
public function getCollectionAction(Request $request) public function getCollectionAction(Request $request)
{ {
$criteria = $this->getCriteria(); $fetcher = $this->getRequestFetcher();
$sorting = $this->getSorting(); $pluralName = Pluralization::pluralize($this->resourceName);
$criteria = $fetcher->getCriteria();
$sorting = $fetcher->getSorting();
if ($this->isPaginated()) { $view = View::create()
->setTemplate($this->getFullTemplateName('list.html'))
;
if ($fetcher->isCollectionPaginated()) {
$paginator = $this $paginator = $this
->getRepository() ->getRepository()
->paginate($criteria, $sorting) ->createPaginator($criteria, $sorting)
; ;
$paginator->setCurrentPage($request->query->get('page', 1), true, true); $paginator->setCurrentPage($request->get('page', 1), true, true);
$paginator->setMaxPerPage($fetcher->getPaginationMaxPerPage());
$resources = $paginator->getCurrentPageResults(); $resources = $paginator->getCurrentPageResults();
$pluralName = Pluralization::pluralize($this->getResourceName()); $data = $fetcher->isHtmlRequest() ? array(
$data = $this->isHtmlRequest() ? array(
$pluralName => $resources, $pluralName => $resources,
'paginator' => $paginator 'paginator' => $paginator
) : $resources; ) : $resources;
} else { } else {
$view->setTemplateVar($pluralName);
$data = $this $data = $this
->getRepository() ->getRepository()
->getCollection($criteria, $sorting) ->findBy($criteria, $sorting, $fetcher->getLimit())
; ;
} }
$view = View::create() $view->setData($data);
->setTemplate($this->getFullTemplateName('list.html'))
->setData($data)
;
return $this->handleView($view); return $this->handleView($view);
} }
/** /**
* Create resource. * Create new resource or just display the form.
*
* @param Request $request
*
* @return Response
*/ */
public function createAction(Request $request) public function createAction(Request $request)
{ {
$resource = $this->createResource(); $resource = $this->create();
$form = $this->createResourceForm($resource); $form = $this->createResourceForm($resource);
if ($request->isMethod('POST') && $form->bind($request)->isValid()) { if ($request->isMethod('POST') && $form->bind($request)->isValid()) {
@ -121,8 +122,8 @@ class ResourceController extends Controller implements ResourceControllerInterfa
$view = View::create() $view = View::create()
->setTemplate($this->getFullTemplateName('create.html')) ->setTemplate($this->getFullTemplateName('create.html'))
->setData(array( ->setData(array(
$this->getResourceName() => $resource, $this->resourceName => $resource,
'form' => $form->createView() 'form' => $form->createView()
)) ))
; ;
@ -130,20 +131,20 @@ class ResourceController extends Controller implements ResourceControllerInterfa
} }
/** /**
* Update resource. * Display the form for editing or update the resource.
*
* @param Request $request
*
* @return Response
*/ */
public function updateAction(Request $request) public function updateAction(Request $request)
{ {
$resource = $this->findResourceOr404(array($this->getIdentifierName() => $this->getIdentifierValue())); $criteria = $this
->getRequestFetcher()
->getIdentifierCriteria()
;
$resource = $this->findResourceOr404($criteria);
$form = $this->createResourceForm($resource); $form = $this->createResourceForm($resource);
if ($request->isMethod('POST') && $form->bind($request)->isValid()) { if ($request->isMethod('POST') && $form->bind($request)->isValid()) {
$this->getManager()->persist($resource); $this->getManager()->persist($resource);
$this->setFlash('success', sprintf("%s has been updated", ucfirst($this->getResourceName())));
return $this->redirectToResource($resource); return $this->redirectToResource($resource);
} }
@ -164,76 +165,56 @@ class ResourceController extends Controller implements ResourceControllerInterfa
} }
/** /**
* Deletes resource. * Delete resource.
*
* @param Request $request
*
* @return Response
*/ */
public function deleteAction(Request $request) public function deleteAction(Request $request)
{ {
$resource = $this->findResourceOr404(array($this->getIdentifierName() => $this->getIdentifierValue())); $criteria = $this
->getRequestFetcher()
->getIdentifierCriteria()
;
$resource = $this->findResourceOr404($criteria);
$this->getManager()->remove($resource); $this->getManager()->remove($resource);
$this->setFlash('success', sprintf("%s has been deleted", ucfirst($this->getResourceName())));
return $this->redirectToResourceCollection(); return $this->redirectToResourceCollection();
} }
public function setFlash($name, $value) protected function getRequestFetcher()
{ {
if ($this->isHtmlRequest()) { return $this->get('sylius_resource.fetcher');
$this
->get('session')
->getFlashBag()
->set($name, $value)
;
}
} }
/** protected function create()
* Create new resource instance.
*/
protected function createResource()
{ {
return $this->getManager()->create(); return $this->getManager()->create();
} }
/**
* Create resource form.
*
* @param ResourceInterface $resource
*
* @return FormInterface
*/
protected function createResourceForm(ResourceInterface $resource = null) protected function createResourceForm(ResourceInterface $resource = null)
{ {
return $this->createForm($this->getResourceFormType(), $resource); return $this->createForm($this->getResourceFormType(), $resource);
} }
/** protected function getResourceFormType()
* Redirect to resource resource. {
* if (null !== $type = $this->requestFetcher->getFormType()) {
* @param ResourceInterface $resource return $type;
* }
* @return RouteRedirectView
*/ return sprintf('%s_%s', $this->bundlePrefix, $this->resourceName);
}
protected function redirectToResource(ResourceInterface $resource) protected function redirectToResource(ResourceInterface $resource)
{ {
$redirect = $this->getRequest()->attributes->get('_sylius.redirect'); $this->requestFetcher->getRedirect();
$route = $redirect ? $redirect : $this->getResourceRoute(); $route = $redirect ? $redirect : $this->getResourceRoute();
return $this->handleView(RouteRedirectView::create($route, array('id' => $resource->getId()))); return $this->handleView(RouteRedirectView::create($route, array('id' => $resource->getId())));
} }
/**
* Redirect to list of resourcees.
*
* @return RouteRedirectView
*/
protected function redirectToResourceCollection() protected function redirectToResourceCollection()
{ {
$redirect = $this->getRequest()->attributes->get('_sylius.redirect'); $this->requestFetcher->getRedirect();
$route = $redirect ? $redirect : $this->getResourceCollectionRoute(); $route = $redirect ? $redirect : $this->getResourceCollectionRoute();
return $this->handleView(RouteRedirectView::create($route)); return $this->handleView(RouteRedirectView::create($route));
@ -241,29 +222,19 @@ class ResourceController extends Controller implements ResourceControllerInterfa
protected function getResourceRoute() protected function getResourceRoute()
{ {
throw new \BadMethodCallException('You have to implement this method'); return sprintf('%s_%s', $this->bundlePrefix, $this->resourceName);
} }
protected function getResourceCollectionRoute() protected function getResourceCollectionRoute()
{ {
throw new \BadMethodCallException('You have to implement this method'); return sprintf('%s_%s', $this->bundlePrefix, Pluralization::pluralize($this->resourceName));
} }
/**
* Get resource manager.
*
* @return ResourceManagerInterface
*/
protected function getManager() protected function getManager()
{ {
return $this->get($this->getServiceName('manager')); return $this->get($this->getServiceName('manager'));
} }
/**
* Get resource repository.
*
* @return ResourceRepositoryInterface
*/
protected function getRepository() protected function getRepository()
{ {
return $this->get($this->getServiceName('repository')); return $this->get($this->getServiceName('repository'));
@ -271,57 +242,18 @@ class ResourceController extends Controller implements ResourceControllerInterfa
protected function getServiceName($name) protected function getServiceName($name)
{ {
return sprintf('%s.%s.%s', $this->getBundlePrefix(), $name, $this->getResourceName()); return sprintf('%s.%s.%s', $this->bundlePrefix, $name, $this->resourceName);
} }
/**
* Tries to find resource with given id.
* Throws special 404 exception when unsuccessful.
*
* @param array $criteria Criteria
*
* @return ResourceInterface
*
* @throws NotFoundHttpException
*/
protected function findResourceOr404(array $criteria) protected function findResourceOr404(array $criteria)
{ {
if (!$resource = $this->getRepository()->get($criteria)) { if (!$resource = $this->getRepository()->findOneBy($criteria)) {
throw new NotFoundHttpException('Requested resource does not exist'); throw new NotFoundHttpException('Requested resource does not exist');
} }
return $resource; return $resource;
} }
protected function getIdentifierName()
{
return $this->getRequest()->attributes->get('_sylius.identifier', 'id');
}
protected function getIdentifierValue()
{
if (null === $identifier = $this->getRequest()->get($this->getIdentifierName())) {
throw new NotFoundHttpException('No resource identifier supplied');
}
return $identifier;
}
protected function isPaginated()
{
return (Boolean) $this->getRequest()->attributes->get('_sylius.paginate', true);
}
protected function getCriteria()
{
return $this->getRequest()->get('_sylius.criteria', array());
}
protected function getSorting()
{
return $this->getRequest()->get('_sylius.sorting', array());
}
protected function renderResponse($templateName, array $parameters = array()) protected function renderResponse($templateName, array $parameters = array())
{ {
return $this->render($this->getFullTemplateName($templateName), $parameters); return $this->render($this->getFullTemplateName($templateName), $parameters);
@ -329,14 +261,12 @@ class ResourceController extends Controller implements ResourceControllerInterfa
protected function getFullTemplateName($name) protected function getFullTemplateName($name)
{ {
$template = $this->getRequest()->attributes->get('_sylius.template'); if (null !== $template = $this->getRequestFetcher()->getTemplate()) {
if (null !== $template) {
return $template; return $template;
} }
return sprintf('%s:%s.%s', return sprintf('%s:%s.%s',
$this->getTemplateNamespace(), $this->templateNamespace,
$name, $name,
$this->getEngine() $this->getEngine()
); );
@ -344,12 +274,7 @@ class ResourceController extends Controller implements ResourceControllerInterfa
protected function getEngine() protected function getEngine()
{ {
return $this->container->getParameter(sprintf('%s.engine', $this->getBundlePrefix())); return $this->container->getParameter(sprintf('%s.engine', $this->bundlePrefix));
}
protected function isHtmlRequest()
{
return 'html' === $this->getRequest()->getRequestFormat();
} }
protected function handleView(View $view) protected function handleView(View $view)
@ -357,23 +282,12 @@ class ResourceController extends Controller implements ResourceControllerInterfa
return $this->get('fos_rest.view_handler')->handle($view); return $this->get('fos_rest.view_handler')->handle($view);
} }
protected function getResourceFormType() protected function setFlash($type, $message)
{ {
return sprintf('%s_%s', $this->getBundlePrefix(), $this->getResourceName()); return $this
} ->get('session')
->getFlashBag()
protected function getTemplateNamespace() ->set($type, $message)
{ ;
return $this->templateNamespace;
}
protected function getBundlePrefix()
{
return $this->bundlePrefix;
}
protected function getResourceName()
{
return $this->resourceName;
} }
} }

View file

@ -1,28 +0,0 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* Resource controlller interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
interface ResourceControllerInterface
{
function getAction(Request $request);
function getCollectionAction(Request $request);
function createAction(Request $request);
function updateAction(Request $request);
function deleteAction(Request $request);
}

View file

@ -29,5 +29,6 @@ class SyliusResourceExtension extends Extension
public function load(array $config, ContainerBuilder $container) public function load(array $config, ContainerBuilder $container)
{ {
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/container')); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/container'));
$loader->load('services.xml');
} }
} }

View file

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Doctrine\ORM;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use Sylius\Bundle\ResourceBundle\Doctrine\ResourceRepository as BaseResourceRepository;
/**
* Doctrine ORM driver resource manager.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
class ResourceRepository extends BaseResourceRepository
{
/**
* {@inheritdoc}
*/
public function createPaginator(array $criteria = array(), array $sortBy = null)
{
$alias = $this->getAlias();
$queryBuilder = $this->objectRepository->createQueryBuilder($alias);
if (null !== $sortBy) {
foreach ($sortBy as $property => $order) {
$queryBuilder->orderBy($alias.$property, $order);
}
}
return new Pagerfanta(new DoctrineORMAdapter($queryBuilder));
}
protected function getAlias()
{
return 'r';
}
}

View file

@ -9,10 +9,10 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Sylius\Bundle\ResourceBundle\Manager\Doctrine; namespace Sylius\Bundle\ResourceBundle\Doctrine;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\ResourceBundle\Manager\ResourceManager; use Sylius\Bundle\ResourceBundle\Manager\ResourceManager as BaseResourceManager;
use Sylius\Bundle\ResourceBundle\Model\ResourceInterface; use Sylius\Bundle\ResourceBundle\Model\ResourceInterface;
/** /**
@ -20,25 +20,25 @@ use Sylius\Bundle\ResourceBundle\Model\ResourceInterface;
* *
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/ */
class DoctrineResourceManager extends ResourceManager implements DoctrineResourceManagerInterface class ResourceManager extends BaseResourceManager
{ {
protected $objectManager; protected $objectManager;
public function __construct(ObjectManager $objectManager, $class) public function __construct(ObjectManager $objectManager, $className)
{ {
$this->objectManager = $objectManager; $this->objectManager = $objectManager;
parent::__construct($class); parent::__construct($className);
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function persist(ResourceInterface $resource, $commit = true) public function persist(ResourceInterface $resource, $flush = true)
{ {
$this->objectManager->persist($resource); $this->objectManager->persist($resource);
if ($commit) { if ($flush) {
$this->objectManager->flush(); $this->objectManager->flush();
} }
} }
@ -46,17 +46,12 @@ class DoctrineResourceManager extends ResourceManager implements DoctrineResourc
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function remove(ResourceInterface $resource, $commit = true) public function remove(ResourceInterface $resource, $flush = true)
{ {
$this->objectManager->remove($resource); $this->objectManager->remove($resource);
if ($commit) { if ($flush) {
$this->objectManager->flush(); $this->objectManager->flush();
} }
} }
public function getObjectManager()
{
return $this->objectManager;
}
} }

View file

@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Doctrine;
use Doctrine\Common\Persistence\ObjectRepository;
use Sylius\Bundle\ResourceBundle\Repository\ResourceRepository as BaseResourceRepository;
/**
* Base Doctrine resource manager class.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
abstract class ResourceRepository extends BaseResourceRepository
{
protected $objectRepository;
public function __construct(ObjectRepository $objectRepository, $className)
{
$this->objectRepository = $objectRepository;
parent::__construct($className);
}
public function find($id)
{
return $this->objectRepository->find($id);
}
public function findAll()
{
return $this->objectRepository->findAll();
}
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
return $this->objectRepository->findBy($criteria, $orderBy, $limit, $offset);
}
public function findOneBy(array $criteria)
{
return $this->objectRepository->findBy($criteria);
}
}

View file

@ -1,24 +0,0 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Manager\Doctrine;
use Sylius\Bundle\ResourceBundle\Manager\ResourceManagerInterface;
/**
* Doctrine resource manager interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
interface DoctrineResourceManagerInterface extends ResourceManagerInterface
{
function getObjectManager();
}

View file

@ -18,22 +18,22 @@ namespace Sylius\Bundle\ResourceBundle\Manager;
*/ */
abstract class ResourceManager implements ResourceManagerInterface abstract class ResourceManager implements ResourceManagerInterface
{ {
protected $class; protected $className;
public function __construct($class) public function __construct($className)
{ {
$this->class = $class; $this->className = $className;
} }
public function create() public function create()
{ {
$class = $this->getClass(); $class = $this->getClassName();
return new $class; return new $class;
} }
public function getClass() public function getClassName()
{ {
return $this->class; return $this->className;
} }
} }

View file

@ -25,28 +25,28 @@ interface ResourceManagerInterface
* *
* @return ResourceInterface * @return ResourceInterface
*/ */
function create(); public function create();
/** /**
* Persist. * Persist.
* *
* @param ResourceInterface $resource * @param ResourceInterface $resource
* @param Boolean $commit * @param Boolean $flush
*/ */
function persist(ResourceInterface $resource, $commit = true); public function persist(ResourceInterface $resource, $flush = true);
/** /**
* Removes resource. * Removes resource.
* *
* @param ResourceInterface $resource * @param ResourceInterface $resource
* @param Boolean $commit * @param Boolean $flush
*/ */
function remove(ResourceInterface $resource, $commit = true); public function remove(ResourceInterface $resource, $flush = true);
/** /**
* Get resource class name. * Get resource class name.
* *
* @return string * @return string
*/ */
function getClass(); public function getClassName();
} }

View file

@ -23,5 +23,5 @@ interface ResourceInterface
* *
* @return mixed * @return mixed
*/ */
function getId(); public function getId();
} }

View file

@ -1,37 +0,0 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Repository\Doctrine;
use Doctrine\Common\Persistence\ObjectRepository;
use Sylius\Bundle\ResourceBundle\Repository\ResourceRepository;
/**
* Base Doctrine resource manager class.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
abstract class DoctrineResourceRepository extends ResourceRepository implements DoctrineResourceRepositoryInterface
{
protected $objectRepository;
public function __construct(ObjectRepository $objectRepository, $class)
{
$this->objectRepository = $objectRepository;
parent::__construct($class);
}
public function getObjectRepository()
{
return $this->objectRepository;
}
}

View file

@ -1,24 +0,0 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Repository\Doctrine;
use Sylius\Bundle\ResourceBundle\Repository\ResourceRepositoryInterface;
/**
* Doctrine resource manager interface.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
interface DoctrineResourceRepositoryInterface extends ResourceRepositoryInterface
{
function getObjectRepository();
}

View file

@ -1,122 +0,0 @@
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\ResourceBundle\Repository\Doctrine\ORM;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use Sylius\Bundle\ResourceBundle\Repository\Doctrine\DoctrineResourceRepository;
/**
* Doctrine ORM driver resource manager.
*
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/
class ResourceRepository extends DoctrineResourceRepository
{
/**
* {@inheritdoc}
*/
public function get(array $criteria)
{
return $this
->getQueryBuilder($criteria, array())
->getQuery()
->getOneOrNullResult()
;
}
/**
* {@inheritdoc}
*/
public function getCollection(array $criteria = array(), array $sorting = array(), $limit = null)
{
$queryBuilder = $this->getQueryBuilder($criteria, $sorting);
if (null !== $limit) {
$queryBuilder->setMaxResults($limit);
}
return $queryBuilder
->getQuery()
->execute()
;
}
/**
* {@inheritdoc}
*/
public function paginate(array $criteria = array(), array $sorting = array())
{
return new Pagerfanta(new DoctrineORMAdapter($this->getQueryBuilder($criteria, $sorting)));
}
protected function getQueryBuilder(array $criteria, array $sorting)
{
$queryBuilder = $this->getBasicQueryBuilder();
$this->filter($queryBuilder, $criteria);
$this->sort($queryBuilder, $sorting);
return $queryBuilder;
}
protected function filter(QueryBuilder $queryBuilder, array $criteria)
{
$reflectionClass = new \ReflectionClass($this->getClass());
$properties = array_keys($reflectionClass->getDefaultProperties());
$i = 0;
foreach ($criteria as $property => $condition) {
if (!is_array($condition)) {
$condition = array('=', $condition);
}
list($comparison, $value) = $condition;
if (in_array($property, $properties) && in_array($comparison, array('=', '!=', '>', '<', '>=', '<='))) {
$formula = sprintf("%s.%s %s :PARAM%d", $this->getAlias(), $property, $comparison, $i);
$queryBuilder
->andWhere($formula)
->setParameter('PARAM'.$i, $value)
;
$i++;
}
}
}
protected function sort(QueryBuilder $queryBuilder, array $sorting)
{
$acceptedOrders = array('asc', 'desc');
foreach ($sorting as $property => $order) {
if (in_array(strtolower($order), $acceptedOrders)) {
$queryBuilder->orderBy($this->getAlias().'.'.$property, $order);
}
}
}
protected function getBasicQueryBuilder()
{
return $this
->getObjectRepository()
->createQueryBuilder($this->getAlias())
;
}
protected function getAlias()
{
return 'r';
}
}

View file

@ -12,21 +12,21 @@
namespace Sylius\Bundle\ResourceBundle\Repository; namespace Sylius\Bundle\ResourceBundle\Repository;
/** /**
* Base resource repository class. * Base Doctrine resource manager class.
* *
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/ */
abstract class ResourceRepository implements ResourceRepositoryInterface abstract class ResourceRepository implements ResourceRepositoryInterface
{ {
protected $class; protected $className;
public function __construct($class) public function __construct($className)
{ {
$this->class = $class; $this->className = $className;
} }
public function getClass() public function getClassName()
{ {
return $this->class; return $this->className;
} }
} }

View file

@ -11,44 +11,19 @@
namespace Sylius\Bundle\ResourceBundle\Repository; namespace Sylius\Bundle\ResourceBundle\Repository;
use Sylius\Bundle\ResourceBundle\Model\ResourceInterface; use Doctrine\Common\Persistence\ObjectRepository;
/** /**
* Resource repository interface. * Resource repository interface.
* *
* @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
*/ */
interface ResourceRepositoryInterface interface ResourceRepositoryInterface extends ObjectRepository
{ {
/**
* Finds resource by identifier.
*
* @param array $criteria
*
* @return ResourceInterface
*/
function get(array $criteria);
/**
* Finds resource by criteria.
*
* @param array $criteria
*
* @return ResourceInterface
*/
function getCollection(array $criteria = array(), array $sorting = array(), $limit = null);
/** /**
* Creates a new Pagerfanta instance to paginate the resources. * Creates a new Pagerfanta instance to paginate the resources.
* *
* @return PagerfantaInterface * @return PagerfantaInterface
*/ */
function paginate(array $criteria = array(), array $sorting = array()); public function createPaginator(array $criteria = array(), array $sortBy = null);
/**
* Get resource class name.
*
* @return string
*/
function getClass();
} }

View file

@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
This file is part of the Sylius package.
(c) Paweł Jędrzejewski
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
-->
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd"
>
<services>
<service id="sylius_addressing.controller.backend.address" class="%sylius_addressing.controller.backend.address.class%">
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
</services>
</container>

View file

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
This file is part of the Sylius package.
(c) Paweł Jędrzejewski
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
-->
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd"
>
<parameters>
<parameter key="sylius_addressing.manager.address.class">Sylius\Bundle\AddressingBundle\Entity\AddressManager</parameter>
<parameter key="sylius_addressing.sorter.address.class">Sylius\Bundle\AddressingBundle\Sorting\ORM\AddressSorter</parameter>
</parameters>
<services>
<!-- managers... -->
<service id="sylius_addressing.manager.address" class="%sylius_addressing.manager.address.class%">
<argument type="service" id="doctrine.orm.default_entity_manager" />
<argument>%sylius_addressing.model.address.class%</argument>
</service>
<!-- sorters... -->
<service id="sylius_addressing.sorter.address" class="%sylius_addressing.sorter.address.class%">
<call method="setContainer">
<argument type="service" id="service_container" />
</call>
</service>
</services>
</container>

View file

@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
This file is part of the Sylius package.
(c) Paweł Jędrzejewski
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
-->
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd"
>
<services>
<service id="sylius_addressing.form.type.address" class="%sylius_addressing.form.type.address.class%">
<argument>%sylius_addressing.model.address.class%</argument>
<tag name="form.type" alias="sylius_addressing_address" />
</service>
</services>
</container>

View file

@ -14,12 +14,15 @@
<container xmlns="http://symfony.com/schema/dic/services" <container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services xsi:schemaLocation="http://symfony.com/schema/dic/services
http://symfony.com/schema/dic/services/services-1.0.xsd" http://symfony.com/schema/dic/services/services-1.0.xsd">
>
<parameters>
<parameter key="sylius_resource.fetcher.class">Sylius\Bundle\ResourceBundle\Controller\RequestFetcher</parameter>
</parameters>
<services> <services>
<service id="sylius_addressing.manipulator.address" class="%sylius_addressing.manipulator.address.class%"> <service id="sylius_resource.fetcher" class="%sylius_resource.fetcher.class%">
<argument type="service" id="sylius_addressing.manager.address" /> <argument type="service" id="request" strict="false" />
</service> </service>
</services> </services>