BaseTest::createValidator()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 80
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 80
rs 8.8387
c 0
b 0
f 0
cc 1
eloc 56
nc 1
nop 2

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
2
3
namespace Vvval\Spiral\Validation\Tests;
4
5
use Interop\Container\ContainerInterface;
6
use Monolog\Handler\NullHandler;
7
use PHPUnit\Framework\TestCase;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\LoggerTrait;
10
use Psr\Log\LogLevel;
11
use Spiral\Core\Container;
12
use Spiral\Core\Traits\SharedTrait;
13
use Spiral\Translator\TranslatorInterface;
14
use Spiral\Validation\CheckerInterface;
15
use Spiral\Validation\Configs\ValidatorConfig;
16
use Spiral\Validation\Validator;
17
use Vvval\Spiral\Validation\Checkers\EntityChecker;
18
use Vvval\Spiral\Validation\Checkers\FieldsChecker;
19
use Vvval\Spiral\Validation\Checkers\RegistryChecker;
20
21
/**
22
 * @property \Spiral\Core\MemoryInterface             $memory
23
 * @property \Spiral\Core\ContainerInterface          $container
24
 * @property \Spiral\Debug\LogsInterface              $logs
25
 * @property \Spiral\Http\HttpDispatcher              $http
26
 * @property \Spiral\Console\ConsoleDispatcher        $console
27
 * @property \Spiral\Console\ConsoleDispatcher        $commands
28
 * @property \Spiral\Files\FilesInterface             $files
29
 * @property \Spiral\Tokenizer\TokenizerInterface     $tokenizer
30
 * @property \Spiral\Tokenizer\ClassesInterface       $locator
31
 * @property \Spiral\Tokenizer\InvocationsInterface   $invocationLocator
32
 * @property \Spiral\Views\ViewManager                $views
33
 * @property \Spiral\Translator\Translator            $translator
34
 * @property \Spiral\Database\DatabaseManager         $dbal
35
 * @property \Spiral\ORM\ORM                          $orm
36
 * @property \Spiral\Encrypter\EncrypterInterface     $encrypter
37
 * @property \Spiral\Database\Entities\Database       $db
38
 * @property \Spiral\Http\Cookies\CookieQueue         $cookies
39
 * @property \Spiral\Http\Routing\RouterInterface     $router
40
 * @property \Spiral\Pagination\PaginatorsInterface   $paginators
41
 * @property \Psr\Http\Message\ServerRequestInterface $request
42
 * @property \Spiral\Http\Request\InputManager        $input
43
 * @property \Spiral\Http\Response\ResponseWrapper    $response
44
 * @property \Spiral\Http\Routing\RouteInterface      $route
45
 * @property \Spiral\Security\PermissionsInterface    $permissions
46
 * @property \Spiral\Security\RulesInterface          $rules
47
 * @property \Spiral\Security\ActorInterface          $actor
48
 * @property \Spiral\Session\SessionInterface         $session
49
 */
50
abstract class BaseTest extends TestCase
51
{
52
    use SharedTrait;
53
54
    /**
55
     * @var TestApplication
56
     */
57
    protected $app;
58
59
    public function setUp()
60
    {
61
        $root = __DIR__ . '/-app-/';
62
        $this->app = TestApplication::init(
0 ignored issues
show
Documentation Bug introduced by
It seems like \Vvval\Spiral\Validation.../'), null, null, false) of type object<self> is incompatible with the declared type object<Vvval\Spiral\Vali...\Tests\TestApplication> of property $app.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
63
            [
64
                'root'        => $root,
65
                'libraries'   => dirname(__DIR__) . '/vendor/',
66
                'application' => $root,
67
                'framework'   => dirname(__DIR__) . '/source/',
68
                'runtime'     => $root . 'runtime/',
69
                'cache'       => $root . 'runtime/cache/',
70
            ],
71
            null,
72
            null,
73
            false
74
        );
75
76
        //Monolog love to write to CLI when no handler set
77
        $this->app->logs->debugHandler(new NullHandler());
78
        $this->app->container->bind('factory', $this->app->container);
79
80
        $files = $this->app->files;
81
82
        //Ensure runtime is clean
83
        foreach ($files->getFiles($this->app->directory('runtime')) as $filename) {
84
            //If exception is thrown here this will mean that application wasn't correctly
85
            //destructed and there is open resources kept
86
            $files->delete($filename);
87
        }
88
89
        $builder = $this->orm->schemaBuilder(true);
90
        $builder->renderSchema();
91
        $builder->pushSchema();
92
        $this->orm->setSchema($builder);
93
94
        if ($this->app->getEnvironment()->get('DEBUG')) {
95
            $this->app->db->getDriver()->setLogger(new class implements LoggerInterface
96
            {
97
                use LoggerTrait;
98
99
                public function log($level, $message, array $context = [])
100
                {
101
                    if ($level == LogLevel::ERROR) {
102
                        echo " \n! \033[31m" . $message . "\033[0m";
103
                    } elseif ($level == LogLevel::ALERT) {
104
                        echo " \n! \033[35m" . $message . "\033[0m";
105
                    } elseif (strpos($message, 'PRAGMA') === 0) {
106
                        echo " \n> \033[34m" . $message . "\033[0m";
107
                    } else {
108
                        if (strpos($message, 'SELECT') === 0) {
109
                            echo " \n> \033[32m" . $message . "\033[0m";
110
                        } else {
111
                            echo " \n> \033[33m" . $message . "\033[0m";
112
                        }
113
                    }
114
                }
115
            });
116
        }
117
118
        clearstatcache();
119
120
        //Open application scope
121
        TestApplication::shareContainer($this->app->container);
122
    }
123
124
    /**
125
     * This method performs full destroy of spiral environment.
126
     */
127
    public function tearDown()
128
    {
129
        \Mockery::close();
130
131
        TestApplication::shareContainer(null);
132
133
        //Forcing destruction
134
        $this->app = null;
135
136
        gc_collect_cycles();
137
        clearstatcache();
138
    }
139
140
    /**
141
     * @return \Spiral\Core\ContainerInterface
142
     */
143
    protected function iocContainer()
144
    {
145
        return $this->app->container;
146
    }
147
148
    /**
149
     * @param array $rules
150
     * @param array $data
151
     *
152
     * @return Validator
153
     */
154
    protected function createValidator(array $rules, array $data = [])
155
    {
156
        $config = new ValidatorConfig([
157
            /*
158
               * Set of empty conditions which tells Validator what rules to be counted as "stop if empty",
159
               * without such condition field validations will be skipped if value is empty.
160
               */
161
            'emptyConditions' => [
162
                "notEmpty",
163
                "required",
164
                "type::notEmpty",
165
                "required::with",
166
                "required::without",
167
                "required::withAll",
168
                "required::withoutAll",
169
                "file::exists",
170
                "file::uploaded",
171
                "image::exists",
172
                "image::uploaded",
173
                "registry::anyValue",
174
                /*{{empties}}*/
175
            ],
176
            /*
177
             * Checkers are resolved using container and provide ability to isolate some validation rules
178
             * under common name and class. You can register new checkers at any moment without any
179
             * performance issues.
180
             */
181
            'checkers'        => [
182
                "registry" => RegistryChecker::class,
183
                "entity"   => EntityChecker::class,
184
                "fields"   => FieldsChecker::class,
185
                /*{{checkers}}*/
186
            ],
187
            /*
188
             * Aliases are only used to simplify developer life.
189
             */
190
            'aliases'         => [
191
                "notEmpty"   => "type::notEmpty",
192
                "required"   => "type::notEmpty",
193
                "datetime"   => "type::datetime",
194
                "timezone"   => "type::timezone",
195
                "bool"       => "type::boolean",
196
                "boolean"    => "type::boolean",
197
                "cardNumber" => "mixed::cardNumber",
198
                "regexp"     => "string::regexp",
199
                "email"      => "address::email",
200
                "url"        => "address::url",
201
                "file"       => "file::exists",
202
                "uploaded"   => "file::uploaded",
203
                "filesize"   => "file::size",
204
                "image"      => "image::valid",
205
                "array"      => "is_array",
206
                "callable"   => "is_callable",
207
                "double"     => "is_double",
208
                "float"      => "is_float",
209
                "int"        => "is_int",
210
                "integer"    => "is_integer",
211
                "numeric"    => "is_numeric",
212
                "long"       => "is_long",
213
                "null"       => "is_null",
214
                "object"     => "is_object",
215
                "real"       => "is_real",
216
                "resource"   => "is_resource",
217
                "scalar"     => "is_scalar",
218
                "string"     => "is_string",
219
                "match"      => "mixed::match",
220
                /*{{aliases}}*/
221
            ]
222
        ]);
223
224
        $translator = \Mockery::mock(TranslatorInterface::class);
225
        $translator->shouldReceive('resolveDomain')->andReturn('domain');
226
        $translator->shouldReceive('trans')->andReturn('error');
227
228
        $container = new Container();
229
        $container->bind(ContainerInterface::class, $container);
0 ignored issues
show
Documentation introduced by
$container is of type object<Spiral\Core\Container>, but the function expects a callable.

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...
230
        $container->bind(TranslatorInterface::class, $translator);
231
232
        return new Validator($rules, $data, $config, $container);
233
    }
234
}