|
4 | 4 |
|
5 | 5 | namespace TypistTech\ImageOptimizeCommand\Operations;
|
6 | 6 |
|
| 7 | +use InvalidArgumentException; |
7 | 8 | use Symfony\Component\Finder\Finder;
|
8 | 9 | use Symfony\Component\Finder\SplFileInfo;
|
9 | 10 | use TypistTech\ImageOptimizeCommand\LoggerInterface;
|
@@ -47,18 +48,43 @@ public function __construct(Finder $finder, LoggerInterface $logger)
|
47 | 48 | */
|
48 | 49 | public function execute(string $directory, string ...$extensions): array
|
49 | 50 | {
|
| 51 | + $this->logger->section('Finding images'); |
| 52 | + |
50 | 53 | $directory = normalize_path($directory);
|
51 | 54 | $pattern = sprintf(
|
52 | 55 | '/\.(%1$s)$/',
|
53 | 56 | implode('|', $extensions)
|
54 | 57 | );
|
55 | 58 |
|
56 |
| - $files = $this->finder->files() |
57 |
| - ->in($directory) |
58 |
| - ->name($pattern); |
| 59 | + $this->logger->info('Directory: ' . $directory); |
| 60 | + $this->logger->info('Pattern: ' . $pattern); |
| 61 | + |
| 62 | + $files = $this->find($directory, $pattern); |
| 63 | + $this->logger->notice(count($files) . 'image(s) found.'); |
| 64 | + |
| 65 | + return array_values($files); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Find files under a directory with specific name pattern. |
| 70 | + * |
| 71 | + * @param string $directory Normalize_directory path. |
| 72 | + * @param string $pattern File name regex. |
| 73 | + * |
| 74 | + * @return string[] |
| 75 | + */ |
| 76 | + protected function find(string $directory, string $pattern): array |
| 77 | + { |
| 78 | + try { |
| 79 | + $files = $this->finder->files()->in($directory)->name($pattern); |
| 80 | + |
| 81 | + return array_map(function (SplFileInfo $file): string { |
| 82 | + return $file->getRealPath(); |
| 83 | + }, iterator_to_array($files)); |
59 | 84 |
|
60 |
| - return array_map(function (SplFileInfo $file): string { |
61 |
| - return $file->getRealPath(); |
62 |
| - }, iterator_to_array($files)); |
| 85 | + // phpcs:ignore |
| 86 | + } catch (InvalidArgumentException $exception) { |
| 87 | + return []; |
| 88 | + } |
63 | 89 | }
|
64 | 90 | }
|
0 commit comments