ArrayTransformer::transform()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
crap 1
1
<?php
2
3
namespace Alchemy\Rest\Response;
4
5
use League\Fractal\Manager;
6
use League\Fractal\Pagination\PaginatorInterface;
7
use League\Fractal\Resource\Collection;
8
use League\Fractal\Resource\Item;
9
use League\Fractal\TransformerAbstract;
10
11
class ArrayTransformer
12
{
13
14
    /**
15
     * @var Manager
16
     */
17
    private $manager;
18
19
    /**
20
     * @var \ArrayAccess
21
     */
22
    private $transformers;
23
24
    /**
25
     * @param Manager $fractalManager
26
     * @param \ArrayAccess $transformerRegistry
27
     */
28 12
    public function __construct(Manager $fractalManager, \ArrayAccess $transformerRegistry)
29
    {
30 12
        $this->manager = $fractalManager;
31 12
        $this->transformers = $transformerRegistry;
32 12
    }
33
34
    /**
35
     * @param string $key
36
     * @return TransformerAbstract
37
     */
38 12
    public function getTransformer($key)
39
    {
40 12
        if (! isset($this->transformers[$key])) {
41 2
            throw new \RuntimeException('Invalid transformer requested.');
42
        }
43
44 10
        return $this->transformers[$key];
45
    }
46
47
    /**
48
     * @param $key
49
     * @param mixed $resource
50
     * @param null|string|array $includes
51
     * @return array
52
     */
53 4
    public function transform($key, $resource, $includes = null)
54
    {
55 4
        $transformer = $this->getTransformer($key);
56 4
        $resource = (new Item($resource, $transformer));
57
58 4
        return $this->convertResource($resource, $includes);
59
    }
60
61
    /**
62
     * @param $key
63
     * @param array $resources
64
     * @param PaginatorInterface $paginator
65
     * @param null|string|array $includes
66
     * @return array
67
     */
68 6
    public function transformList($key, $resources, $includes = null, PaginatorInterface $paginator = null)
69
    {
70 6
        $transformer = $this->getTransformer($key);
71 6
        $resource = new Collection($resources, $transformer);
72
73 6
        if ($paginator !== null) {
74 2
            $resource->setPaginator($paginator);
75 4
        }
76
77 6
        return $this->convertResource($resource, $includes);
78
    }
79
80
    /**
81
     * @param mixed $resource
82
     * @param null|string|array $includes
83
     * @return array
84
     */
85 10
    private function convertResource($resource, $includes = null)
86
    {
87 10
        if ($includes !== null) {
88 6
            $this->manager->parseIncludes($includes);
89 6
        }
90
91 10
        return $this->manager->createData($resource)->toArray();
92
    }
93
}
94