1
|
|
|
<?php namespace Pz\Doctrine\Rest; |
2
|
|
|
|
3
|
|
|
use Doctrine\ORM\EntityNotFoundException; |
4
|
|
|
use Doctrine\ORM\EntityRepository; |
5
|
|
|
use Pz\Doctrine\Rest\Contracts\JsonApiResource; |
6
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
7
|
|
|
use Pz\Doctrine\Rest\Exceptions\RestException; |
8
|
|
|
|
9
|
|
|
class RestRepository extends EntityRepository |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var string |
13
|
|
|
*/ |
14
|
|
|
protected $alias; |
15
|
|
|
|
16
|
|
|
protected $resourceKey; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @return \Doctrine\ORM\EntityManager |
20
|
|
|
*/ |
21
|
7 |
|
public function getEntityManager() |
22
|
|
|
{ |
23
|
7 |
|
return parent::getEntityManager(); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @return \Doctrine\ORM\QueryBuilder |
28
|
|
|
*/ |
29
|
6 |
|
public function sourceQueryBuilder() |
30
|
|
|
{ |
31
|
6 |
|
return $this->createQueryBuilder($this->alias()); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @return string|null |
36
|
|
|
*/ |
37
|
12 |
|
public function getResourceKey() |
38
|
|
|
{ |
39
|
12 |
|
if (isset(class_implements($this->getClassName())[JsonApiResource::class])) { |
40
|
11 |
|
return call_user_func("{$this->getClassName()}::getResourceKey"); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Base root alias for queries. |
48
|
|
|
* |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
6 |
|
public function alias() |
52
|
|
|
{ |
53
|
6 |
|
if ($this->alias === null) { |
54
|
6 |
|
$this->alias = strtolower( |
55
|
6 |
|
preg_replace( |
56
|
6 |
|
'/(?<!^)[A-Z]/', '_$0', |
57
|
6 |
|
$this->getClassMetadata()->getReflectionClass()->getShortName() |
58
|
|
|
) |
59
|
|
|
); |
60
|
|
|
} |
61
|
|
|
|
62
|
6 |
|
return $this->alias; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param RestRequestContract $request |
67
|
|
|
* |
68
|
|
|
* @return null|object |
69
|
|
|
* @throws EntityNotFoundException |
70
|
|
|
*/ |
71
|
5 |
|
public function findByIdentifier(RestRequestContract $request) |
72
|
|
|
{ |
73
|
5 |
|
if (null === ($entity = $this->find($request->getId()))) { |
74
|
1 |
|
throw RestException::createNotFound($request->getId(), $this->getResourceKey(), sprintf( |
75
|
1 |
|
'Entity of type `%s` not found.', $this->getClassName() |
76
|
|
|
)); |
77
|
|
|
} |
78
|
|
|
|
79
|
4 |
|
return $entity; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @param RestRequestContract $request |
84
|
|
|
* @param JsonApiResource $resource |
85
|
|
|
* |
86
|
|
|
* @return string |
87
|
|
|
*/ |
88
|
1 |
|
public function linkJsonApiResource(RestRequestContract $request, JsonApiResource $resource) |
89
|
|
|
{ |
90
|
1 |
|
return sprintf('%s/%s/%s', $request->getBaseUrl(), $resource->getResourceKey(), $resource->getId()); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|