Verified Commit 233ec1d9 authored by Alex Pott's avatar Alex Pott
Browse files

feat: #3446354 Create a simple class to allow discovering recipes in the file system

By: jnicola
By: phenaproxima
By: thejimbirch
By: mohit_aghera
By: b_sharpe
By: mxr576
By: nedjo
parent 52d22093
Loading
Loading
Loading
Loading
Loading
+164
Changes for core/lib/Drupal/Core/Recipe/Finder.php: 164 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Core\Recipe;

use Composer\InstalledVersions;
use Psr\Log\LoggerInterface;
use Symfony\Component\Finder\Finder as SymfonyFinder;

/**
 * Discovers recipes at specific locations in the file system.
 *
 * By default, this will scan core's recipes, along with the directory where
 * Composer is configured to install recipes. Alternatively, it can scan
 * directories of your choosing. It won't recurse into the file system, which is
 * an intentional difference from ExtensionDiscovery, because all recipes
 * (except core's) must be installed in a single location.
 *
 * Once instantiated, this object should be used as a simple iterator over
 * \Drupal\Core\Recipe\Recipe objects. For example:
 *
 * @code
 * $discovery = new Finder('/path/to/recipes');
 * foreach ($discovery as $recipe) {
 *   echo $recipe->name;
 * }
 * @endcode
 *
 * @see \Drupal\Core\Recipe\RecipeConfigurator
 *
 * @implements \IteratorAggregate<\Drupal\Core\Recipe\Recipe>
 *
 * @internal
 *   This API is experimental.
 */
final class Finder extends SymfonyFinder {

  /**
   * The location where Composer is configured to install recipes.
   */
  private static ?string $recipesDirectory = NULL;

  /**
   * Constructs a recipe finder.
   *
   * @param string|array|null $directories
   *   (optional) The directories that should be searched for recipes, or NULL
   *   to use the default locations.
   * @param bool $skipInvalid
   *   (optional) Whether to silently skip invalid recipes, or allow them to
   *   throw exceptions.
   * @param \Psr\Log\LoggerInterface|null $logger
   *   (optional) A logger where exceptions raised by invalid recipes should be
   *   logged.
   */
  public function __construct(
    string|array|null $directories = NULL,
    private readonly bool $skipInvalid = FALSE,
    public readonly ?LoggerInterface $logger = NULL,
  ) {
    parent::__construct();

    $directories ??= [
      // Placeholders used by the Composer installer don't make sense here.
      // For example, if Composer is configured to install recipes in
      // `./recipes/{$name}`, we really just want to scan `./recipes`.
      str_replace(['{$vendor}', '{$name}'], '', self::getComposerRecipesDirectory()),
      // Drupal runs in the web root, so this directory is guaranteed to exist
      // (and Finder will throw if it doesn't).
      'core/recipes',
    ];
    $this->in($directories)->followLinks();
  }

  /**
   * {@inheritdoc}
   */
  public function getIterator(): \Generator {
    // Set options that should never be configurable by calling code, so that
    // we can guarantee they are what we expect them to be before iterating.
    // Calling name() and depth() on $this is forbidden, so we need to set those
    // options on the parent class.
    $this->files();
    parent::name('recipe.yml');
    parent::depth(1);

    foreach (parent::getIterator() as $file) {
      try {
        yield Recipe::createFromDirectory($file->getPath());
      }
      catch (\Throwable $e) {
        $this->logger?->error($e->getMessage());
        if ($this->skipInvalid) {
          continue;
        }
        throw $e;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function directories(): never {
    throw new \LogicException('Recipe discovery can only scan for files.');
  }

  /**
   * {@inheritdoc}
   */
  public function depth(mixed $levels): never {
    throw new \LogicException('Recipe discovery cannot recurse into the file system.');
  }

  /**
   * {@inheritdoc}
   */
  public function name(mixed $patterns): never {
    throw new \LogicException('Recipe discovery can only scan for files named `recipe.yml`.');
  }

  /**
   * Returns the directory where recipes are installed.
   *
   * Placeholder tokens, like {$name} and {$vendor}, are left as-is.
   *
   * @param string|null $project_root
   *   (optional) The root of the project, where the top-level `composer.json`
   *   is. Auto-detected by default.
   *
   * @return string
   *   The path where Composer has installed recipes.
   *
   * @throws \RuntimeException
   *   Thrown if the install directory for recipes cannot be determined.
   */
  public static function getComposerRecipesDirectory(?string $project_root = NULL): string {
    // This is expensive to compute, and very unlikely to change in a request.
    if (isset(self::$recipesDirectory)) {
      return self::$recipesDirectory;
    }

    if (empty($project_root)) {
      ['install_path' => $project_root] = InstalledVersions::getRootPackage();
      $project_root = realpath($project_root);
    }
    assert(is_string($project_root));

    $file = $project_root . DIRECTORY_SEPARATOR . 'composer.json';
    $data = (string) file_get_contents($file);
    $data = json_decode($data, TRUE, flags: JSON_THROW_ON_ERROR);

    $directory = array_find_key(
      $data['extra']['installer-paths'] ?? [],
      fn (array $criteria): bool => in_array('type:' . Recipe::COMPOSER_PROJECT_TYPE, $criteria, TRUE),
    );
    if ($directory) {
      return self::$recipesDirectory = $project_root . DIRECTORY_SEPARATOR . $directory;
    }
    throw new \RuntimeException("No recipe install location is configured in $file.");
  }

}
+200
Changes for core/tests/Drupal/KernelTests/Core/Recipe/RecipeFinderTest.php: 200 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\KernelTests\Core\Recipe;

use ColinODell\PsrTestLogger\TestLogger;
use Drupal\Component\FileSystem\FileSystem;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Recipe\Finder;
use Drupal\Core\Recipe\Recipe;
use Drupal\KernelTests\KernelTestBase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\TestWith;
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;

/**
 * Tests the recipe finder.
 */
#[CoversClass(Finder::class)]
#[Group('Recipe')]
#[RunTestsInSeparateProcesses]
class RecipeFinderTest extends KernelTestBase {

  /**
   * Tests that the finder yields Recipe objects.
   */
  public function testFinderYieldsRecipes(): void {
    foreach (new Finder($this->root . '/core/recipes') as $recipe) {
      $this->assertInstanceOf(Recipe::class, $recipe);
    }
  }

  /**
   * Tests that certain configuration options are disallowed.
   */
  #[TestWith([
    'name',
    ['alternate.yml'],
    'Recipe discovery can only scan for files named `recipe.yml`.',
  ])]
  #[TestWith([
    'depth',
    [2],
    'Recipe discovery cannot recurse into the file system.',
  ])]
  #[TestWith([
    'directories',
    [],
    'Recipe discovery can only scan for files.',
  ])]
  public function testForbiddenMethods(string $method, array $arguments, string $expected_exception): void {
    $this->expectException(\LogicException::class);
    $this->expectExceptionMessage($expected_exception);

    $finder = new Finder($this->root . '/core/recipes');
    $finder->$method(...$arguments);
  }

  /**
   * Tests that invalid recipes can be safely skipped, with a log message.
   */
  public function testSkipInvalidRecipe(): void {
    $finder = new Finder(
      $this->root . '/core/tests/fixtures/recipes',
      TRUE,
      new TestLogger(),
    );
    // Convert to an array so that the generator gets run.
    iterator_to_array($finder);
    $this->assertTrue($finder->logger->hasErrorThatContains('foo: !php/enum Drupal\config_enum_test\DoesNotExistEnumValue::No'));
  }

  /**
   * Tests that recipes can be filtered in custom ways.
   */
  public function testCustomFiltering(): void {
    $finder = new Finder($this->root . '/core/recipes');

    // By default, we'll find the example recipe.
    $this->assertContains(
      'Example',
      array_column(iterator_to_array($finder), 'name'),
    );
    // But not if we explicitly filter it out.
    $finder->notPath('example');
    $this->assertNotContains(
      'Example',
      array_column(iterator_to_array($finder), 'name'),
    );
  }

  /**
   * Tests that there is an error if the finder is given invalid directories.
   *
   * @param string|array $directories
   *   The directory, or directories, to instantiate the finder with.
   */
  #[TestWith([''])]
  #[TestWith(['nonsense'])]
  #[TestWith([['core', 'nonsense']])]
  public function testInvalidDirectoriesRejected(string|array $directories): void {
    $error_directory = array_last((array) $directories);
    $this->expectException(DirectoryNotFoundException::class);
    $this->expectExceptionMessage("The \"$error_directory\" directory does not exist.");
    new Finder($directories);
  }

  /**
   * Tests that there is an error if Composer is misconfigured for recipes.
   */
  public function testUnknownComposerRecipeDirectory(): void {
    // By default, core's `composer.json` does not set up a recipe install path.
    $this->expectException(\RuntimeException::class);
    $this->expectExceptionMessage("No recipe install location is configured in $this->root/composer.json.");
    Finder::getComposerRecipesDirectory();
  }

  /**
   * Tests that the Composer recipe directory is read correctly.
   */
  public function testComposerRecipeDirectory(): void {
    $temp_dir = FileSystem::getOsTemporaryDirectory() . '/test';
    mkdir($temp_dir . '/recipes/test', recursive: TRUE);

    $contents = Json::encode([
      'extra' => [
        'installer-paths' => [
          'recipes/{$name}' => ['type:' . Recipe::COMPOSER_PROJECT_TYPE],
        ],
      ],
    ]);
    file_put_contents($temp_dir . '/composer.json', $contents);

    $this->assertSame($temp_dir . '/recipes/{$name}', Finder::getComposerRecipesDirectory($temp_dir));
    // The project root is now statically cached, so if we put a recipe in
    // there, it should be discovered.
    file_put_contents($temp_dir . '/recipes/test/recipe.yml', 'name: Test!');
    $names = array_column(iterator_to_array(new Finder()), 'name');
    $this->assertContains('Test!', $names);
    // Core recipes should be discovered too, by default.
    $this->assertContains('Administrator role', $names);

    (new SymfonyFilesystem())->remove($temp_dir);
  }

  /**
   * Tests that invalid recipes throw an exception by default.
   */
  public function testInvalidRecipesThrow(): void {
    $finder = new Finder($this->root . '/core/tests/fixtures/recipes');
    // This is a parse error, so we don't care about the exception type.
    $this->expectExceptionMessage('foo: !php/enum Drupal\config_enum_test\DoesNotExistEnumValue::No');
    iterator_to_array($finder);
  }

  /**
   * Tests scanning specific directories for recipes.
   */
  public function testScanSpecificDirectories(): void {
    // The finder can scan a single directory...
    $finder = new Finder($this->root . '/core/recipes', TRUE);
    $names = array_column(iterator_to_array($finder), 'name');
    $this->assertContains('Administrator role', $names);
    $this->assertContains('Editorial workflow', $names);
    $this->assertNotContains('Input Test', $names);

    // ...or several.
    $finder = new Finder([
      $this->root . '/core/recipes',
      $this->root . '/core/tests/fixtures/recipes',
    ], TRUE);
    $names = array_column(iterator_to_array($finder), 'name');
    $this->assertContains('Administrator role', $names);
    $this->assertContains('Editorial workflow', $names);
    $this->assertContains('Input Test', $names);
  }

  /**
   * Tests that the recipe finder follows symlinks.
   */
  public function testDiscoveryFollowsSymlinks(): void {
    $cookbook_dir = FileSystem::getOsTemporaryDirectory();
    $link_name = uniqid($cookbook_dir . '/recipe_link');
    $target = $this->root . '/core/recipes/administrator_role';

    $file_system = new SymfonyFilesystem();
    $file_system->symlink($target, $link_name);

    $recipes = iterator_to_array(new Finder($cookbook_dir));
    $this->assertCount(1, $recipes);
    $this->assertSame('Administrator role', reset($recipes)->name);

    $file_system->remove($link_name);
  }

}