Passed
Push — v2 ( b247ab...8c624d )
by Alexander
02:21
created

TransformerResolver::resolveFromData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Flugg\Responder\Transformers;
4
5
use Flugg\Responder\Contracts\Transformable;
6
use Flugg\Responder\Contracts\Transformers\TransformerResolver as TransformerResolverContract;
7
use Flugg\Responder\Exceptions\InvalidTransformerException;
8
use Illuminate\Contracts\Container\Container;
9
use Illuminate\Contracts\Support\Arrayable;
10
use Traversable;
11
12
/**
13
 * This class is responsible for resolving transformers.
14
 *
15
 * @package flugger/laravel-responder
16
 * @author  Alexander Tømmerås <[email protected]>
17
 * @license The MIT License
18
 */
19
class TransformerResolver implements TransformerResolverContract
20
{
21
    /**
22
     * A container used to resolve transformers.
23
     *
24
     * @var \Illuminate\Contracts\Container\Container
25
     */
26
    protected $container;
27
28
    /**
29
     * Transformable to transformer mappings.
30
     *
31
     * @var array
32
     */
33
    protected $bindings = [];
34
35
    /**
36
     * Construct the resolver class.
37
     *
38
     * @param \Illuminate\Contracts\Container\Container $container
39
     */
40
    public function __construct(Container $container)
41
    {
42
        $this->container = $container;
43
    }
44
45
    /**
46
     * Register a transformable to transformer binding.
47
     *
48
     * @param  string|array         $transformable
49
     * @param  string|callback|null $transformer
50
     * @return void
51
     */
52
    public function bind($transformable, $transformer = null)
53
    {
54
        $this->bindings = array_merge($this->bindings, is_array($transformable) ? $transformable : [
55
            $transformable => $transformer,
56
        ]);
57
    }
58
59
    /**
60
     * Resolve a transformer.
61
     *
62
     * @param  \Flugg\Responder\Transformers\Transformer|string|callable $transformer
63
     * @return \Flugg\Responder\Transformers\Transformer|callable
64
     * @throws \Flugg\Responder\Exceptions\InvalidTransformerException
65
     */
66
    public function resolve($transformer)
67
    {
68
        if (is_string($transformer)) {
69
            return $this->container->make($transformer);
70
        }
71
72
        if (! is_callable($transformer) && ! $transformer instanceof Transformer) {
73
            throw new InvalidTransformerException;
74
        }
75
76
        return $transformer;
77
    }
78
79
    /**
80
     * Resolve a transformer from the given data.
81
     *
82
     * @param  mixed $data
83
     * @return \Flugg\Responder\Transformers\Transformer|callable|null
84
     */
85
    public function resolveFromData($data)
86
    {
87
        $transformable = $this->resolveTransformable($data);
88
        $transformer = $this->resolveTransformer($transformable);
89
90
        return $this->resolve($transformer);
0 ignored issues
show
Bug introduced by
It seems like $transformer defined by $this->resolveTransformer($transformable) on line 88 can also be of type null or object<Flugg\Responder\Contracts\Transformable>; however, Flugg\Responder\Transfor...rmerResolver::resolve() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
91
    }
92
93
    /**
94
     * Resolve a transformable from the given data.
95
     *
96
     * @param  mixed $data
97
     * @return \Flugg\Responder\Contracts\Transformable|null
98
     */
99
    protected function resolveTransformable($data)
100
    {
101
        if (is_array($data) || $data instanceof Traversable) {
102
            foreach ($data as $item) {
103
                return $item;
104
            }
105
        }
106
107
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $data; (array|object|integer|double|string|null|boolean) is incompatible with the return type documented by Flugg\Responder\Transfor...r::resolveTransformable of type Flugg\Responder\Contracts\Transformable|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
108
    }
109
110
    /**
111
     * Resolve a transformer from the transformable element.
112
     *
113
     * @param  mixed $transformable
114
     * @return \Flugg\Responder\Contracts\Transformable|callable|null
115
     */
116
    protected function resolveTransformer($transformable)
117
    {
118
        if (is_object($transformable) && key_exists(get_class($transformable), $this->bindings)) {
119
            return $this->bindings[get_class($transformable)];
120
        }
121
122
        if ($transformable instanceof Transformable) {
123
            return $transformable->transformer();
124
        }
125
126
        return $this->resolveFallbackTransformer();
127
    }
128
129
    /**
130
     * Resolve a fallback closure transformer just returning the data directly.
131
     *
132
     * @return callable
133
     */
134
    protected function resolveFallbackTransformer()
135
    {
136
        return function ($data) {
137
            return $data instanceof Arrayable ? $data->toArray() : $data;
138
        };
139
    }
140
}