TransformerResolver::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 2
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Rexlabs\Laravel\Smokescreen\Transformers;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
use Rexlabs\Laravel\Smokescreen\Exceptions\UnresolvedTransformerException;
8
use Rexlabs\Smokescreen\Resource\ResourceInterface;
9
use Rexlabs\Smokescreen\Transformer\TransformerResolverInterface;
10
11
class TransformerResolver implements TransformerResolverInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    protected $namespace;
17
18
    /**
19
     * @var string
20
     */
21
    protected $nameTemplate;
22
23
    /**
24
     * TransformerResolver constructor.
25
     *
26
     * @param string $namespace
27
     * @param string $nameTemplate
28
     */
29 18
    public function __construct(string $namespace, string $nameTemplate)
30
    {
31 18
        $this->namespace = $namespace;
32 18
        $this->nameTemplate = $nameTemplate;
33
    }
34
35
    /**
36
     * Determines the Transformer object to be used for a particular resource.
37
     * Inspects the underlying Eloquent model to determine an appropriately
38
     * named transformer class, and instantiate the object.
39
     *
40
     * {@inheritdoc}
41
     *
42
     * @throws \Rexlabs\Laravel\Smokescreen\Exceptions\UnresolvedTransformerException
43
     */
44 14
    public function resolve(ResourceInterface $resource)
45
    {
46 14
        $transformer = null;
47
48
        // Find the underlying model of the resource data
49 14
        $model = null;
50 14
        $data = $resource->getData();
51 14
        if ($data instanceof Model) {
52 3
            $model = $data;
53 12
        } elseif ($data instanceof Collection) {
54 2
            $model = $data->first();
55
        }
56
57 14
        if ($model !== null) {
58
            // Cool, now let's try to find a matching transformer based on our Model class
59
            // We use our configuration value 'transformer_namespace' to determine where to look.
60
            try {
61 5
                $modelName = (new \ReflectionClass($model))->getShortName();
62 5
                $transformerName = preg_replace('/{ModelName}/i', $modelName, $this->nameTemplate);
63 5
                $transformer = resolve(sprintf('%s\\%s', $this->namespace, $transformerName));
64 1
            } catch (\Exception $e) {
65 1
                throw new UnresolvedTransformerException(
66 1
                    'Unable to resolve transformer for model: ' . \get_class($model),
67 1
                    0,
68 1
                    $e
69 1
                );
70
            }
71
        }
72
73 13
        return $transformer;
74
    }
75
}
76