blob: 729dd178126e3c1ee3767177ddc50190f742aa70 [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation\Extractor;
13
14use Symfony\Component\Translation\Exception\InvalidArgumentException;
15
16/**
17 * Base class used by classes that extract translation messages from files.
18 *
19 * @author Marcos D. Sánchez <marcosdsanchez@gmail.com>
20 */
21abstract class AbstractFileExtractor
22{
23 /**
24 * @param string|iterable $resource Files, a file or a directory
25 *
26 * @return iterable
27 */
28 protected function extractFiles($resource)
29 {
30 if (is_iterable($resource)) {
31 $files = [];
32 foreach ($resource as $file) {
33 if ($this->canBeExtracted($file)) {
34 $files[] = $this->toSplFileInfo($file);
35 }
36 }
37 } elseif (is_file($resource)) {
38 $files = $this->canBeExtracted($resource) ? [$this->toSplFileInfo($resource)] : [];
39 } else {
40 $files = $this->extractFromDirectory($resource);
41 }
42
43 return $files;
44 }
45
46 private function toSplFileInfo(string $file): \SplFileInfo
47 {
48 return new \SplFileInfo($file);
49 }
50
51 /**
52 * @return bool
53 *
54 * @throws InvalidArgumentException
55 */
56 protected function isFile(string $file)
57 {
58 if (!is_file($file)) {
59 throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
60 }
61
62 return true;
63 }
64
65 /**
66 * @return bool
67 */
68 abstract protected function canBeExtracted(string $file);
69
70 /**
71 * @param string|array $resource Files, a file or a directory
72 *
73 * @return iterable files to be extracted
74 */
75 abstract protected function extractFromDirectory($resource);
76}