1
|
|
|
<?php namespace Pz\Doctrine\Rest\Action; |
2
|
|
|
|
3
|
|
|
use Doctrine\ORM\QueryBuilder; |
4
|
|
|
use Doctrine\ORM\Tools\Pagination\Paginator; |
5
|
|
|
use League\Fractal\Pagination\DoctrinePaginatorAdapter; |
6
|
|
|
use League\Fractal\Resource\Collection; |
7
|
|
|
use Pz\Doctrine\Rest\Contracts\RestRequestContract; |
8
|
|
|
use Pz\Doctrine\Rest\RestResponse; |
9
|
|
|
use Pz\Doctrine\Rest\RestRepository; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Action for providing collection (list or array) of data with API. |
13
|
|
|
*/ |
14
|
|
|
class RelatedCollectionAction extends CollectionAction |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Field that contains the related repository |
18
|
|
|
* |
19
|
|
|
* @var RestRepository |
20
|
|
|
*/ |
21
|
|
|
protected $relatedRepository; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Field that contains the related resourse key |
25
|
|
|
* |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
protected $relatedKey; |
29
|
|
|
|
30
|
|
|
public function __construct(RestRepository $repository, RestRepository $relatedRepository, $transformer, $relatedKey) |
31
|
|
|
{ |
32
|
|
|
parent::__construct($repository, $transformer); |
33
|
|
|
$this->relatedRepository = $relatedRepository; |
34
|
|
|
$this->relatedKey = $relatedKey; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param RestRequestContract $request |
39
|
|
|
* |
40
|
|
|
* @return RestResponse |
41
|
|
|
*/ |
42
|
|
|
protected function handle($request) |
43
|
|
|
{ |
44
|
|
|
$resourceKey = $this->relatedRepository()->getResourceKey(); |
45
|
|
|
$this->authorize($request, $this->repository()->getClassName()); |
46
|
|
|
|
47
|
|
|
$entity = $this->repository()->findByIdentifier($request); |
|
|
|
|
48
|
|
|
$qb = $this->relatedRepository()->sourceQueryBuilder(); |
49
|
|
|
$qb->andWhere($this->relatedRepository()->alias() . '.' . $this->relatedKey . ' = ' . ((int)$request->getId())); |
50
|
|
|
$this->applyPagination($request, $qb); |
51
|
|
|
$this->applyFilter($request, $qb); |
52
|
|
|
|
53
|
|
|
$paginator = new Paginator($qb, false); |
54
|
|
|
$collection = new Collection($paginator, $this->transformer(), $resourceKey); |
55
|
|
|
|
56
|
|
|
if ($qb->getMaxResults()) { |
57
|
|
|
$collection->setPaginator( |
58
|
|
|
new DoctrinePaginatorAdapter( |
59
|
|
|
$paginator, |
60
|
|
|
$this->paginatorUrlGenerator($request, $resourceKey) |
61
|
|
|
) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $this->response()->resource($request, $collection); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return RestRepository |
70
|
|
|
*/ |
71
|
|
|
public function relatedRepository() |
72
|
|
|
{ |
73
|
|
|
return $this->relatedRepository; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|