Completed
Push — master ( 7e3774...ee2aad )
by tac
03:58
created

Endpoint::process()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 0
loc 22
rs 8.6738
cc 5
eloc 13
nc 5
nop 0
1
<?php
2
3
namespace Tacone\Bees\Widget;
4
5
use App;
6
use ArrayAccess;
7
use Countable;
8
use Illuminate\Contracts\Support\Arrayable;
9
use Illuminate\Contracts\Support\Jsonable;
10
use Illuminate\Contracts\Support\Renderable;
11
use IteratorAggregate;
12
use Tacone\Bees\Base\DelegatedArrayTrait;
13
use Tacone\Bees\Collection\FieldCollection;
14
use Tacone\Bees\Field\Field;
15
use Tacone\Bees\Helper\Error;
16
use Tacone\DataSource\AbstractDataSource;
17
use Tacone\DataSource\DataSource;
18
19
class Endpoint implements Countable, IteratorAggregate, ArrayAccess, Arrayable, Jsonable
20
{
21
    use DelegatedArrayTrait;
22
23
    /**
24
     * @var FieldCollection
25
     */
26
    protected $fields;
27
28
    /**
29
     * @var AbstractDataSource
30
     */
31
    protected $source;
32
33
    protected $auto = false;
34
35
    public function __construct($source = [])
36
    {
37
        $this->fields = new FieldCollection();
38
        $this->initSource($source);
39
    }
40
41
    public static function auto($source)
42
    {
43
        $endpoint = new static($source);
44
        $endpoint->auto = true;
45
        return $endpoint;
46
    }
47
48
    protected function initSource($source)
49
    {
50
        $this->source = DataSource::make($source);
51
    }
52
53
    /**
54
     * @param string $name
55
     * @param array $arguments
56
     *
57
     * @return Field|static|mixed
58
     */
59
    public function __call($name, $arguments)
60
    {
61
        // Is it a field name?
62
        try {
63
            $binding = "bees.$name";
64
            $field = App::make($binding, $arguments);
65
            $this->fields->add($field);
66
67
            return $field;
68
        } catch (\ReflectionException $e) {
69
            // not a field name
70
        }
71
72
        // oh, well, then ...
73
        throw Error::missingMethod($this, $name);
74
    }
75
76
    public function source($newSource = null)
77
    {
78
        if (func_num_args()) {
79
            $this->source = $newSource;
80
81
            return $this;
82
        }
83
84
        return $this->source;
85
    }
86
87
    /**
88
     * Collection containing all the fields in the form.
89
     *
90
     * @return FieldCollection
91
     */
92
    public function fields()
93
    {
94
        return $this->fields;
95
    }
96
97
    /**
98
     * Get a field by name (dotted offset).
99
     *
100
     * (you can also use array notation like:
101
     * <code>$form['author.name']</code>
102
     *
103
     * @param string $name
104
     *
105
     * @return Field
106
     */
107
    public function field($name)
108
    {
109
        return $this->fields->get($name);
110
    }
111
112
    /**
113
     * Get the fields value as an associative array.
114
     * By default a nested array is returned.
115
     * Passing true as the first parameter, a flat
116
     * array will be returned, with dotted offsets
117
     * as the keys.
118
     *
119
     * @param bool $flat
120
     *
121
     * @return array
122
     */
123
    public function toArray($flat = false)
124
    {
125
        return $this->fields()->toArray($flat);
126
    }
127
128
    /**
129
     * Required by DelegatedArrayTrait.
130
     *
131
     * @return FieldCollection
132
     */
133
    protected function getDelegatedStorage()
134
    {
135
        return $this->fields;
136
    }
137
138
    /**
139
     * Sets the fields values back to the models.
140
     */
141
    public function writeSource()
142
    {
143
        foreach ($this->fields as $name => $field) {
144
            $this->source[$name] = $field->value();
145
        }
146
    }
147
148
    /**
149
     * Fills the form with the values coming from the DB
150
     * and HTTP input.
151
     */
152
    public function populate()
153
    {
154
        $this->fromSource();
155
        $this->fromInput();
156
    }
157
158
    public function fromSource()
159
    {
160
        return $this->from($this->source);
161
    }
162
163
    public function fromInput()
164
    {
165
        return $this->from(\Input::all());
166
    }
167
168
    public function from($source)
169
    {
170
        if (!$source instanceof AbstractDataSource) {
171
            $source = DataSource::make($source);
172
        }
173
174
        return $this->fields->from($source);
175
    }
176
177
    /**
178
     * Saves the models back to the database.
179
     */
180
    public function save()
181
    {
182
        return $this->source->save();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Tacone\DataSource\AbstractDataSource as the method save() does only exist in the following sub-classes of Tacone\DataSource\AbstractDataSource: Tacone\DataSource\AbstractEloquentDataSource, Tacone\DataSource\EloquentCollectionDataSource, Tacone\DataSource\EloquentModelDataSource. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
183
    }
184
185
    /**
186
     * Validates the form, then sets eventual errors on each field.
187
     *
188
     * @return mixed
189
     */
190
    public function validate()
191
    {
192
        $arguments = func_get_args();
193
194
        return call_user_func_array([$this->fields, 'validate'], $arguments);
195
    }
196
197
    /**
198
     * @return mixed
199
     */
200
    public function errors()
201
    {
202
        $arguments = func_get_args();
203
204
        return call_user_func_array([$this->fields, 'errors'], $arguments);
205
    }
206
207
    /**
208
     * Convert the object to its JSON representation.
209
     *
210
     * @param  int $options
211
     * @return string
212
     */
213
    public function toJson($options = 0)
214
    {
215
        if ($this->auto) {
216
            $this->process();
217
        }
218
        return json_encode(
219
            $this->toArray(),
220
            JSON_UNESCAPED_SLASHES
221
        );
222
    }
223
224
    protected function getKey()
225
    {
226
        $parameters = \Route::current()->parameters();
227
        return reset($parameters);
228
    }
229
230
    protected function process()
231
    {
232
        $key = $this->getKey();
233
        $this->load($key);
0 ignored issues
show
Unused Code introduced by
The call to Endpoint::load() has too many arguments starting with $key.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
234
        $this->fromSource();
235
236
        if (\Request::method() == 'GET') {
237
            if (!$key) App::abort(404);
238
239
        } elseif (\Request::method() == 'POST') {
240
            $this->fromInput();
241
            if ($this->validate()) {
242
                $this->writeSource();
243
                $this->save();
244
            } else {
245
                // TODO: move this to the middleware
246
                // HTTP_UNPROCESSABLE_ENTITY
247
                App::abort(422, $this->errors());
248
            }
249
250
        }
251
    }
252
253
    protected function load()
254
    {
255
        $key = $this->getKey();
256
        if ($key) {
257
            $instance = $this->source->unwrap()->find($key) or App::abort(404);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
258
            $this->initSource($instance);
259
        }
260
    }
261
}
262