Completed
Pull Request — master (#7)
by Davide
02:23
created

Validation::getTranslator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace DavidePastore\Slim\Validation;
4
5
use Respect\Validation\Exceptions\NestedValidationException;
6
7
/**
8
 * Validation for Slim.
9
 */
10
class Validation
11
{
12
    /**
13
     * Validators.
14
     *
15
     * @var array
16
     */
17
    protected $validators = [];
18
19
    /**
20
     * The translator to use fro the exception message.
21
     *
22
     * @var callable
23
     */
24
    protected $translator = null;
25
26
    /**
27
     * Errors from the validation.
28
     *
29
     * @var array
30
     */
31
    protected $errors = [];
32
33
    /**
34
     * Create new Validator service provider.
35
     *
36
     * @param null|array|ArrayAccess $validators
37
     * @param null|callable          $translator
38
     */
39 10
    public function __construct($validators = null, $translator = null)
40
    {
41
        // Set the validators
42 10
        if (is_array($validators) || $validators instanceof ArrayAccess) {
0 ignored issues
show
Bug introduced by
The class DavidePastore\Slim\Validation\ArrayAccess does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
43 9
            $this->validators = $validators;
0 ignored issues
show
Documentation Bug introduced by
It seems like $validators can also be of type object<DavidePastore\Slim\Validation\ArrayAccess>. However, the property $validators is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
44 10
        } elseif (is_null($validators)) {
45 1
            $this->validators = [];
46 1
        }
47 10
        $this->translator = $translator;
48 10
    }
49
50
    /**
51
     * Validation middleware invokable class.
52
     *
53
     * @param \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
54
     * @param \Psr\Http\Message\ResponseInterface      $response PSR7 response
55
     * @param callable                                 $next     Next middleware
56
     *
57
     * @return \Psr\Http\Message\ResponseInterface
58
     */
59 10
    public function __invoke($request, $response, $next)
60
    {
61 10
        $this->errors = [];
62
        $params = $request->getParams();
63
        $this->validate($params, $this->validators);
64 10
65 9
        return $next($request, $response);
66
    }
67 9
68 9
    /**
69 6
     * Validate the parameters by the given params, validators and actual keys.
70 2
     * This method populates the $errors attribute.
71 2
     *
72 6
     * @param array $params     The array of parameters.
73
     * @param array $validators The array of validators.
74 10
     * @param array $actualKeys An array that will save all the keys of the tree to retrieve the correct value.
75
     */
76 10
    private function validate($params = [], $validators = [], $actualKeys = [])
77
    {
78
        //Validate every parameters in the validators array
79
      foreach ($validators as $key => $validator) {
80
          $actualKeys[] = $key;
81
          $param = $this->getNestedParam($params, $actualKeys);
82
          if (is_array($validator)) {
83
              $this->validate($params, $validator, $actualKeys);
84 10
          } else {
85
              try {
86 10
                  $validator->assert($param);
87
              } catch (NestedValidationException $exception) {
88
                  if ($this->translator) {
89
                      $exception->setParam('translator', $this->translator);
90
                  }
91
                  $this->errors[implode('.', $actualKeys)] = $exception->getMessages();
92
              }
93
          }
94 9
95
          //Remove the key added in this foreach
96 9
          array_pop($actualKeys);
97
      }
98
    }
99
100
    /**
101
     * Get the nested parameter value.
102
     *
103
     * @param array $params An array that represents the values of the parameters.
104 9
     * @param array $keys   An array that represents the tree of keys to use.
105
     *
106 9
     * @return mixed The nested parameter value by the given params and tree of keys.
107
     */
108
    private function getNestedParam($params = [], $keys = [])
109
    {
110
        if (empty($keys)) {
111
            return $params;
112
        } else {
113
            $firstKey = array_shift($keys);
114 1
            if (array_key_exists($firstKey, $params)) {
115
                $paramValue = $params[$firstKey];
116 1
117 1
                return $this->getNestedParam($paramValue, $keys);
118
            } else {
119
                return;
120
            }
121
        }
122
    }
123
124 2
    /**
125
     * Check if there are any errors.
126 2
     *
127
     * @return bool
128
     */
129
    public function hasErrors()
130
    {
131
        return !empty($this->errors);
132
    }
133
134 1
    /**
135
     * Get errors.
136 1
     *
137 1
     * @return array The errors array.
138
     */
139
    public function getErrors()
140
    {
141
        return $this->errors;
142
    }
143
144
    /**
145
     * Get validators.
146
     *
147
     * @return array The validators array.
148
     */
149
    public function getValidators()
150
    {
151
        return $this->validators;
152
    }
153
154
    /**
155
     * Set validators.
156
     *
157
     * @param array $validators The validators array.
158
     */
159
    public function setValidators($validators)
160
    {
161
        $this->validators = $validators;
162
    }
163
164
    /**
165
     * Get translator.
166
     *
167
     * @return callable The translator.
168
     */
169
    public function getTranslator()
170
    {
171
        return $this->translator;
172
    }
173
174
    /**
175
     * Set translator.
176
     *
177
     * @param callable $translator The translator.
178
     */
179
    public function setTranslator($translator)
180
    {
181
        $this->translator = $translator;
182
    }
183
}
184