AbstractFileExtractor.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. /**
  12. * Base class used by classes that extract translation messages from files.
  13. *
  14. * @author Marcos D. Sánchez <marcosdsanchez@gmail.com>
  15. */
  16. abstract class AbstractFileExtractor
  17. {
  18. /**
  19. * @param string|array $resource files, a file or a directory
  20. *
  21. * @return array
  22. */
  23. protected function extractFiles($resource)
  24. {
  25. if (is_array($resource) || $resource instanceof \Traversable) {
  26. $files = array();
  27. foreach ($resource as $file) {
  28. if ($this->canBeExtracted($file)) {
  29. $files[] = $this->toSplFileInfo($file);
  30. }
  31. }
  32. } elseif (is_file($resource)) {
  33. $files = $this->canBeExtracted($resource) ? array($this->toSplFileInfo($resource)) : array();
  34. } else {
  35. $files = $this->extractFromDirectory($resource);
  36. }
  37. return $files;
  38. }
  39. /**
  40. * @param string $file
  41. *
  42. * @return \SplFileInfo
  43. */
  44. private function toSplFileInfo($file)
  45. {
  46. return ($file instanceof \SplFileInfo) ? $file : new \SplFileInfo($file);
  47. }
  48. /**
  49. * @param string $file
  50. *
  51. * @return bool
  52. *
  53. * @throws \InvalidArgumentException
  54. */
  55. protected function isFile($file)
  56. {
  57. if (!is_file($file)) {
  58. throw new \InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
  59. }
  60. return true;
  61. }
  62. /**
  63. * @param string $file
  64. *
  65. * @return bool
  66. */
  67. abstract protected function canBeExtracted($file);
  68. /**
  69. * @param string|array $resource files, a file or a directory
  70. *
  71. * @return array files to be extracted
  72. */
  73. abstract protected function extractFromDirectory($resource);
  74. }