Completed
Push — master ( a4eeee...1f82e1 )
by Jodie
05:38 queued 12s
created

TransformerResolver::resolve()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 12
nop 1
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
    /** @var string|null */
14
    protected $namespace;
15
16
    /**
17
     * TransformerResolver constructor.
18
     *
19
     * @param string $namespace
20
     */
21
    public function __construct(string $namespace)
22
    {
23
        $this->namespace = $namespace;
24
    }
25
26
    /**
27
     * Determines the Transformer object to be used for a particular resource.
28
     * Inspects the underlying Eloquent model to determine an appropriately
29
     * named transformer class, and instantiate the object.
30
     *
31
     * {@inheritdoc}
32
     *
33
     * @throws \Rexlabs\Laravel\Smokescreen\Exceptions\UnresolvedTransformerException
34
     */
35
    public function resolve(ResourceInterface $resource)
36
    {
37
        $transformer = null;
38
39
        // Find the underlying model of the resource data
40
        $model = null;
41
        $data = $resource->getData();
42
        if ($data instanceof Model) {
43
            $model = $data;
44
        } elseif ($data instanceof Collection) {
45
            $model = $data->first();
46
        }
47
48
        // If no model can be determined from the data
49
        if ($model !== null) {
50
            // Cool, now let's try to find a matching transformer based on our Model class
51
            // We use our configuration value 'transformer_namespace' to determine where to look.
52
            try {
53
                $transformerClass = sprintf('%s\\%sTransformer',
54
                    $this->namespace,
55
                    (new \ReflectionClass($model))->getShortName());
56
                $transformer = resolve($transformerClass);
57
            } catch (\Exception $e) {
58
                throw new UnresolvedTransformerException('Unable to resolve transformer for model: '.\get_class($model),
59
                    0, $e);
60
            }
61
        }
62
63
        return $transformer;
64
    }
65
}
66