LoaderFactory.php 2.1 KB

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