DirSearch.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Component;
  7. use Magento\Framework\Filesystem;
  8. /**
  9. * Class for searching files across all locations of certain component type
  10. */
  11. class DirSearch
  12. {
  13. /**
  14. * Component registrar
  15. *
  16. * @var ComponentRegistrarInterface
  17. */
  18. private $registrar;
  19. /**
  20. * Read dir factory
  21. *
  22. * @var Filesystem\Directory\ReadFactory
  23. */
  24. private $readFactory;
  25. /**
  26. * Constructor
  27. *
  28. * @param ComponentRegistrarInterface $registrar
  29. * @param Filesystem\Directory\ReadFactory $readFactory
  30. */
  31. public function __construct(ComponentRegistrarInterface $registrar, Filesystem\Directory\ReadFactory $readFactory)
  32. {
  33. $this->registrar = $registrar;
  34. $this->readFactory = $readFactory;
  35. }
  36. /**
  37. * Search for files in each component by pattern, returns absolute paths
  38. *
  39. * @param string $componentType
  40. * @param string $pattern
  41. * @return array
  42. */
  43. public function collectFiles($componentType, $pattern)
  44. {
  45. return $this->collect($componentType, $pattern, false);
  46. }
  47. /**
  48. * Search for files in each component by pattern, returns file objects with absolute file paths
  49. *
  50. * @param string $componentType
  51. * @param string $pattern
  52. * @return ComponentFile[]
  53. */
  54. public function collectFilesWithContext($componentType, $pattern)
  55. {
  56. return $this->collect($componentType, $pattern, true);
  57. }
  58. /**
  59. * Collect files in components
  60. * If $withContext is true, returns array of file objects with component context
  61. *
  62. * @param string $componentType
  63. * @param string $pattern
  64. * @param bool|false $withContext
  65. * @return array
  66. */
  67. private function collect($componentType, $pattern, $withContext)
  68. {
  69. $files = [];
  70. foreach ($this->registrar->getPaths($componentType) as $componentName => $path) {
  71. $directoryRead = $this->readFactory->create($path);
  72. $foundFiles = $directoryRead->search($pattern);
  73. foreach ($foundFiles as $foundFile) {
  74. $foundFile = $directoryRead->getAbsolutePath($foundFile);
  75. if ($withContext) {
  76. $files[] = new ComponentFile($componentType, $componentName, $foundFile);
  77. } else {
  78. $files[] = $foundFile;
  79. }
  80. }
  81. }
  82. return $files;
  83. }
  84. }