This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
forked from samsonasik/expressive-composer-installer
/
ProjectSandboxTrait.php
304 lines (260 loc) · 9 KB
/
ProjectSandboxTrait.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<?php
/**
* @see https://github.com/zendframework/zend-expressive-installer for the canonical source repository
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-expressive-installer/blob/master/LICENSE.md New BSD License
*/
declare(strict_types=1);
namespace ExpressiveInstallerTest;
use App\Action\HomePageAction;
use App\Action\PingAction;
use DirectoryIterator;
use ExpressiveInstaller\OptionalPackages;
use PHPUnit\Framework\Assert;
use Psr\Container\ContainerInterface;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequest;
use Zend\Expressive\Application;
use Zend\Expressive\Helper\ServerUrlMiddleware;
use Zend\Expressive\Helper\UrlHelperMiddleware;
use Zend\Expressive\Middleware\ImplicitHeadMiddleware;
use Zend\Expressive\Middleware\ImplicitOptionsMiddleware;
use Zend\Expressive\Middleware\NotFoundHandler;
use Zend\Stratigility\Middleware\ErrorHandler;
trait ProjectSandboxTrait
{
/**
* @var null|callable Additional autoloader to prepend to stack.
* Used when flat install is requested.
*/
protected $autoloader;
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var string Root of the sandbox system
*/
protected $projectRoot;
/**
* Copies the project files into a temporary filesystem.
*
* Sets the path to the new temporary filesystem in the $projectRoot
* property, changes the working directory to that new location, and
* returns the location.
*
* cleanup() recursively removes the created directory.
*/
protected function copyProjectFilesToTempFilesystem()
{
$this->projectRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('exp');
mkdir($this->projectRoot . '/data', 0777, true);
foreach (['config', 'public', 'src', 'templates', 'test'] as $path) {
$this->recursiveCopy(
$this->packageRoot . DIRECTORY_SEPARATOR . $path,
$this->projectRoot . DIRECTORY_SEPARATOR . $path
);
}
chdir($this->projectRoot);
return $this->projectRoot;
}
/**
* Prepare the sandbox for the selected instalation type.
*
* Sets the installer's install type, and sets up the application structure.
*
* If a non-minimal install type is selected, also sets up the alternate
* autoloader to ensure the `App` namespace resolves correctly.
*
* @param string $installType
* @param OptionalPackages $installer
*/
protected function prepareSandboxForInstallType($installType, OptionalPackages $installer)
{
$installer->setInstallType($installType);
$installer->setupDefaultApp($installType);
switch ($installType) {
case OptionalPackages::INSTALL_FLAT:
$this->setUpAlternateAutoloader('/src/');
break;
case OptionalPackages::INSTALL_MODULAR:
$this->setUpAlternateAutoloader('/src/App/src/', true);
break;
}
}
/**
* Enable development-mode configuration within the sandbox.
*/
protected function enableDevelopmentMode()
{
$target = sprintf(
'%s%sconfig%sdevelopment.config.php',
$this->projectRoot,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR
);
copy($target . '.dist', $target);
Assert::assertFileExists($target);
$target = sprintf(
'%s%sconfig%sautoload%sdevelopment.local.php',
$this->projectRoot,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR
);
copy($target . '.dist', $target);
Assert::assertFileExists($target);
}
/**
* Adds an alternate autoloader to the stack for the App namespace.
*
* Required, as the tests will load classes from that namespace, but the
* class files will exist in temporary directories.
*
* Any test that uses this (and it's implicit when using setInstallType())
* MUST run in a separate process.
*
* tearDown() unregisters the autoloader.
*
* @param string $appPath The path to the App namespace source code,
* relative to the project root.
* @param bool $stripNamespace Whether or not to strip the initial
* namespace when determining the path (ala PSR-4).
*/
protected function setUpAlternateAutoloader($appPath, $stripNamespace = false)
{
$this->autoloader = function ($class) use ($appPath, $stripNamespace) {
if (0 !== strpos($class, 'App\\')) {
return false;
}
$class = $stripNamespace
? str_replace('App\\', '', $class)
: $class;
$path = $this->projectRoot
. $appPath
. str_replace('\\', '/', $class)
. '.php';
if (! file_exists($path)) {
return false;
}
include $path;
};
spl_autoload_register($this->autoloader, true, true);
}
/**
* Remove the alternate autolader, if present.
*/
protected function tearDownAlternateAutoloader()
{
if ($this->autoloader) {
spl_autoload_unregister($this->autoloader);
unset($this->autoloader);
}
}
/**
* Returns the configured container for the sandbox project.
*
* @return ContainerInterface;
*/
protected function getContainer()
{
if ($this->container) {
return $this->container;
}
$path = $this->projectRoot
? $this->projectRoot . '/config/container.php'
: 'config/container.php';
/** @var ContainerInterface $container */
$this->container = require $path;
return $this->container;
}
/**
* Creates and dispatches an application at the requested path.
*
* @param string $path Path to request within the application
* @param bool $setupRoutes Whether or not to setup routes before dispatch
* @return Response
*/
protected function getAppResponse($path = '/', $setupRoutes = true)
{
$container = $this->getContainer();
/** @var Application $app */
$app = $container->get(Application::class);
// Import programmatic/declarative middleware pipeline and routing configuration statements
$app->pipe(ErrorHandler::class);
$app->pipe(ServerUrlMiddleware::class);
$app->pipeRoutingMiddleware();
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(ImplicitOptionsMiddleware::class);
$app->pipe(UrlHelperMiddleware::class);
$app->pipeDispatchMiddleware();
$app->pipe(NotFoundHandler::class);
if ($setupRoutes === true && $container->has(HomePageAction::class)) {
$app->get('/', HomePageAction::class, 'home');
}
if ($setupRoutes === true && $container->has(PingAction::class)) {
$app->get('/api/ping', PingAction::class, 'api.ping');
}
return $app(
new ServerRequest([], [], 'https://example.com' . $path, 'GET'),
new Response(),
$app->getDefaultDelegate()
);
}
/**
* Recursively copy the files from one tree to another.
*
* @param string $source Source tree to copy.
* @param string $target Target tree to copy into.
*/
protected function recursiveCopy($source, $target)
{
if (! is_dir($target)) {
mkdir($target, 0777, true);
}
if (! is_dir($source)) {
return;
}
$dir = new DirectoryIterator($source);
foreach ($dir as $fileInfo) {
if ($fileInfo->isFile()) {
$realPath = $fileInfo->getRealPath();
$path = ltrim(str_replace($source, '', $realPath), '/\\');
copy($realPath, sprintf('%s/%s', $target, $path));
continue;
}
if ($fileInfo->isDir() && ! $fileInfo->isDot()) {
$path = $fileInfo->getFilename();
mkdir($target . '/' . $path, 0777, true);
$this->recursiveCopy(
$source . DIRECTORY_SEPARATOR . $path,
$target . DIRECTORY_SEPARATOR . $path
);
continue;
}
}
}
/**
* Recursively remove a filesystem tree.
*
* @param string $target Tree to remove.
*/
protected function recursiveDelete($target)
{
if (! is_dir($target)) {
return;
}
foreach (scandir($target) as $node) {
if (in_array($node, ['.', '..'], true)) {
continue;
}
$path = sprintf('%s/%s', $target, $node);
if (is_dir($path)) {
$this->recursiveDelete($path);
continue;
}
unlink($path);
}
rmdir($target);
}
}