Completed
Push — master ( ded069...f3e90c )
by Ryan
07:28
created

FormCriteria::build()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 51
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
c 5
b 1
f 0
dl 0
loc 51
rs 9.4109
cc 3
eloc 25
nc 2
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php namespace Anomaly\Streams\Platform\Ui\Form;
2
3
use Anomaly\Streams\Platform\Support\Decorator;
4
use Anomaly\Streams\Platform\Support\Hydrator;
5
use Anomaly\Streams\Platform\Traits\FiresCallbacks;
6
use Illuminate\Contracts\Cache\Repository;
7
use Illuminate\Contracts\Container\Container;
8
use Illuminate\Http\Request;
9
10
/**
11
 * Class FormCriteria
12
 *
13
 * @link          http://anomaly.is/streams-platform
14
 * @author        AnomalyLabs, Inc. <[email protected]>
15
 * @author        Ryan Thompson <[email protected]>
16
 * @package       Anomaly\Streams\Platform\Ui\Form
17
 */
18
class FormCriteria
19
{
20
21
    use FiresCallbacks;
22
23
    /**
24
     * The cache repository.
25
     *
26
     * @var Repository
27
     */
28
    protected $cache;
29
30
    /**
31
     * The form builder.
32
     *
33
     * @var FormBuilder
34
     */
35
    protected $builder;
36
37
    /**
38
     * The request object.
39
     *
40
     * @var Request
41
     */
42
    protected $request;
43
44
    /**
45
     * The hydrator utility.
46
     *
47
     * @var Hydrator
48
     */
49
    protected $hydrator;
50
51
    /**
52
     * The service container.
53
     *
54
     * @var Container
55
     */
56
    protected $container;
57
58
    /**
59
     * The parameters.
60
     *
61
     * @var array
62
     */
63
    protected $parameters = [];
64
65
    /**
66
     * Create a new FormCriteria instance.
67
     *
68
     * @param Repository  $cache
69
     * @param Request     $request
70
     * @param Hydrator    $hydrator
71
     * @param Container   $container
72
     * @param FormBuilder $builder
73
     * @param array       $parameters
74
     */
75
    public function __construct(
76
        Repository $cache,
77
        Request $request,
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
78
        Hydrator $hydrator,
79
        Container $container,
80
        FormBuilder $builder,
81
        array $parameters = []
82
    ) {
83
        $this->cache      = $cache;
84
        $this->builder    = $builder;
85
        $this->request    = $request;
86
        $this->hydrator   = $hydrator;
87
        $this->container  = $container;
88
        $this->parameters = $parameters;
89
90
        $this->setBuilder($builder);
91
92
        $this->fire('initialized', ['criteria' => $this]);
93
    }
94
95
    /**
96
     * Get the form.
97
     *
98
     * @return FormPresenter
99
     */
100
    public function get()
101
    {
102
        $this->build();
103
104
        return (new Decorator())->decorate($this->builder->make()->getForm());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (new \Anomaly\Str...er->make()->getForm()); (object|integer|double|string|null|boolean|array) is incompatible with the return type documented by Anomaly\Streams\Platform\Ui\Form\FormCriteria::get of type Anomaly\Streams\Platform...Form\FormPresenter|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...
105
    }
106
107
    /**
108
     * Build the builder.
109
     *
110
     * @return FormBuilder
111
     */
112
    public function build()
113
    {
114
115
        /**
116
         * Hide breadcrumbs by default.
117
         */
118
        array_set(
119
            $this->parameters,
120
            'options.breadcrumb',
121
            array_get(
122
                $this->parameters,
123
                'options.breadcrumb',
124
                false
125
            )
126
        );
127
128
        /**
129
         * Cache and hash!
130
         */
131
        array_set($this->parameters, 'key', md5(json_encode($this->parameters)));
132
133
        /**
134
         * Set the forms URL after obtaining
135
         * our parameter hash for the form.
136
         */
137
        array_set(
138
            $this->parameters,
139
            'options.url',
140
            array_get(
141
                $this->parameters,
142
                'options.url',
143
                $this->builder->getOption('url', 'form/handle/' . array_get($this->parameters, 'key'))
144
            )
145
        );
146
147
        $this->cache->remember(
148
            'form::' . array_get($this->parameters, 'key'),
149
            30,
150
            function () {
151
                return $this->parameters;
152
            }
153
        );
154
155
        if (is_array(array_get($this->parameters, 'options'))) {
156
            foreach (array_pull($this->parameters, 'options') as $key => $value) {
157
                $this->builder->setOption($key, $value);
158
            }
159
        }
160
161
        return $this->hydrator->hydrate($this->builder, $this->parameters);
162
    }
163
164
    /**
165
     * Set a parameter.
166
     *
167
     * @param $key
168
     * @param $value
169
     * @return $this
170
     */
171
    public function setParameter($key, $value)
172
    {
173
        $this->parameters[$key] = $value;
174
175
        return $this;
176
    }
177
178
    /**
179
     * Get the builder.
180
     *
181
     * @return FormBuilder
182
     */
183
    public function getBuilder()
184
    {
185
        return $this->builder;
186
    }
187
188
    /**
189
     * Set the form builder.
190
     *
191
     * @param FormBuilder $builder
192
     * @return $this
193
     */
194
    public function setBuilder($builder)
195
    {
196
        if (!is_object($builder)) {
197
            $builder = app($builder);
198
        }
199
200
        $this->builder = $builder;
201
202
        array_set($this->parameters, 'builder', get_class($this->builder));
203
204
        return $this;
205
    }
206
207
    /**
208
     * Route through __get
209
     *
210
     * @param $name
211
     * @return $this
212
     */
213
    public function __get($name)
214
    {
215
        return $this->__call($name, []);
216
    }
217
218
    /**
219
     * @param $name
220
     * @param $arguments
221
     * @return $this
222
     */
223
    public function __call($name, $arguments)
224
    {
225
226 View Code Duplication
        if (method_exists($this->builder, camel_case('set_' . $name))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
227
228
            array_set($this->parameters, $name, array_shift($arguments));
229
230
            return $this;
231
        }
232
233 View Code Duplication
        if (method_exists($this->builder, camel_case('add_' . $name))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
235
            array_set($this->parameters, $name, array_shift($arguments));
236
237
            return $this;
238
        }
239
240 View Code Duplication
        if (!method_exists($this->builder, camel_case($name)) && count($arguments) === 1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
242
            $key = snake_case($name);
243
244
            array_set($this->parameters, "options.{$key}", array_shift($arguments));
245
246
            return $this;
247
        }
248
249 View Code Duplication
        if (!method_exists($this->builder, camel_case($name)) && count($arguments) === 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
250
251
            $key = snake_case($name);
252
253
            // Helpful for form.disableLabels().disableFoo() ...
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
254
            array_set($this->parameters, "options.{$key}", true);
255
256
            return $this;
257
        }
258
259
        return $this;
260
    }
261
262
    /**
263
     * Return the form.
264
     *
265
     * @return string
266
     */
267
    public function __toString()
268
    {
269
        return $this->get()->__toString();
270
    }
271
}
272