<?php

namespace Drupal\Composer\Plugin\Scaffold;

use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Drupal\Composer\Plugin\Scaffold\Operations\ScaffoldResult;

/**
 * Generates an 'autoload_runtime.php' that includes the Symfony_runtime loader.
 *
 * @internal
 */
final class GenerateAutoloadRuntimeReferenceFile {

  /**
   * This class provides only static methods.
   */
  private function __construct() {
  }

  /**
   * Generates the autoload_runtime file at the specified location.
   *
   * This only writes a bit of PHP that includes the autoload_runtime file that
   * Composer generated. Drupal does this so that it can guarantee that there
   * will always be an `autoload_runtime.php` file in a well-known location.
   *
   * @param \Composer\IO\IOInterface $io
   *   IOInterface to write to.
   * @param string $package_name
   *   The name of the package defining the autoload_runtime file
   *   (the root package).
   * @param string $web_root
   *   The path to the web root.
   * @param string $vendor
   *   The path to the vendor directory.
   *
   * @return \Drupal\Composer\Plugin\Scaffold\Operations\ScaffoldResult
   *   The result of the autoload_runtime file generation.
   */
  public static function generateAutoloadRuntime(IOInterface $io, string $package_name, string $web_root, string $vendor): ScaffoldResult {
    $autoload_runtime_path = static::autoloadRuntimePath($package_name, $web_root);
    // Calculate the relative path from the webroot (location of the project
    // autoload_runtime.php) to the vendor directory.
    $fs = new Filesystem();
    $relative_autoload_path = $fs->findShortestPath($autoload_runtime_path->fullPath(), "$vendor/autoload_runtime.php");
    file_put_contents($autoload_runtime_path->fullPath(), static::autoLoadRuntimeContents($relative_autoload_path));
    return new ScaffoldResult($autoload_runtime_path, TRUE);
  }

  /**
   * Determines whether or not the autoload_runtime file has been committed.
   *
   * @param \Composer\IO\IOInterface $io
   *   IOInterface to write to.
   * @param string $package_name
   *   The name of the package defining the autoload_runtime file
   *   (the root package).
   * @param string $web_root
   *   The path to the web root.
   *
   * @return bool
   *   True if autoload_runtime.php file exists and has been committed to the
   *   repository
   */
  public static function autoloadRuntimeFileCommitted(IOInterface $io, string $package_name, string $web_root): bool {
    $autoload_runtime_path = static::autoloadRuntimePath($package_name, $web_root);
    $autoload_runtime_file = $autoload_runtime_path->fullPath();
    $location = dirname($autoload_runtime_file);
    if (!file_exists($autoload_runtime_file)) {
      return FALSE;
    }
    return Git::checkTracked($io, $autoload_runtime_file, $location);
  }

  /**
   * Generates a scaffold file path object for the autoload_runtime file.
   *
   * @param string $package_name
   *   The name of the package defining the autoload_runtime file
   *   (the root package).
   * @param string $web_root
   *   The path to the web root.
   *
   * @return \Drupal\Composer\Plugin\Scaffold\ScaffoldFilePath
   *   Object wrapping the relative and absolute path to the destination file.
   */
  protected static function autoloadRuntimePath(string $package_name, string $web_root): ScaffoldFilePath {
    $rel_path = 'autoload_runtime.php';
    $dest_rel_path = '[web-root]/' . $rel_path;
    $dest_full_path = $web_root . '/' . $rel_path;
    return new ScaffoldFilePath('autoload_runtime', $package_name, $dest_rel_path, $dest_full_path);
  }

  /**
   * Builds the contents of the autoload_runtime file.
   *
   * @param string $relative_autoload_runtime_path
   *   The relative path to the runtime loader in vendor.
   *
   * @return string
   *   Return the contents for the autoload_runtime.php.
   */
  protected static function autoLoadRuntimeContents(string $relative_autoload_runtime_path): string {
    $relative_autoload_runtime_path = preg_replace('#^\./#', '', $relative_autoload_runtime_path);
    return <<<EOF
<?php

/**
 * @file
 * Includes the autoload_runtime created by the Symfony Runtime component.
 *
 * This file was generated by drupal-scaffold.
 *
 * @see composer.json
 * @see index.php
 * @see core/install.php
 * @see core/rebuild.php
 */

use Drupal\Core\Runtime\DrupalRuntime;

// By default, the symfony/runtime component would load SymfonyRuntime as its
// runtime. However, Drupal's Kernel has a lot of runtime components that it
// expects to be prepared. Thus, we default Drupal applications to DrupalRuntime
// instead to make this easily accessible.
\$_ENV['APP_RUNTIME'] ??= \$_SERVER['APP_RUNTIME'] ?? DrupalRuntime::class;
return require __DIR__ . '/{$relative_autoload_runtime_path}';

EOF;
  }

}
