blob: 4c088b94f991e23788a0e6a086de5c566f1cb96d [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{
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010023 protected function extractFiles(string|iterable $resource): iterable
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020024 {
25 if (is_iterable($resource)) {
26 $files = [];
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) ? [$this->toSplFileInfo($resource)] : [];
34 } else {
35 $files = $this->extractFromDirectory($resource);
36 }
37
38 return $files;
39 }
40
41 private function toSplFileInfo(string $file): \SplFileInfo
42 {
43 return new \SplFileInfo($file);
44 }
45
46 /**
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020047 * @throws InvalidArgumentException
48 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010049 protected function isFile(string $file): bool
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020050 {
51 if (!is_file($file)) {
52 throw new InvalidArgumentException(sprintf('The "%s" file does not exist.', $file));
53 }
54
55 return true;
56 }
57
58 /**
59 * @return bool
60 */
61 abstract protected function canBeExtracted(string $file);
62
63 /**
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010064 * @return iterable
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020065 */
Matthias Andreas Benkard1ba53812022-12-27 17:32:58 +010066 abstract protected function extractFromDirectory(string|array $resource);
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +020067}