Passed
Push — master ( dc770a...719d75 )
by Pavel
50s
created

RelatedCollectionAction::relatedRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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);
0 ignored issues
show
Unused Code introduced by
The assignment to $entity is dead and can be removed.
Loading history...
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