AbstractFileExtractor.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. /**
  20. * @param string|iterable $resource Files, a file or a directory
  21. *
  22. * @return iterable
  23. */
  24. protected function extractFiles($resource)
  25. {
  26. if (is_iterable($resource)) {
  27. $files = [];
  28. foreach ($resource as $file) {
  29. if ($this->canBeExtracted($file)) {
  30. $files[] = $this->toSplFileInfo($file);
  31. }
  32. }
  33. } elseif (is_file($resource)) {
  34. $files = $this->canBeExtracted($resource) ? [$this->toSplFileInfo($resource)] : [];
  35. } else {
  36. $files = $this->extractFromDirectory($resource);
  37. }
  38. return $files;
  39. }
  40. private function toSplFileInfo(string $file): \SplFileInfo
  41. {
  42. return new \SplFileInfo($file);
  43. }
  44. /**
  45. * @return bool
  46. *
  47. * @throws InvalidArgumentException
  48. */
  49. protected function isFile(string $file)
  50. {
  51. if (!is_file($file)) {
  52. throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
  53. }
  54. return true;
  55. }
  56. /**
  57. * @return bool
  58. */
  59. abstract protected function canBeExtracted(string $file);
  60. /**
  61. * @param string|array $resource Files, a file or a directory
  62. *
  63. * @return iterable files to be extracted
  64. */
  65. abstract protected function extractFromDirectory($resource);
  66. }