-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathAbstractConverter.php
More file actions
95 lines (80 loc) · 2.6 KB
/
AbstractConverter.php
File metadata and controls
95 lines (80 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/**
* Created by Eton Digital.
* User: Vladimir Mladenovic (vladimir.mladenovic@etondigital.com)
* Date: 15.7.15.
* Time: 09.02
*/
namespace ED\BlogBundle\Converter;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class AbstractConverter implements ParamConverterInterface
{
protected $targetEntitiesArray;
protected $doctrine;
function __construct($targetEntitiesArray, Registry $doctrine)
{
$this->targetEntitiesArray = $targetEntitiesArray;
$this->doctrine = $doctrine;
}
/**
* Stores the object in the request.
*
* @param Request $request The request
* @param ParamConverter $configuration Contains the name, class and options of the object
*
* @return bool True if the object has been successfully set, else false
*/
public function apply(Request $request, ParamConverter $configuration)
{
$slug = $request->get('slug', null);
$username = $request->get('username', null);
$id = $request->get('id', null);
if ($slug)
{
$searchArray = array('slug' => $slug);
}
elseif($username)
{
$searchArray = array('usernameCanonical' => $username);
}
elseif($id)
{
$searchArray = array('id' => $id);
}
else
{
throw new \InvalidArgumentException('Route attribute is missing');
}
$class = $this->targetEntitiesArray[$configuration->getClass()];
$repository = $this->doctrine->getRepository($class);
$object = $repository->findOneBy( $searchArray );
if(!$object)
throw new NotFoundHttpException("Sorry, requested resource can't be found.");
$request->attributes->set($configuration->getName(), $object);
}
/**
* Checks if the object is supported.
*
* @param ParamConverter $configuration Should be an instance of ParamConverter
*
* @return bool True if the object is supported, else false
*/
public function supports(ParamConverter $configuration)
{
if (null === $configuration->getClass()) {
return false;
}
if(array_key_exists($configuration->getClass(), $this->targetEntitiesArray))
{
return true;
}
else
{
return false;
}
}
}