Completed
Push — master ( 2df407...de4379 )
by Neomerx
05:05
created

Application::showSingleValueValidation()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 66
Code Lines 34

Duplication

Lines 10
Ratio 15.15 %

Importance

Changes 0
Metric Value
dl 10
loc 66
rs 8.6045
c 0
b 0
f 0
cc 5
eloc 34
nc 16
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 Sample;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use DateTime;
20
use DateTimeInterface;
21
use Limoncello\Validation\ArrayValidator as v;
22
use Limoncello\Validation\Contracts\Errors\ErrorInterface;
23
use MessageFormatter;
24
use Sample\Validation\Errors;
25
use Sample\Validation\Rules as r;
26
27
/**
28
 * @package Sample
29
 */
30
class Application
31
{
32
    /**
33
     * @var bool
34
     */
35
    private $isOutputToConsole;
36
37
    /**
38
     * @param bool $isOutputToConsole
39
     */
40
    public function __construct(bool $isOutputToConsole = true)
41
    {
42
        $this->isOutputToConsole = $isOutputToConsole;
43
    }
44
45
    /**
46
     * @return void
47
     */
48
    public function run(): void
49
    {
50
        $validator = v::validator([
51
            'sku'           => r::required(r::sku()),
52
            'amount'        => r::required(r::amount(5)),
53
            'delivery_date' => r::nullable(r::deliveryDate()),
54
            'email'         => r::email(),
55
            'address1'      => r::required(r::address1()),
56
            'address2'      => r::address2(),
57
            'accepted'      => r::required(r::areTermsAccepted()),
58
        ]);
59
60
        // Check with invalid data
61
        $invalidInput = [
62
            'sku'           => '123',
63
            'amount'        => '10',
64
            'delivery_date' => '2001-01-01',
65
            'email'         => 'john.dow',
66
            // 'address1'   => 'Dow 1', // missed required parameter
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
67
            'accepted'      => 'false',
68
        ];
69
        $this->console('Invalid data (errors)' . PHP_EOL);
70
        $validator->validate($invalidInput);
71
        $this->printErrors($validator->getErrors());
0 ignored issues
show
Documentation introduced by
$validator->getErrors() is of type array<integer,object<Lim...Errors\ErrorInterface>>, but the function expects a object<Sample\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
        $this->console('Invalid data (captures)' . PHP_EOL);
73
        $this->printCaptures($validator->getCaptures());
0 ignored issues
show
Documentation introduced by
$validator->getCaptures() is of type array, but the function expects a object<Sample\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
74
75
        // Check with valid data
76
        $validInput = [
77
            'sku'           => '1',
78
            'amount'        => '3',
79
            'delivery_date' => (new DateTime('+2 days'))->format(DateTime::ISO8601),
80
            'email'         => '[email protected]',
81
            'address1'      => 'Dow 1',
82
            'address2'      => null,
83
            'accepted'      => 'true',
84
        ];
85
        $this->console(PHP_EOL . 'Valid data (errors)' . PHP_EOL);
86
        $validator->validate($validInput);
87
        $this->printErrors($validator->getErrors());
0 ignored issues
show
Documentation introduced by
$validator->getErrors() is of type array<integer,object<Lim...Errors\ErrorInterface>>, but the function expects a object<Sample\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
88
        $this->console('Valid data (captures)' . PHP_EOL);
89
        $this->printCaptures($validator->getCaptures());
0 ignored issues
show
Documentation introduced by
$validator->getCaptures() is of type array, but the function expects a object<Sample\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
90
91
        // The output would be
92
        // -------------------------------------------------------------------------------------------------------
93
        // Invalid data (errors)
94
        // Param `sku` failed for `123` with: The value should be a valid SKU.
95
        // Param `amount` failed for `10` with: The value should be between 1 and 5.
96
        // Param `delivery_date` failed for `2001-01-01` with: The value should be a valid date time.
97
        // Param `email` failed for `john.dow` with: The value should be a valid email address.
98
        // Param `accepted` failed for `` with: The value should be equal to 1.
99
        // Param `address1` failed for `` with: The value is required.
100
        // Invalid data (captures)
101
        // No captures
102
        
103
        // Valid data (errors)
104
        // No errors
105
        // Valid data (captures)
106
        // `sku` = `1` (integer)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
107
        // `amount` = `3` (integer)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
108
        // `delivery_date` = `2018-01-04T15:07:33+0100` (object)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
109
        // `email` = `[email protected]` (string)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
110
        // `address1` = `Dow 1` (string)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
111
        // `address2` = `` (NULL)
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
112
        // `accepted` = `1` (boolean)
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
113
        // -------------------------------------------------------------------------------------------------------
114
    }
115
116
    /**
117
     * @param iterable $errors
118
     *
119
     * @return void
120
     */
121
    private function printErrors(iterable $errors): void
122
    {
123
        $hasErrors = false;
124
125
        foreach ($errors as $error) {
126
            $hasErrors = true;
127
128
            /** @var ErrorInterface $error */
129
            $paramName  = $error->getParameterName();
130
            $entry      = empty($paramName) ? 'Validation' : "Param `$paramName`";
131
            $paramValue = $error->getParameterValue();
132
            $errorMsg   = Errors::MESSAGES[$error->getMessageCode()];
133
            $context    = $error->getMessageContext();
134
            $errorMsg   = MessageFormatter::formatMessage('en', $errorMsg, $context !== null ? $context : []);
135
    
136
            $this->console("$entry failed for `$paramValue` with: $errorMsg" . PHP_EOL);
137
        }
138
139
        if ($hasErrors === false) {
140
            $this->console('No errors' . PHP_EOL);
141
        }
142
    }
143
144
    /**
145
     * @param iterable $captures
146
     *
147
     * @return void
148
     */
149
    private function printCaptures(iterable $captures): void
150
    {
151
        $hasCaptures = false;
152
153
        foreach ($captures as $name => $value) {
154
            $hasCaptures = true;
155
            $type        = gettype($value);
156
            $value       = $value instanceof DateTimeInterface ? $value->format(DateTime::ISO8601) : $value;
157
            $this->console("`$name` = `$value` ($type)" . PHP_EOL);
158
        }
159
160
        if ($hasCaptures === false) {
161
            $this->console('No captures' . PHP_EOL);
162
        }
163
    }
164
165
    /**
166
     * @param string $string
167
     */
168
    private function console(string $string): void
169
    {
170
        if ($this->isOutputToConsole === true) {
171
            echo $string;
172
        }
173
    }
174
}
175