No Description

AbstractFileExtractor.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. * @param string $file
  46. *
  47. * @return bool
  48. *
  49. * @throws InvalidArgumentException
  50. */
  51. protected function isFile($file)
  52. {
  53. if (!is_file($file)) {
  54. throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
  55. }
  56. return true;
  57. }
  58. /**
  59. * @param string $file
  60. *
  61. * @return bool
  62. */
  63. abstract protected function canBeExtracted($file);
  64. /**
  65. * @param string|array $resource Files, a file or a directory
  66. *
  67. * @return iterable files to be extracted
  68. */
  69. abstract protected function extractFromDirectory($resource);
  70. }