BaseTest::iocContainer()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spiral\Tests;
4
5
use Monolog\Handler\NullHandler;
6
use PHPUnit\Framework\TestCase;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\LoggerTrait;
9
use Psr\Log\LogLevel;
10
use Spiral\Core\Traits\SharedTrait;
11
use Spiral\Database\Builders\SelectQuery;
12
use Spiral\Debug\Snapshot;
13
use Spiral\Snapshotter\Bootloaders\FileHandlerBootloader;
14
use Spiral\Snapshotter\DelegateSnapshot;
15
use Spiral\Snapshotter\AggregationHandler\Database\SnapshotRecord;
16
use Spiral\Snapshotter\AggregationHandler;
17
18
/**
19
 * @property \Spiral\Core\MemoryInterface             $memory
20
 * @property \Spiral\Core\ContainerInterface          $container
21
 * @property \Spiral\Debug\LogsInterface              $logs
22
 * @property \Spiral\Http\HttpDispatcher              $http
23
 * @property \Spiral\Console\ConsoleDispatcher        $console
24
 * @property \Spiral\Console\ConsoleDispatcher        $commands
25
 * @property \Spiral\Files\FilesInterface             $files
26
 * @property \Spiral\Tokenizer\TokenizerInterface     $tokenizer
27
 * @property \Spiral\Tokenizer\ClassesInterface       $locator
28
 * @property \Spiral\Tokenizer\InvocationsInterface   $invocationLocator
29
 * @property \Spiral\Views\ViewManager                $views
30
 * @property \Spiral\Translator\Translator            $translator
31
 * @property \Spiral\Database\DatabaseManager         $dbal
32
 * @property \Spiral\ORM\ORM                          $orm
33
 * @property \Spiral\Encrypter\EncrypterInterface     $encrypter
34
 * @property \Spiral\Database\Entities\Database       $db
35
 * @property \Spiral\Http\Cookies\CookieQueue         $cookies
36
 * @property \Spiral\Http\Routing\RouterInterface     $router
37
 * @property \Spiral\Pagination\PaginatorsInterface   $paginators
38
 * @property \Psr\Http\Message\ServerRequestInterface $request
39
 * @property \Spiral\Http\Request\InputManager        $input
40
 * @property \Spiral\Http\Response\ResponseWrapper    $response
41
 * @property \Spiral\Http\Routing\RouteInterface      $route
42
 * @property \Spiral\Security\PermissionsInterface    $permissions
43
 * @property \Spiral\Security\RulesInterface          $rules
44
 * @property \Spiral\Security\ActorInterface          $actor
45
 * @property \Spiral\Session\SessionInterface         $session
46
 */
47
abstract class BaseTest extends TestCase
48
{
49
    use SharedTrait;
50
51
    /**
52
     * @var TestApplication
53
     */
54
    protected $app;
55
56
    public function setUp()
57
    {
58
        $root = __DIR__ . '/-app-/';
59
        $this->app = TestApplication::init(
0 ignored issues
show
Documentation Bug introduced by
It seems like \Spiral\Tests\TestApplic.../'), null, null, false) of type object<self> is incompatible with the declared type object<Spiral\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...
60
            [
61
                'root'        => $root,
62
                'libraries'   => dirname(__DIR__) . '/vendor/',
63
                'application' => $root,
64
                'framework'   => dirname(__DIR__) . '/source/',
65
                'runtime'     => $root . 'runtime/',
66
                'cache'       => $root . 'runtime/cache/',
67
            ],
68
            null,
69
            null,
70
            false
71
        );
72
73
        //Monolog love to write to CLI when no handler set
74
        $this->app->logs->debugHandler(new NullHandler());
75
        $this->app->container->bind('factory', $this->app->container);
76
77
        $files = $this->app->files;
78
79
        //Ensure runtime is clean
80
        foreach ($files->getFiles($this->app->directory('runtime')) as $filename) {
81
            //If exception is thrown here this will mean that application wasn't correctly
82
            //destructed and there is open resources kept
83
            $files->delete($filename);
84
        }
85
86
        $builder = $this->orm->schemaBuilder(true);
87
        $builder->renderSchema();
88
        $builder->pushSchema();
89
        $this->orm->setSchema($builder);
90
91
        if ($this->app->getEnvironment()->get('DEBUG')) {
92
            $this->app->db->getDriver()->setLogger(new class implements LoggerInterface
93
            {
94
                use LoggerTrait;
95
96
                public function log($level, $message, array $context = [])
97
                {
98
                    if ($level == LogLevel::ERROR) {
99
                        echo " \n! \033[31m" . $message . "\033[0m";
100
                    } elseif ($level == LogLevel::ALERT) {
101
                        echo " \n! \033[35m" . $message . "\033[0m";
102
                    } elseif (strpos($message, 'PRAGMA') === 0) {
103
                        echo " \n> \033[34m" . $message . "\033[0m";
104
                    } else {
105
                        if (strpos($message, 'SELECT') === 0) {
106
                            echo " \n> \033[32m" . $message . "\033[0m";
107
                        } else {
108
                            echo " \n> \033[33m" . $message . "\033[0m";
109
                        }
110
                    }
111
                }
112
            });
113
        }
114
115
        clearstatcache();
116
117
        //Open application scope
118
        TestApplication::shareContainer($this->app->container);
119
    }
120
121
    /**
122
     * This method performs full destroy of spiral environment.
123
     */
124
    public function tearDown()
125
    {
126
        \Mockery::close();
127
128
        TestApplication::shareContainer(null);
129
130
        //Forcing destruction
131
        $this->app = null;
132
133
        gc_collect_cycles();
134
        clearstatcache();
135
    }
136
137
    /**
138
     * @return \Spiral\Core\ContainerInterface
139
     */
140
    protected function iocContainer()
141
    {
142
        return $this->app->container;
143
    }
144
145
    /**
146
     * @param string $message
147
     * @param int    $code
148
     * @return Snapshot
149
     */
150
    protected function makeSnapshot(string $message, int $code): Snapshot
151
    {
152
        return $this->factory->make(Snapshot::class, [
0 ignored issues
show
Documentation introduced by
The property factory does not exist on object<Spiral\Tests\BaseTest>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
153
            'exception' => new \Error($message, $code)
0 ignored issues
show
Unused Code introduced by
The call to Error::__construct() has too many arguments starting with $message.

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...
154
        ]);
155
    }
156
157
    /**
158
     * @param Snapshot $snapshot
159
     * @param bool     $report
160
     * @return SnapshotRecord
161
     */
162
    protected function handleSnapshot(Snapshot $snapshot, bool $report = true): SnapshotRecord
163
    {
164
        /** @var DelegateSnapshot $delegate */
165
        $delegate = $this->factory->make(DelegateSnapshot::class, [
0 ignored issues
show
Documentation introduced by
The property factory does not exist on object<Spiral\Tests\BaseTest>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
166
            'exception' => $snapshot->getException(),
167
            'handler'   => bind(AggregationHandler::class)
168
        ]);
169
170
        if ($report) {
171
            $delegate->report();
172
        }
173
174
        return $this->orm->source(SnapshotRecord::class)->findOne(
175
            [],
176
            ['id' => SelectQuery::SORT_DESC]
177
        );
178
    }
179
180
    /**
181
     * @param Snapshot $snapshot
182
     * @param bool     $report
183
     */
184
    protected function handleFileSnapshot(Snapshot $snapshot, bool $report = true)
185
    {
186
        $this->app->getBootloader()->bootload([FileHandlerBootloader::class]);
187
188
        /** @var DelegateSnapshot $delegate */
189
        $delegate = $this->factory->make(DelegateSnapshot::class, [
0 ignored issues
show
Documentation introduced by
The property factory does not exist on object<Spiral\Tests\BaseTest>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
190
            'exception' => $snapshot->getException()
191
        ]);
192
193
        if ($report) {
194
            $delegate->report();
195
        }
196
    }
197
}