Composer.php 9.67 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Composer;

5
use Drupal\Component\PhpStorage\FileStorage;
6
use Composer\Script\Event;
7
use Composer\Installer\PackageEvent;
8
use Composer\Semver\Constraint\Constraint;
9
use Composer\Util\ProcessExecutor;
10 11 12 13 14 15 16 17

/**
 * Provides static functions for composer script events.
 *
 * @see https://getcomposer.org/doc/articles/scripts.md
 */
class Composer {

18 19 20 21
  protected static $packageToCleanup = [
    'behat/mink' => ['tests', 'driver-testsuite'],
    'behat/mink-browserkit-driver' => ['tests'],
    'behat/mink-goutte-driver' => ['tests'],
22
    'brumann/polyfill-unserialize' => ['tests'],
23
    'drupal/coder' => ['coder_sniffer/Drupal/Test', 'coder_sniffer/DrupalPractice/Test'],
24 25 26 27 28 29 30 31 32
    'doctrine/cache' => ['tests'],
    'doctrine/collections' => ['tests'],
    'doctrine/common' => ['tests'],
    'doctrine/inflector' => ['tests'],
    'doctrine/instantiator' => ['tests'],
    'egulias/email-validator' => ['documentation', 'tests'],
    'fabpot/goutte' => ['Goutte/Tests'],
    'guzzlehttp/promises' => ['tests'],
    'guzzlehttp/psr7' => ['tests'],
33 34
    'jcalderonzumba/gastonjs' => ['docs', 'examples', 'tests'],
    'jcalderonzumba/mink-phantomjs-driver' => ['tests'],
35 36
    'masterminds/html5' => ['test'],
    'mikey179/vfsStream' => ['src/test'],
37
    'paragonie/random_compat' => ['tests'],
38 39 40 41
    'pear/archive_tar' => ['tests'],
    'pear/console_getopt' => ['tests'],
    'pear/pear-core-minimal' => ['tests'],
    'pear/pear_exception' => ['tests'],
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    'phpdocumentor/reflection-docblock' => ['tests'],
    'phpunit/php-code-coverage' => ['tests'],
    'phpunit/php-timer' => ['tests'],
    'phpunit/php-token-stream' => ['tests'],
    'phpunit/phpunit' => ['tests'],
    'phpunit/php-mock-objects' => ['tests'],
    'sebastian/comparator' => ['tests'],
    'sebastian/diff' => ['tests'],
    'sebastian/environment' => ['tests'],
    'sebastian/exporter' => ['tests'],
    'sebastian/global-state' => ['tests'],
    'sebastian/recursion-context' => ['tests'],
    'stack/builder' => ['tests'],
    'symfony/browser-kit' => ['Tests'],
    'symfony/class-loader' => ['Tests'],
    'symfony/console' => ['Tests'],
    'symfony/css-selector' => ['Tests'],
    'symfony/debug' => ['Tests'],
    'symfony/dependency-injection' => ['Tests'],
    'symfony/dom-crawler' => ['Tests'],
62 63
    // @see \Drupal\Tests\Component\EventDispatcher\ContainerAwareEventDispatcherTest
    // 'symfony/event-dispatcher' => ['Tests'],
64 65 66 67 68 69 70
    'symfony/http-foundation' => ['Tests'],
    'symfony/http-kernel' => ['Tests'],
    'symfony/process' => ['Tests'],
    'symfony/psr-http-message-bridge' => ['Tests'],
    'symfony/routing' => ['Tests'],
    'symfony/serializer' => ['Tests'],
    'symfony/translation' => ['Tests'],
71
    'symfony/validator' => ['Tests', 'Resources'],
72 73 74 75 76
    'symfony/yaml' => ['Tests'],
    'symfony-cmf/routing' => ['Test', 'Tests'],
    'twig/twig' => ['doc', 'ext', 'test'],
  ];

77
  /**
78
   * Add vendor classes to Composer's static classmap.
79 80
   */
  public static function preAutoloadDump(Event $event) {
81 82 83
    // Get the configured vendor directory.
    $vendor_dir = $event->getComposer()->getConfig()->get('vendor-dir');

84 85 86 87 88 89
    // We need the root package so we can add our classmaps to its loader.
    $package = $event->getComposer()->getPackage();
    // We need the local repository so that we can query and see if it's likely
    // that our files are present there.
    $repository = $event->getComposer()->getRepositoryManager()->getLocalRepository();
    // This is, essentially, a null constraint. We only care whether the package
90
    // is present in the vendor directory yet, but findPackage() requires it.
91
    $constraint = new Constraint('>', '');
92 93 94 95 96 97 98
    // It's possible that there is no classmap specified in a custom project
    // composer.json file. We need one so we can optimize lookup for some of our
    // dependencies.
    $autoload = $package->getAutoload();
    if (!isset($autoload['classmap'])) {
      $autoload['classmap'] = [];
    }
99 100
    // Check for our packages, and then optimize them if they're present.
    if ($repository->findPackage('symfony/http-foundation', $constraint)) {
101
      $autoload['classmap'] = array_merge($autoload['classmap'], [
102 103 104 105 106
        $vendor_dir . '/symfony/http-foundation/Request.php',
        $vendor_dir . '/symfony/http-foundation/ParameterBag.php',
        $vendor_dir . '/symfony/http-foundation/FileBag.php',
        $vendor_dir . '/symfony/http-foundation/ServerBag.php',
        $vendor_dir . '/symfony/http-foundation/HeaderBag.php',
107
      ]);
108 109
    }
    if ($repository->findPackage('symfony/http-kernel', $constraint)) {
110
      $autoload['classmap'] = array_merge($autoload['classmap'], [
111 112 113
        $vendor_dir . '/symfony/http-kernel/HttpKernel.php',
        $vendor_dir . '/symfony/http-kernel/HttpKernelInterface.php',
        $vendor_dir . '/symfony/http-kernel/TerminableInterface.php',
114
      ]);
115
    }
116
    $package->setAutoload($autoload);
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
  /**
   * Ensures that .htaccess and web.config files are present in Composer root.
   *
   * @param \Composer\Script\Event $event
   */
  public static function ensureHtaccess(Event $event) {

    // The current working directory for composer scripts is where you run
    // composer from.
    $vendor_dir = $event->getComposer()->getConfig()->get('vendor-dir');

    // Prevent access to vendor directory on Apache servers.
    $htaccess_file = $vendor_dir . '/.htaccess';
    if (!file_exists($htaccess_file)) {
      file_put_contents($htaccess_file, FileStorage::htaccessLines(TRUE) . "\n");
    }

    // Prevent access to vendor directory on IIS servers.
    $webconfig_file = $vendor_dir . '/web.config';
    if (!file_exists($webconfig_file)) {
      $lines = <<<EOT
<configuration>
  <system.webServer>
    <authorization>
      <deny users="*">
    </authorization>
  </system.webServer>
</configuration>
EOT;
      file_put_contents($webconfig_file, $lines . "\n");
    }
  }

152 153 154
  /**
   * Remove possibly problematic test files from vendored projects.
   *
155 156 157
   * @param \Composer\Installer\PackageEvent $event
   *   A PackageEvent object to get the configured composer vendor directories
   *   from.
158 159 160
   */
  public static function vendorTestCodeCleanup(PackageEvent $event) {
    $vendor_dir = $event->getComposer()->getConfig()->get('vendor-dir');
161
    $io = $event->getIO();
162 163 164 165 166 167 168 169
    $op = $event->getOperation();
    if ($op->getJobType() == 'update') {
      $package = $op->getTargetPackage();
    }
    else {
      $package = $op->getPackage();
    }
    $package_key = static::findPackageKey($package->getName());
170 171 172 173
    $message = sprintf("    Processing <comment>%s</comment>", $package->getPrettyName());
    if ($io->isVeryVerbose()) {
      $io->write($message);
    }
174 175 176
    if ($package_key) {
      foreach (static::$packageToCleanup[$package_key] as $path) {
        $dir_to_remove = $vendor_dir . '/' . $package_key . '/' . $path;
177
        $print_message = $io->isVeryVerbose();
178
        if (is_dir($dir_to_remove)) {
179 180 181 182 183 184 185 186 187
          if (static::deleteRecursive($dir_to_remove)) {
            $message = sprintf("      <info>Removing directory '%s'</info>", $path);
          }
          else {
            // Always display a message if this fails as it means something has
            // gone wrong. Therefore the message has to include the package name
            // as the first informational message might not exist.
            $print_message = TRUE;
            $message = sprintf("      <error>Failure removing directory '%s'</error> in package <comment>%s</comment>.", $path, $package->getPrettyName());
188 189
          }
        }
190 191 192 193 194 195 196 197 198 199 200 201 202
        else {
          // If the package has changed or the --prefer-dist version does not
          // include the directory this is not an error.
          $message = sprintf("      Directory '%s' does not exist", $path);
        }
        if ($print_message) {
          $io->write($message);
        }
      }

      if ($io->isVeryVerbose()) {
        // Add a new line to separate this output from the next package.
        $io->write("");
203 204 205 206 207 208 209 210 211 212
      }
    }
  }

  /**
   * Find the array key for a given package name with a case-insensitive search.
   *
   * @param string $package_name
   *   The package name from composer. This is always already lower case.
   *
213
   * @return string|null
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
   *   The string key, or NULL if none was found.
   */
  protected static function findPackageKey($package_name) {
    $package_key = NULL;
    // In most cases the package name is already used as the array key.
    if (isset(static::$packageToCleanup[$package_name])) {
      $package_key = $package_name;
    }
    else {
      // Handle any mismatch in case between the package name and array key.
      // For example, the array key 'mikey179/vfsStream' needs to be found
      // when composer returns a package name of 'mikey179/vfsstream'.
      foreach (static::$packageToCleanup as $key => $dirs) {
        if (strtolower($key) === $package_name) {
          $package_key = $key;
          break;
        }
      }
    }
    return $package_key;
  }

236 237 238 239 240 241 242
  /**
   * Removes Composer's timeout so that scripts can run indefinitely.
   */
  public static function removeTimeout() {
    ProcessExecutor::setTimeout(0);
  }

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
  /**
   * Helper method to remove directories and the files they contain.
   *
   * @param string $path
   *   The directory or file to remove. It must exist.
   *
   * @return bool
   *   TRUE on success or FALSE on failure.
   */
  protected static function deleteRecursive($path) {
    if (is_file($path) || is_link($path)) {
      return unlink($path);
    }
    $success = TRUE;
    $dir = dir($path);
    while (($entry = $dir->read()) !== FALSE) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $entry_path = $path . '/' . $entry;
      $success = static::deleteRecursive($entry_path) && $success;
    }
    $dir->close();

    return rmdir($path) && $success;
  }

270
}