LoaderFactory.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace Fgm\ComposerCheck;
  3. /**
  4. * Class LoaderFactory builds Loader instances.
  5. */
  6. class LoaderFactory {
  7. /**
  8. * The absolute path to the directory holding the composer.(json|lock) pair.
  9. *
  10. * @var string
  11. */
  12. protected $directory;
  13. /**
  14. * LoaderFactory constructor.
  15. *
  16. * @param string $directory
  17. * The path of a directory holding a composer.(json|lock) file pair.
  18. */
  19. public function __construct(string $directory) {
  20. $validatedDirectory = self::validateDirectory($directory);
  21. if (empty($validatedDirectory)) {
  22. throw new \InvalidArgumentException("Unusable directory: $directory");
  23. }
  24. $this->directory = $validatedDirectory;
  25. }
  26. /**
  27. * Build the absolute path to the directory holding the file pair.
  28. *
  29. * @param string $directory
  30. * A directory path to validate.
  31. *
  32. * @return false|string
  33. * The absolute path to the directory, or FALSE if it does not contain
  34. * a readable file pair.
  35. */
  36. public static function validateDirectory(string $directory) {
  37. $path = realpath($directory);
  38. // PHP is_dir() follows symlinks to report on the link target.
  39. if (empty($path) || !is_dir($path) || !is_readable($path)) {
  40. return FALSE;
  41. }
  42. foreach (['json', 'lock'] as $kind) {
  43. $filePath = realpath("${path}/composer.${kind}");
  44. if (empty($filePath) || !is_file($filePath) || !is_readable($filePath)) {
  45. return FALSE;
  46. }
  47. }
  48. return $path;
  49. }
  50. /**
  51. * The actual factory method.
  52. *
  53. * @param string $type
  54. * The kind of loader to instantiate: "lock" or "requirements".
  55. *
  56. * @return \Fgm\ComposerCheck\LoaderInterface
  57. * A loader instance.
  58. */
  59. public function createLoader(string $type) {
  60. $className = __NAMESPACE__ . '\\' . ucfirst($type) . 'Loader';
  61. if (!class_exists($className)) {
  62. throw new \InvalidArgumentException("Unknown loader type: $type.");
  63. }
  64. /** @var \Fgm\ComposerCheck\LoaderInterface $loader */
  65. $loader = new $className($this->directory);
  66. return $loader;
  67. }
  68. }