Test Failed
Push — master ( c55f59...68f2b4 )
by Pavel
03:14
created

CollectionMatcher::matching()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Bankiru\Api\Doctrine\Persister;
4
5
use Bankiru\Api\Doctrine\ApiEntityManager;
6
use Bankiru\Api\Doctrine\Rpc\CrudsApiInterface;
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\Common\Collections\Criteria;
9
use Doctrine\Common\Collections\Selectable;
10
11
final class CollectionMatcher implements Selectable
12
{
13
    /** @var CrudsApiInterface */
14
    private $api;
15
    /** @var ApiEntityManager */
16
    private $manager;
17
18
    /**
19
     * CollectionMatcher constructor.
20
     *
21
     * @param CrudsApiInterface $api
22
     * @param ApiEntityManager  $manager
23
     */
24
    public function __construct(ApiEntityManager $manager, CrudsApiInterface $api)
25
    {
26
        $this->api     = $api;
27
        $this->manager = $manager;
28
    }
29
30
    public function matching(Criteria $criteria)
31
    {
32
        if ($this->api instanceof Selectable) {
33
            return $this->api->matching($criteria);
34
        }
35
36
        return $this->search($criteria);
37
    }
38
39
    private function search(Criteria $criteria)
40
    {
41
        $expr = $criteria->getWhereExpression();
42
43
        $filter = [];
44
        if ($expr) {
45
            $visitor = new SimpleCriteriaVisitor();
46
            $filter  = $visitor->dispatch($expr);
47
        }
48
49
        $orderings = $criteria->getOrderings();
50
        $offset    = $criteria->getFirstResult();
51
        $length    = $criteria->getMaxResults();
52
53
        $data = $this->api->search($filter, $orderings, $offset, $length);
54
55
        $entities = [];
56
        foreach ($data as $object) {
57
            $entities[] = $this->manager->getUnitOfWork()->getOrCreateEntity(
58
                $this->api->getMetadata()->getName(),
59
                $object
60
            );
61
        }
62
63
        return new ArrayCollection($entities);
64
    }
65
}
66