AbstractFileExtractor.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 = array();
  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) ? array($this->toSplFileInfo($resource)) : array();
  35. } else {
  36. $files = $this->extractFromDirectory($resource);
  37. }
  38. return $files;
  39. }
  40. /**
  41. * @param string $file
  42. *
  43. * @return \SplFileInfo
  44. */
  45. private function toSplFileInfo($file)
  46. {
  47. return ($file instanceof \SplFileInfo) ? $file : new \SplFileInfo($file);
  48. }
  49. /**
  50. * @param string $file
  51. *
  52. * @return bool
  53. *
  54. * @throws InvalidArgumentException
  55. */
  56. protected function isFile($file)
  57. {
  58. if (!is_file($file)) {
  59. throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
  60. }
  61. return true;
  62. }
  63. /**
  64. * @param string $file
  65. *
  66. * @return bool
  67. */
  68. abstract protected function canBeExtracted($file);
  69. /**
  70. * @param string|array $resource files, a file or a directory
  71. *
  72. * @return array files to be extracted
  73. */
  74. abstract protected function extractFromDirectory($resource);
  75. }