AbstractFileExtractor.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Translation\Extractor;
  11. use Symfony\Component\Translation\Exception\InvalidArgumentException;
  12. /**
  13. * Base class used by classes that extract translation messages from files.
  14. *
  15. * @author Marcos D. Sánchez <marcosdsanchez@gmail.com>
  16. */
  17. abstract class AbstractFileExtractor
  18. {
  19. protected function extractFiles(string|iterable $resource): iterable
  20. {
  21. if (is_iterable($resource)) {
  22. $files = [];
  23. foreach ($resource as $file) {
  24. if ($this->canBeExtracted($file)) {
  25. $files[] = $this->toSplFileInfo($file);
  26. }
  27. }
  28. } elseif (is_file($resource)) {
  29. $files = $this->canBeExtracted($resource) ? [$this->toSplFileInfo($resource)] : [];
  30. } else {
  31. $files = $this->extractFromDirectory($resource);
  32. }
  33. return $files;
  34. }
  35. private function toSplFileInfo(string $file): \SplFileInfo
  36. {
  37. return new \SplFileInfo($file);
  38. }
  39. /**
  40. * @throws InvalidArgumentException
  41. */
  42. protected function isFile(string $file): bool
  43. {
  44. if (!is_file($file)) {
  45. throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
  46. }
  47. return true;
  48. }
  49. /**
  50. * @return bool
  51. */
  52. abstract protected function canBeExtracted(string $file);
  53. /**
  54. * @return iterable
  55. */
  56. abstract protected function extractFromDirectory(string|array $resource);
  57. }