This repository has been archived by the owner on Jan 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 165
/
ScriptHandler.php
598 lines (500 loc) · 22.8 KB
/
ScriptHandler.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sensio\Bundle\DistributionBundle\Composer;
use Symfony\Component\ClassLoader\ClassCollectionLoader;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use Composer\Script\Event;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ScriptHandler
{
/**
* Composer variables are declared static so that an event could update
* a composer.json and set new options, making them immediately available
* to forthcoming listeners.
*/
protected static $options = array(
'symfony-app-dir' => 'app',
'symfony-web-dir' => 'web',
'symfony-assets-install' => 'hard',
'symfony-cache-warmup' => false,
);
/**
* Asks if the new directory structure should be used, installs the structure if needed.
*
* @param Event $event
*/
public static function defineDirectoryStructure(Event $event)
{
$options = static::getOptions($event);
if (!getenv('SENSIOLABS_ENABLE_NEW_DIRECTORY_STRUCTURE') || !$event->getIO()->askConfirmation('Would you like to use Symfony 3 directory structure? [y/N] ', false)) {
return;
}
$rootDir = getcwd();
$appDir = $options['symfony-app-dir'];
$webDir = $options['symfony-web-dir'];
$binDir = static::$options['symfony-bin-dir'] = 'bin';
$varDir = static::$options['symfony-var-dir'] = 'var';
static::updateDirectoryStructure($event, $rootDir, $appDir, $binDir, $varDir, $webDir);
}
/**
* Builds the bootstrap file.
*
* The bootstrap file contains PHP file that are always needed by the application.
* It speeds up the application bootstrapping.
*
* @param Event $event
*/
public static function buildBootstrap(Event $event)
{
$options = static::getOptions($event);
$bootstrapDir = $autoloadDir = $options['symfony-app-dir'];
if (static::useNewDirectoryStructure($options)) {
$bootstrapDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $bootstrapDir, 'build bootstrap file')) {
return;
}
}
if (!static::hasDirectory($event, 'symfony-app-dir', $autoloadDir, 'build bootstrap file')) {
return;
}
static::executeBuildBootstrap($event, $bootstrapDir, $autoloadDir, $options['process-timeout']);
}
protected static function hasDirectory(Event $event, $configName, $path, $actionName)
{
if (!is_dir($path)) {
$event->getIO()->write(sprintf('The %s (%s) specified in composer.json was not found in %s, can not %s.', $configName, $path, getcwd(), $actionName));
return false;
}
return true;
}
/**
* Sets up deployment target specific features.
* Could be custom web server configs, boot command files etc.
*
* @param Event $event
*/
public static function prepareDeploymentTarget(Event $event)
{
static::prepareDeploymentTargetHeroku($event);
}
protected static function prepareDeploymentTargetHeroku(Event $event)
{
$options = static::getOptions($event);
if (($stack = getenv('STACK')) && ($stack == 'cedar' || $stack == 'cedar-14')) {
$fs = new Filesystem();
if (!$fs->exists('Procfile')) {
$event->getIO()->write('Heroku deploy detected; creating default Procfile for "web" dyno');
$fs->dumpFile('Procfile', sprintf('web: $(composer config bin-dir)/heroku-php-apache2 %s/', $options['symfony-web-dir']));
}
}
}
/**
* Clears the Symfony cache.
*
* @param Event $event
*/
public static function clearCache(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'clear the cache');
if (null === $consoleDir) {
return;
}
$warmup = '';
if (!$options['symfony-cache-warmup']) {
$warmup = ' --no-warmup';
}
static::executeCommand($event, $consoleDir, 'cache:clear'.$warmup, $options['process-timeout']);
}
/**
* Installs the assets under the web root directory.
*
* For better interoperability, assets are copied instead of symlinked by default.
*
* Even if symlinks work on Windows, this is only true on Windows Vista and later,
* but then, only when running the console with admin rights or when disabling the
* strict user permission checks (which can be done on Windows 7 but not on Windows
* Vista).
*
* @param Event $event
*/
public static function installAssets(Event $event)
{
$options = static::getOptions($event);
$consoleDir = static::getConsoleDir($event, 'install assets');
if (null === $consoleDir) {
return;
}
$webDir = $options['symfony-web-dir'];
$symlink = '';
if ($options['symfony-assets-install'] == 'symlink') {
$symlink = '--symlink ';
} elseif ($options['symfony-assets-install'] == 'relative') {
$symlink = '--symlink --relative ';
}
if (!static::hasDirectory($event, 'symfony-web-dir', $webDir, 'install assets')) {
return;
}
static::executeCommand($event, $consoleDir, 'assets:install '.$symlink.escapeshellarg($webDir), $options['process-timeout']);
}
/**
* Updated the requirements file.
*
* @param Event $event
*/
public static function installRequirementsFile(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
$fs = new Filesystem();
$newDirectoryStructure = static::useNewDirectoryStructure($options);
if (!$newDirectoryStructure) {
if (!static::hasDirectory($event, 'symfony-app-dir', $appDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $appDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $appDir.'/check.php', true);
} else {
$binDir = $options['symfony-bin-dir'];
$varDir = $options['symfony-var-dir'];
if (!static::hasDirectory($event, 'symfony-var-dir', $varDir, 'install the requirements files')) {
return;
}
if (!static::hasDirectory($event, 'symfony-bin-dir', $binDir, 'install the requirements files')) {
return;
}
$fs->copy(__DIR__.'/../Resources/skeleton/app/SymfonyRequirements.php', $varDir.'/SymfonyRequirements.php', true);
$fs->copy(__DIR__.'/../Resources/skeleton/app/check.php', $binDir.'/symfony_requirements', true);
$fs->remove(array($appDir.'/check.php', $appDir.'/SymfonyRequirements.php', true));
$fs->dumpFile($binDir.'/symfony_requirements', '#!/usr/bin/env php'.PHP_EOL.str_replace(".'/SymfonyRequirements.php'", ".'/".$fs->makePathRelative($varDir, $binDir)."SymfonyRequirements.php'", file_get_contents($binDir.'/symfony_requirements')));
$fs->chmod($binDir.'/symfony_requirements', 0755);
}
$webDir = $options['symfony-web-dir'];
// if the user has already removed the config.php file, do nothing
// as the file must be removed for production use
if ($fs->exists($webDir.'/config.php')) {
if (!$newDirectoryStructure) {
$fs->copy(__DIR__.'/../Resources/skeleton/web/config.php', $webDir.'/config.php', true);
} else {
$fs->dumpFile($webDir.'/config.php', str_replace('/../app/SymfonyRequirements.php', '/'.$fs->makePathRelative($varDir, $webDir).'SymfonyRequirements.php', file_get_contents(__DIR__.'/../Resources/skeleton/web/config.php')));
}
}
}
public static function removeSymfonyStandardFiles(Event $event)
{
$options = static::getOptions($event);
$appDir = $options['symfony-app-dir'];
if (!is_dir($appDir)) {
return;
}
if (!is_dir($appDir.'/SymfonyStandard')) {
return;
}
$fs = new Filesystem();
$fs->remove($appDir.'/SymfonyStandard');
}
public static function installAcmeDemoBundle(Event $event)
{
$rootDir = getcwd();
$options = static::getOptions($event);
if (file_exists($rootDir.'/src/Acme/DemoBundle')) {
return;
}
if (!getenv('SENSIOLABS_FORCE_ACME_DEMO')) {
if (!$event->getIO()->askConfirmation('Would you like to install Acme demo bundle? [y/N] ', false)) {
return;
}
}
$event->getIO()->write('Installing the Acme demo bundle.');
$appDir = $options['symfony-app-dir'];
$kernelFile = $appDir.'/AppKernel.php';
$fs = new Filesystem();
$fs->mirror(__DIR__.'/../Resources/skeleton/acme-demo-bundle', $rootDir.'/src', null, array('override' => true));
$ref = '$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();';
$bundleDeclaration = "\$bundles[] = new Acme\\DemoBundle\\AcmeDemoBundle();";
$content = file_get_contents($kernelFile);
if (false === strpos($content, $bundleDeclaration)) {
$updatedContent = str_replace($ref, $bundleDeclaration."\n ".$ref, $content);
if ($content === $updatedContent) {
throw new \RuntimeException('Unable to patch %s.', $kernelFile);
}
$fs->dumpFile($kernelFile, $updatedContent);
}
static::patchAcmeDemoBundleConfiguration($appDir, $fs);
}
private static function patchAcmeDemoBundleConfiguration($appDir, Filesystem $fs)
{
$routingFile = $appDir.'/config/routing_dev.yml';
$securityFile = $appDir.'/config/security.yml';
$routingData = file_get_contents($routingFile).<<<EOF
# AcmeDemoBundle routes (to be removed)
_acme_demo:
resource: "@AcmeDemoBundle/Resources/config/routing.yml"
EOF;
$fs->dumpFile($routingFile, $routingData);
$securityData = <<<EOF
# you can read more about security in the related section of the documentation
# http://symfony.com/doc/current/book/security.html
security:
# http://symfony.com/doc/current/book/security.html#encoding-the-user-s-password
encoders:
Symfony\Component\Security\Core\User\User: plaintext
# http://symfony.com/doc/current/book/security.html#hierarchical-roles
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
# http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
in_memory:
memory:
users:
user: { password: userpass, roles: [ 'ROLE_USER' ] }
admin: { password: adminpass, roles: [ 'ROLE_ADMIN' ] }
# the main part of the security, where you can set up firewalls
# for specific sections of your app
firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
# the login page has to be accessible for everybody
demo_login:
pattern: ^/demo/secured/login$
security: false
# secures part of the application
demo_secured_area:
pattern: ^/demo/secured/
# it's important to notice that in this case _demo_security_check and _demo_login
# are route names and that they are specified in the AcmeDemoBundle
form_login:
check_path: _demo_security_check
login_path: _demo_login
logout:
path: _demo_logout
target: _demo
#anonymous: ~
#http_basic:
# realm: "Secured Demo Area"
# with these settings you can restrict or allow access for different parts
# of your application based on roles, ip, host or methods
# http://symfony.com/doc/current/cookbook/security/access_control.html
access_control:
#- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
EOF;
$fs->dumpFile($securityFile, $securityData);
}
public static function doBuildBootstrap($bootstrapDir, $autoloadDir = null, $useNewDirectoryStructure = false)
{
$file = $bootstrapDir.'/bootstrap.php.cache';
if (file_exists($file)) {
unlink($file);
}
$classes = array(
'Symfony\\Component\\HttpFoundation\\ParameterBag',
'Symfony\\Component\\HttpFoundation\\HeaderBag',
'Symfony\\Component\\HttpFoundation\\FileBag',
'Symfony\\Component\\HttpFoundation\\ServerBag',
'Symfony\\Component\\HttpFoundation\\Request',
'Symfony\\Component\\HttpFoundation\\Response',
'Symfony\\Component\\HttpFoundation\\ResponseHeaderBag',
'Symfony\\Component\\DependencyInjection\\ContainerAwareInterface',
// Cannot be included because annotations will parse the big compiled class file
//'Symfony\\Component\\DependencyInjection\\ContainerAware',
'Symfony\\Component\\DependencyInjection\\Container',
'Symfony\\Component\\HttpKernel\\Kernel',
'Symfony\\Component\\ClassLoader\\ClassCollectionLoader',
'Symfony\\Component\\ClassLoader\\ApcClassLoader',
'Symfony\\Component\\HttpKernel\\Bundle\\Bundle',
'Symfony\\Component\\Config\\ConfigCache',
// cannot be included as commands are discovered based on the path to this class via Reflection
//'Symfony\\Bundle\\FrameworkBundle\\FrameworkBundle',
);
// introspect the autoloader to get the right file
// we cannot use class_exist() here as it would load the class
// which won't be included into the cache then.
// we know that composer autoloader is first (see bin/build_bootstrap.php)
$autoloaders = spl_autoload_functions();
if (is_array($autoloaders[0]) && method_exists($autoloaders[0][0], 'findFile') && $autoloaders[0][0]->findFile('Symfony\\Bundle\\FrameworkBundle\\HttpKernel')) {
$classes[] = 'Symfony\\Bundle\\FrameworkBundle\\HttpKernel';
} elseif (is_array($autoloaders[0]) && method_exists($autoloaders[0][0], 'findFile') && $autoloaders[0][0]->findFile('Symfony\\Component\\HttpKernel\\DependencyInjection\\ContainerAwareHttpKernel')) {
$classes[] = 'Symfony\\Component\\HttpKernel\\DependencyInjection\\ContainerAwareHttpKernel';
} else {
$classes[] = 'Symfony\\Component\\HttpKernel\\HttpKernel';
}
ClassCollectionLoader::load($classes, dirname($file), basename($file, '.php.cache'), false, false, '.php.cache');
$fs = new Filesystem();
$bootstrapContent = substr(file_get_contents($file), 5);
if ($useNewDirectoryStructure) {
$cacheDir = $fs->makePathRelative($bootstrapDir, $autoloadDir);
$bootstrapContent = str_replace(array("return \$this->rootDir.'/logs", "return \$this->rootDir.'/cache"), array("return \$this->rootDir.'/".$cacheDir."logs", "return \$this->rootDir.'/".$cacheDir."cache"), $bootstrapContent);
}
if ($autoloadDir) {
$fs = new Filesystem();
$autoloadDir = $fs->makePathRelative($autoloadDir, $bootstrapDir);
}
file_put_contents($file, sprintf(<<<'EOF'
<?php
namespace {
error_reporting(error_reporting() & ~E_USER_DEPRECATED);
$loader = require_once __DIR__.'/%sautoload.php';
}
%s
namespace { return $loader; }
EOF
, $autoloadDir, $bootstrapContent));
}
protected static function executeCommand(Event $event, $consoleDir, $cmd, $timeout = 300)
{
$php = escapeshellarg(static::getPhp(false));
$phpArgs = implode(' ', array_map('escapeshellarg', static::getPhpArguments()));
$console = escapeshellarg($consoleDir.'/console');
if ($event->getIO()->isDecorated()) {
$console .= ' --ansi';
}
$process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$console.' '.$cmd, null, null, null, $timeout);
$process->run(function ($type, $buffer) use ($event) { $event->getIO()->write($buffer, false); });
if (!$process->isSuccessful()) {
throw new \RuntimeException(sprintf("An error occurred when executing the \"%s\" command:\n\n%s\n\n%s.", escapeshellarg($cmd), $process->getOutput(), $process->getErrorOutput()));
}
}
protected static function executeBuildBootstrap(Event $event, $bootstrapDir, $autoloadDir, $timeout = 300)
{
$php = escapeshellarg(static::getPhp(false));
$phpArgs = implode(' ', array_map('escapeshellarg', static::getPhpArguments()));
$cmd = escapeshellarg(__DIR__.'/../Resources/bin/build_bootstrap.php');
$bootstrapDir = escapeshellarg($bootstrapDir);
$autoloadDir = escapeshellarg($autoloadDir);
$useNewDirectoryStructure = '';
if (static::useNewDirectoryStructure(static::getOptions($event))) {
$useNewDirectoryStructure = escapeshellarg('--use-new-directory-structure');
}
$process = new Process($php.($phpArgs ? ' '.$phpArgs : '').' '.$cmd.' '.$bootstrapDir.' '.$autoloadDir.' '.$useNewDirectoryStructure, getcwd(), null, null, $timeout);
$process->run(function ($type, $buffer) use ($event) { $event->getIO()->write($buffer, false); });
if (!$process->isSuccessful()) {
throw new \RuntimeException('An error occurred when generating the bootstrap file.');
}
}
protected static function updateDirectoryStructure(Event $event, $rootDir, $appDir, $binDir, $varDir, $webDir)
{
$event->getIO()->write('Updating Symfony directory structure...');
$fs = new Filesystem();
$fs->mkdir(array($binDir, $varDir));
foreach (array(
$appDir.'/console' => $binDir.'/console',
$appDir.'/phpunit.xml.dist' => $rootDir.'/phpunit.xml.dist',
) as $source => $target) {
$fs->rename($source, $target, true);
}
foreach (array('/logs', '/cache') as $dir) {
$fs->rename($appDir.$dir, $varDir.$dir);
}
$gitignore = <<<EOF
/web/bundles/
/app/config/parameters.yml
/var/bootstrap.php.cache
/var/SymfonyRequirements.php
/var/cache/*
/var/logs/*
!var/cache/.gitkeep
!var/logs/.gitkeep
/build/
/vendor/
/bin/*
!bin/console
!bin/symfony_requirements
/composer.phar
EOF;
$phpunitKernelBefore = <<<EOF
<!--
<php>
<server name="KERNEL_DIR" value="/path/to/your/app/" />
</php>
-->
EOF;
$phpunitKernelAfter = <<<EOF
<php>
<server name="KERNEL_DIR" value="$appDir/" />
</php>
EOF;
$phpunit = str_replace(array('<directory>../src', '"bootstrap.php.cache"', $phpunitKernelBefore), array('<directory>src', '"'.$varDir.'/bootstrap.php.cache"', $phpunitKernelAfter), file_get_contents($rootDir.'/phpunit.xml.dist'));
$composer = str_replace("\"symfony-app-dir\": \"app\",", "\"symfony-app-dir\": \"app\",\n \"symfony-bin-dir\": \"bin\",\n \"symfony-var-dir\": \"var\",", file_get_contents($rootDir.'/composer.json'));
$fs->dumpFile($webDir.'/app.php', str_replace($appDir.'/bootstrap.php.cache', $varDir.'/bootstrap.php.cache', file_get_contents($webDir.'/app.php')));
$fs->dumpFile($webDir.'/app_dev.php', str_replace($appDir.'/bootstrap.php.cache', $varDir.'/bootstrap.php.cache', file_get_contents($webDir.'/app_dev.php')));
$fs->dumpFile($binDir.'/console', str_replace(array(".'/bootstrap.php.cache'", ".'/AppKernel.php'"), array(".'/".$fs->makePathRelative($varDir, $binDir)."bootstrap.php.cache'", ".'/".$fs->makePathRelative($appDir, $binDir)."AppKernel.php'"), file_get_contents($binDir.'/console')));
$fs->dumpFile($rootDir.'/phpunit.xml.dist', $phpunit);
$fs->dumpFile($rootDir.'/composer.json', $composer);
$fs->dumpFile($rootDir.'/.gitignore', $gitignore);
$fs->chmod($binDir.'/console', 0755);
}
protected static function getOptions(Event $event)
{
$options = array_merge(static::$options, $event->getComposer()->getPackage()->getExtra());
$options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];
$options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');
return $options;
}
protected static function getPhp($includeArgs = true)
{
$phpFinder = new PhpExecutableFinder();
if (!$phpPath = $phpFinder->find($includeArgs)) {
throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
}
return $phpPath;
}
protected static function getPhpArguments()
{
$arguments = array();
$phpFinder = new PhpExecutableFinder();
if (method_exists($phpFinder, 'findArguments')) {
$arguments = $phpFinder->findArguments();
}
if (false !== $ini = php_ini_loaded_file()) {
$arguments[] = '--php-ini='.$ini;
}
return $arguments;
}
/**
* Returns a relative path to the directory that contains the `console` command.
*
* @param Event $event The command event.
* @param string $actionName The name of the action
*
* @return string|null The path to the console directory, null if not found.
*/
protected static function getConsoleDir(Event $event, $actionName)
{
$options = static::getOptions($event);
if (static::useNewDirectoryStructure($options)) {
if (!static::hasDirectory($event, 'symfony-bin-dir', $options['symfony-bin-dir'], $actionName)) {
return;
}
return $options['symfony-bin-dir'];
}
if (!static::hasDirectory($event, 'symfony-app-dir', $options['symfony-app-dir'], 'execute command')) {
return;
}
return $options['symfony-app-dir'];
}
/**
* Returns true if the new directory structure is used.
*
* @param array $options Composer options
*
* @return bool
*/
protected static function useNewDirectoryStructure(array $options)
{
return isset($options['symfony-var-dir']) && is_dir($options['symfony-var-dir']);
}
}