Last active
April 14, 2017 14:20
-
-
Save pounard/8e3b8bff157d10a66cddccb0f968865b to your computer and use it in GitHub Desktop.
Param converter sans annotations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace MonVendor\MonBundle\Controller; | |
use MonVendor\MonBundle\Gestion\DemandeHelper; | |
use MonVendor\MonBundle\Gestion\Entity\Aide; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; | |
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; | |
/** | |
* Param converter for misc. business entities | |
*/ | |
class MonParamConverter implements ParamConverterInterface | |
{ | |
private $helper; | |
/** | |
* Default constructor | |
* | |
* @param Service $service | |
*/ | |
public function __construct(DemandeHelper $helper) | |
{ | |
$this->helper = $helper; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function apply(Request $request, ParamConverter $configuration) | |
{ | |
$param = $configuration->getName(); | |
if (!$request->attributes->has($param)) { | |
return false; | |
} | |
$id = $request->attributes->get($param); | |
$object = null; | |
if (!$id && $configuration->isOptional()) { | |
return false; | |
} | |
try { | |
switch ($configuration->getClass()) { | |
case Aide::class: | |
if (!$this->helper->aideExists($id)) { | |
throw new \InvalidArgumentException(); | |
} | |
$object = $this->helper->getAide($id, true); | |
break; | |
} | |
} catch (\InvalidArgumentException $e) { | |
throw new NotFoundHttpException('Not Found.', $e); | |
} | |
$request->attributes->set($param, $object); | |
return true; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function supports(ParamConverter $configuration) | |
{ | |
switch ($configuration->getClass()) { | |
case Aide::class: | |
return true; | |
} | |
return false; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
mon_appli.mon_param_converter: | |
# Pas besoin qu'il soit publique | |
public: false | |
class: MonVendor\MonBundle\Controller\MonParamConverter | |
# Tes arguments, c'est un service | |
arguments: ['...'] | |
# Le tag magique qui fait que ça marche | |
tags: [{name: request.param_converter, priority: 1024, converter: mon_appli.mon_param_converter}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment