-
Notifications
You must be signed in to change notification settings - Fork 0
/
SetupApplicationTrait.php
94 lines (76 loc) · 2.67 KB
/
SetupApplicationTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace Zfegg\ExpressiveTest\Helper;
use Composer\Autoload\ClassLoader;
use Laminas\Stratigility\Middleware\ErrorHandler;
use Mezzio\Application;
use Mezzio\MiddlewareFactory;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use ReflectionClass;
use Zfegg\ExpressiveTest\MockRequestFactory;
use Zfegg\ExpressiveTest\PassMiddleware;
trait SetupApplicationTrait
{
/**
* @var ContainerInterface|\Laminas\ServiceManager\ServiceManager
*/
protected $container;
protected function getProjectDir(): string
{
$reflector = new ReflectionClass(ClassLoader::class);
$file = $reflector->getFileName();
return realpath(dirname($file) . '/../../');
}
public function loadContainer(): ContainerInterface
{
if ($this->container) {
return $this->container;
}
$projectRoot = $this->getProjectDir();
$containerFile = $projectRoot . '/config/container.php';
if (file_exists($containerFile)) {
$this->container = include $containerFile;
return $this->container;
}
throw new \RuntimeException('Load container error.');
}
protected function setUp(): void
{
chdir($this->getProjectDir());
$this->container = $this->loadContainer();
$this->container->setAllowOverride(true);
$this->container->setService(ErrorHandler::class, new PassMiddleware());
$this->container->addDelegator(
Application::class,
function ($container, $name, callable $callback) {
$app = $callback();
$factory = $container->get(MiddlewareFactory::class);
$projectRoot = $this->getProjectDir();
foreach (['pipeline', 'routes'] as $file) {
$file = $projectRoot . "/config/$file.php";
if (file_exists($file)) {
(require $file)($app, $factory, $container);
}
}
return $app;
}
);
}
public function runApp(
string $method,
string $requestUri,
array $parsedBody = [],
array $servers = [],
$body = null,
array $cookies = [],
array $files = []
): ResponseInterface {
$servers['REQUEST_METHOD'] = $method;
$servers['REQUEST_URI'] = $requestUri;
$request = MockRequestFactory::create($servers, $parsedBody, $body, $cookies, $files);
/** @var \Mezzio\Application $app */
$app = $this->container->get(Application::class);
return $app->handle($request);
}
}