doctrine override default finder methods for all entity - symfony

There is a way to override the default finder methods for all entity repository
for exemple this is the default methode findBy in Doctrine\ORM\EntityRepository
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
$persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
return $persister->loadAll($criteria, $orderBy, $limit, $offset);
}
But my need is something like this
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
$persister = $this->_em->getUnitOfWork()->getEntityPersister($this->_entityName);
$criteria['foo'] = 'bar';
return $persister->loadAll($criteria, $orderBy, $limit, $offset);
}
I want create a service to override this method by modifying the criteria array and adding some custom criteria attribute if needed.
I know that I can override the repository for every entity but my project has been enlarged and for now I want a practical solution to avoid changing in all entity repository.

You can make a class that extends ServiceEntityRepository and in that class define all the classes you wish to override. Then finally you will need to update all your repositories to extend this new class instead of the ServiceEntityRepository.

You shouldn't do it this way. Embrace Doctrine Filters. Using one you can introduce any kind of logic globally to all of your queries.

Refer to the answer of #emix this is more detailed solution
Now let's create the annotation. This will be added to the class to indicate which fields that will be filtered by doctrine.
/**
* #Annotation
* #Target("CLASS")
*/
final class CenterSelector
{
public $centerFieldName;
}
And use it in your class
/**
* #CenterSelector(centerFieldName="you-name-field")
*/
class CommercialPiece{
protected $you-name-field;
}
Create your Filter class that extends from SQLFilter
class CenterFilter extends SQLFilter
{
protected $reader;
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if (empty($this->reader)) {
return '';
}
// The Doctrine filter is called for any query on any entity
// Check if the current entity is (marked with an annotation)
$centerSelector = $this->reader->getClassAnnotation(
$targetEntity->getReflectionClass(),
CenterSelector::class
);
if (!$centerSelector) {
return '';
}
// FieldName parameter in annotation
$fieldName = $centerSelector->centerFieldName;
try {
$mySelector= $this->getParameter('my-selector');
} catch (\InvalidArgumentException $e) {
// No my-selector has been defined
return '';
}
if (empty($fieldName) || empty($mySelector)) {
return '';
} else{
var_dump($mySelector);
// Add the Where clause in the request
$query = sprintf('%s.%s = %s', $targetTableAlias, $fieldName, $mySelector);
}
return $query;
}
public function setAnnotationReader(Reader $reader)
{
$this->reader = $reader;
}
}
And I created a listener onKernelRequest
public function __construct(
ObjectManager $em,
SessionInterface $session,
Reader $reader)
{
$this->em = $em;
$this->session = $session;
$this->reader = $reader;
}
public function onKernelRequest(GetResponseEvent $event)
{
$globalSelector = $this->session->get('my-global-selector');
$filter = $this->em->getFilters()->enable('center_filter');
$filter->setParameter('my-selector', $globalSelector );
$filter->setAnnotationReader($this->reader);
}
Finally don't forget to add this in config.yml
orm:
entity_managers:
default:
auto_mapping: true
filters:
center_filter:
class: your-name-space\Filter\CenterFilter
enabled: true

Related

How to toggle Symfony's php-translation/symfony-bundle EditInPlace

I followed this documentation for Edit In Place, and setup the Activator, and it works!
However, I will be using this on the production site and allowing access via a ROLE_TRANSLATOR Authorization. This is also working, but I don't want the web interface always "on"
How would I go about enabling it via some sort of link or toggle?
My thoughts, it would be simple to just add a URL parameter, like ?trans=yes and then in the activator;
return ($this->authorizationChecker->isGranted(['ROLE_TRANSLATOR']) && $_GET['trans'] == 'yes');
Obviously, $_GET would not work, I didn't even try.
How do I generate a link to simply reload THIS page with the extra URL parameter
How do I check for that parameter within the "Activator"
or, is there a better way?
The "proper" way to do this, as I have discovered more about "services" is to do the logic diectly in the RoleActivator.php file.
referencing documentation for How to Inject Variables into all Templates via Referencing Services I came up with the following solution;
src/Security/RoleActivator.php
<?php
namespace App\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Translation\Bundle\EditInPlace\ActivatorInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class RoleActivator implements ActivatorInterface
{
/**
* #var AuthorizationCheckerInterface
*/
private $authorizationChecker;
/**
* #var TranslatorInterface
*/
private $translate;
/**
* #var RequestStack
*/
private $request;
private $params;
private $path;
private $flag = null;
public function __construct(AuthorizationCheckerInterface $authorizationChecker, TranslatorInterface $translate, RequestStack $request)
{
$this->authorizationChecker = $authorizationChecker;
$this->translate = $translate;
$this->request = $request;
}
/**
* {#inheritdoc}
*/
public function checkRequest(Request $request = null)
{
if ($this->flag === null) { $this->setFlag($request); }
try {
return ($this->authorizationChecker->isGranted(['ROLE_TRANSLATOR']) && $this->flag);
} catch (AuthenticationCredentialsNotFoundException $e) {
return false;
}
}
public function getText()
{
if ($this->flag === null) { $this->setFlag(); }
return ($this->flag) ? 'linkText.translate.finished' : 'linkText.translate.start'; // Translation key's returned
}
public function getHref()
{
if ($this->flag === null) { $this->setFlag(); }
$params = $this->params;
if ($this->flag) {
unset($params['trans']);
} else {
$params['trans'] = 'do';
}
$queryString = '';
if (!empty($params)) {
$queryString = '?';
foreach ($params as $key => $value) {
$queryString.= $key.'='.$value.'&';
}
$queryString = rtrim($queryString, '&');
}
return $this->path.$queryString;
}
private function setFlag(Request $request = null)
{
if ($request === null) {
$request = $this->request->getCurrentRequest();
}
$this->flag = $request->query->has('trans');
$this->params = $request->query->all();
$this->path = $request->getPathInfo();
}
}
config\packages\twig.yaml
twig:
# ...
globals:
EditInPlace: '#EditInPlace_RoleActivator'
config\services.yaml
services:
# ...
EditInPlace_RoleActivator:
class: App\Security\RoleActivator
arguments: ["#security.authorization_checker"]
So What I added over and above the php-translation example is the getText and getHref methods and corresponding private variables being set in the checkRequest and read there after.
Now in my twig template (in the header) I just use
{% if is_granted('ROLE_TRANSLATOR') %}
{{ EditInPlace.Text }}
{% endif %}
Add the new keys to the translation files and your done. the trans=do query parameter is toggled on and off with each click of the link. You could even add toggling styles with a class name, just copy the getText method to something like getClass and return string a or b with the Ternary.

Symfony2: Get controller as a service classname from service name or Route object

I have some Controllers defined as services and I need to have the classname of my controllers from the route name.
For non-service controllers I can get the route collection with the router service:
$route = $this->router->getRouteCollection()->get($routeName);
//Retrieve an object like that:
Route {
-path: "/admin/dashboard"
-host: ""
-schemes: []
-methods: []
-defaults: array:1 [
"_controller" => "AppBundle\Controller\Admin\AdminController::dashboardAction"
]
-requirements: []
-options: array:1 []
-compiled: null
-condition: ""
}
I can access the controller classname with $route["defaults"]["_controller"] so this is fine.
The issue is with my controllers as services, the _controller attribute is the name of the service, not the Controller class (like app.controller.admin.user:listAction) I have the name of the service but I need to have the classname (AppBundle\Controller\Admin\UserController)
The only solution I came up with is to get the service from the Container and use get_class() on the service but it will have a huge performance impact only to retrieve the class of the controller/service.
Is there any other solution ?
as suggested in https://github.com/FriendsOfSymfony/FOSUserBundle/issues/2751, I implemented a cached map to get route-names resolved to controllers classes and methods.
<?php
// src/Cache/RouteClassMapWarmer.php
namespace App\Cache;
use Symfony\Component\Cache\Simple\PhpFilesCache;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\Routing\RouterInterface;
class RouteClassMapWarmer implements CacheWarmerInterface
{
/** #var ContainerInterface */
protected $container;
/** #var RouterInterface */
protected $router;
public function __construct(ContainerInterface $container, RouterInterface $router)
{
$this->container = $container;
$this->router = $router;
}
public function warmUp($cacheDirectory)
{
$cache = new PhpFilesCache('route_class_map', 0, $cacheDirectory);
$controllers = [];
foreach ($this->router->getRouteCollection() as $routeName => $route) {
$controller = $route->getDefault('_controller');
if (false === strpos($controller, '::')) {
list($controllerClass, $controllerMethod) = explode(':', $controller, 2);
// service_id gets resolved here
$controllerClass = get_class($this->container->get($controllerClass));
}
else {
list($controllerClass, $controllerMethod) = explode('::', $controller, 2);
}
$controllers[$routeName] = ['class' => $controllerClass, 'method' => $controllerMethod];
}
unset($controller);
unset($route);
$cache->set('route_class_map', $controllers);
}
public function isOptional()
{
return false;
}
}
And in my RouteHelper, the implementation reading this looks like this
$cache = new PhpFilesCache('route_class_map', 0, $this->cacheDirectory);
$controllers = $cache->get('route_class_map');
if (!isset($controllers[$routeName])) {
throw new CacheException('No entry for route ' . $routeName . ' forund in RouteClassMap cache, please warmup first.');
}
if (null !== $securityAnnotation = $this->annotationReader->getMethodAnnotation((new \ReflectionClass($controllers[$routeName]['class']))->getMethod($controllers[$routeName]['method']), Security::class))
{
return $this->securityExpressionHelper->evaluate($securityAnnotation->getExpression(), ['myParameter' => $myParameter]);
}
This should be much faster than getting the routeCollection and resolve the service_id:method notated _controller-properties against the container on every request.

Extend Doctrine EntityRepository

I have written a class BasicRepository in order to use it instead of the EntityRepository to add some basic modification like remove all deleted-flaged items.
<?php
namespace AppBundle\Repository;
use AppBundle\DataFixtures\ORM\LoadEventPrioData;
use AppBundle\Entity\Location;
use Doctrine\ORM\EntityRepository;
class BasicRepository extends EntityRepository
{
public function createQueryBuilder($alias, $indexBy = null)
{
$query = parent::createQueryBuilder($alias);
dump(parent::getClassName());
dump($this->getClassName());
if (property_exists($this->getClassName(), 'isDeleted')) {
dump("Ping");
$query->andWhere($alias.'.isDeleted = :false')->setParameter('false', false);
}
else {
dump("Pong");
}
return $query;
}
}
Controller:
...
public function searchAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$meta = new ClassMetadata('AppBundle:Location');
$er = new BasicRepository($em, $meta);
$query = $er->createQueryBuilder('u');
...
My aim is that - if the property "isDeleted" (boolean) exists in the Entity - the Query should contain an additional Where-Statement.
For some strange reason property_exists always return false - even when the property exits in the class.
I get your idea. The correct place you're looking for is Doctrine Filters. Check this package: https://github.com/DeprecatedPackages/DoctrineFilters#usage
There you can find example exactly with your use case:
<?php
use Doctrine\ORM\Mapping\ClassMetadata;
use Symplify\DoctrineFilters\Contract\Filter\FilterInterface;
final class SoftdeletableFilter implements FilterInterface
{
/**
* {#inheritdoc}
*/
public function addFilterConstraint(ClassMetadata $entity, $alias)
{
if ($entity->getReflectionClass()->hasProperty('isDeleted')) {
return "$alias.isDeleted = 0";
}
return '';
}
}

Symfony2 : Automatically map query string in Controller parameter

In Symfony2, the route parameters can be automatically map to the controller arguments, eg: http://a.com/test/foo will return "foo"
/**
* #Route("/test/{name}")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
see http://symfony.com/doc/current/book/routing.html#route-parameters-and-controller-arguments
But I want to use query string instead eg: http://a.com/test?name=foo
How to do that ?
For me there are only 3 solutions:
re-implement ControllerResolverInterface
use a custom ParamConverter
$name = $request->query->get('name');
Is there another solution ?
I provide you the code for those which want to use a converter :
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Put specific attribute parameter to query parameters
*/
class QueryStringConverter implements ParamConverterInterface{
public function supports(ParamConverter $configuration) {
return 'querystring' == $configuration->getConverter();
}
public function apply(Request $request, ParamConverter $configuration) {
$param = $configuration->getName();
if (!$request->query->has($param)) {
return false;
}
$value = $request->query->get($param);
$request->attributes->set($param, $value);
}
}
services.yml :
services:
querystring_paramconverter:
class: AppBundle\Extension\QueryStringConverter
tags:
- { name: request.param_converter, converter: querystring }
In your controller:
/**
* #Route("/test")
* #ParamConverter("name", converter="querystring")
*/
public function action(Request $request, $name) {
return new Response(print_r($name, true));
}
An improved solution based on Remy's answer which will map the parameter to an entity :
<?php
namespace AppBundle\Extension;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter;
/**
* Put specific attribute parameter to query parameters
*/
class QueryStringConverter extends DoctrineParamConverter {
protected function getIdentifier(Request $request, $options, $name)
{
if ($request->query->has($name)) {
return $request->query->get($name);
}
return false;
}
}
services.yml:
services:
querystring_paramconverter:
class: MBS\AppBundle\Extension\QueryStringConverter
arguments: ['#doctrine']
tags:
- { name: request.param_converter, converter: querystring }
in your controller:
/**
* #Route("/test")
* #ParamConverter("myobject")
*/
public function action(Request $request, AnyEntity $myobject) {
return new Response(print_r($myobject->getName(), true));
}
like #2, To solve private method (getIdentifier) first set attributes and execute normally (parent::apply). Tested on Symfony 4.4
<?php
namespace App\FrameworkExtra\Converters;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter;
use Symfony\Component\HttpFoundation\Request;
class QueryStringEntityConverter extends DoctrineParamConverter
{
public function supports(ParamConverter $configuration)
{
return 'querystringentity' == $configuration->getConverter();
}
public function apply(Request $request, ParamConverter $configuration)
{
$param = $configuration->getName();
if (!$request->query->has($param)) {
return false;
}
$value = $request->query->get($param);
$request->attributes->set($param, $value);
return parent::apply($request, $configuration);
}
}
I havn't checked, but it seems that the FOSRestBundle provides the #QueryParam annotation which does that :
http://symfony.com/doc/current/bundles/FOSRestBundle/param_fetcher_listener.html

Symfony2 and ParamConverter(s)

Accessing my route /message/new i'm going to show a form for sending a new message to one or more customers. Form model has (among others) a collection of Customer entities:
class MyFormModel
{
/**
* #var ArrayCollection
*/
public $customers;
}
I'd like to implement automatic customers selection using customers GET parameters, like this:
message/new?customers=2,55,543
This is working now by simply splitting on , and do a query for getting customers:
public function newAction(Request $request)
{
$formModel = new MyFormModel();
// GET "customers" parameter
$customersIds = explode($request->get('customers'), ',');
// If something was found in "customers" parameter then get entities
if(!empty($customersIds)) :
$repo = $this->getDoctrine()->getRepository('AcmeHelloBundle:Customer');
$found = $repo->findAllByIdsArray($customersIds);
// Assign found Customer entities
$formModel->customers = $found;
endif;
// Go on showing the form
}
How can i do the same using Symfony 2 converters? Like:
public function newAction(Request $request, $selectedCustomers)
{
}
Answer to my self: there is not such thing to make you life easy. I've coded a quick and dirty (and possibly buggy) solution i'd like to share, waiting for a best one.
EDIT WARNING: this is not going to work with two parameter converters with the same class.
Url example
/mesages/new?customers=2543,3321,445
Annotations:
/**
* #Route("/new")
* #Method("GET|POST")
* #ParamConverter("customers",
* class="Doctrine\Common\Collections\ArrayCollection", options={
* "finder" = "getFindAllWithMobileByUserQueryBuilder",
* "entity" = "Acme\HelloBundle\Entity\Customer",
* "field" = "id",
* "delimiter" = ",",
* }
* )
*/
public function newAction(Request $request, ArrayCollection $customers = null)
{
}
Option delimiter is used to split GET parameter while id is used for adding a WHERE id IN... clause. There are both optional.
Option class is only used as a "signature" to tell that converter should support it. entity has to be a FQCN of a Doctrine entity while finder is a repository method to be invoked and should return a query builder (default one provided).
Converter
class ArrayCollectionConverter implements ParamConverterInterface
{
/**
* #var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
function apply(Request $request, ConfigurationInterface $configuration)
{
$name = $configuration->getName();
$options = $this->getOptions($configuration);
// Se request attribute to an empty collection (as default)
$request->attributes->set($name, new ArrayCollection());
// If request parameter is missing or empty then return
if(is_null($val = $request->get($name)) || strlen(trim($val)) === 0)
return;
// If splitted values is an empty array then return
if(!($items = preg_split('/\s*'.$options['delimiter'].'\s*/', $val,
0, PREG_SPLIT_NO_EMPTY))) return;
// Get the repository and logged user
$repo = $this->getEntityManager()->getRepository($options['entity']);
$user = $this->getSecurityContext->getToken()->getUser();
if(!$finder = $options['finder']) :
// Create a new default query builder with WHERE user_id clause
$builder = $repo->createQueryBuilder('e');
$builder->andWhere($builder->expr()->eq("e.user", $user->getId()));
else :
// Call finder method on repository
$builder = $repo->$finder($user);
endif;
// Edit the builder and add WHERE IN $items clause
$alias = $builder->getRootAlias() . "." . $options['field'];
$wherein = $builder->expr()->in($alias, $items);
$result = $builder->andwhere($wherein)->getQuery()->getResult();
// Set request attribute and we're done
$request->attributes->set($name, new ArrayCollection($result));
}
public function supports(ConfigurationInterface $configuration)
{
$class = $configuration->getClass();
// Check if class is ArrayCollection from Doctrine
if('Doctrine\Common\Collections\ArrayCollection' !== $class)
return false;
$options = $this->getOptions($configuration);
$manager = $this->getEntityManager();
// Check if $options['entity'] is actually a Dcontrine one
try
{
$manager->getClassMetadata($options['entity']);
return true;
}
catch(\Doctrine\ORM\Mapping\MappingException $e)
{
return false;
}
}
protected function getOptions(ConfigurationInterface $configuration)
{
return array_replace(
array(
'entity' => null,
'finder' => null,
'field' => 'id',
'delimiter' => ','
),
$configuration->getOptions()
);
}
/**
* #return \Doctrine\ORM\EntityManager
*/
protected function getEntityManager()
{
return $this->container->get('doctrine.orm.default_entity_manager');
}
/**
* #return \Symfony\Component\Security\Core\SecurityContext
*/
protected function getSecurityContext()
{
return $this->container->get('security.context');
}
}
Service definition
arraycollection_converter:
class: Acme\HelloBundle\Request\ArrayCollectionConverter
arguments: ['#service_container']
tags:
- { name: request.param_converter}
It's late, but according to latest documentation about #ParamConverter, you can achieve it follow way:
* #ParamConverter("users", class="AcmeBlogBundle:User", options={
* "repository_method" = "findUsersByIds"
* })
you just need make sure that repository method can handle comma (,) separated values

Resources