12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace Fgm\ComposerCheck;
- /**
- * Class LoaderFactory builds Loader instances.
- */
- class LoaderFactory {
- /**
- * The absolute path to the directory holding the composer.(json|lock) pair.
- *
- * @var string
- */
- protected $directory;
- /**
- * LoaderFactory constructor.
- *
- * @param string $directory
- * The path of a directory holding a composer.(json|lock) file pair.
- */
- public function __construct(string $directory) {
- $validatedDirectory = self::validateDirectory($directory);
- if (empty($validatedDirectory)) {
- throw new \InvalidArgumentException("Unusable directory: $directory");
- }
- $this->directory = $validatedDirectory;
- }
- /**
- * Build the absolute path to the directory holding the file pair.
- *
- * @param string $directory
- * A directory path to validate.
- *
- * @return false|string
- * The absolute path to the directory, or FALSE if it does not contain
- * a readable file pair.
- */
- public static function validateDirectory(string $directory) {
- $path = realpath($directory);
- // PHP is_dir() follows symlinks to report on the link target.
- if (empty($path) || !is_dir($path) || !is_readable($path)) {
- return FALSE;
- }
- foreach (['json', 'lock'] as $kind) {
- $filePath = realpath("${path}/composer.${kind}");
- if (empty($filePath) || !is_file($filePath) || !is_readable($filePath)) {
- return FALSE;
- }
- }
- return $path;
- }
- /**
- * The actual factory method.
- *
- * @param string $type
- * The kind of loader to instantiate: "lock" or "requirements".
- *
- * @return \Fgm\ComposerCheck\LoaderInterface
- * A loader instance.
- */
- public function createLoader(string $type) {
- $className = __NAMESPACE__ . '\\' . ucfirst($type) . 'Loader';
- if (!class_exists($className)) {
- throw new \InvalidArgumentException("Unknown loader type: $type.");
- }
- /** @var \Fgm\ComposerCheck\LoaderInterface $loader */
- $loader = new $className($this->directory);
- return $loader;
- }
- }
|