LoaderFactory.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. }