AbstractFileExtractor.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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|array $resource Files, a file or a directory
  21. *
  22. * @return array
  23. */
  24. protected function extractFiles($resource)
  25. {
  26. if (\is_array($resource) || $resource instanceof \Traversable) {
  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 array files to be extracted
  68. */
  69. abstract protected function extractFromDirectory($resource);
  70. }