|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of Blitz PHP framework. |
| 5 | + * |
| 6 | + * (c) 2022 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view |
| 9 | + * the LICENSE file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace BlitzPHP\HotReloader; |
| 13 | + |
| 14 | +use BlitzPHP\Exceptions\FrameworkException; |
| 15 | +use FilesystemIterator; |
| 16 | +use RecursiveDirectoryIterator; |
| 17 | +use RecursiveIteratorIterator; |
| 18 | + |
| 19 | +/** |
| 20 | + * @internal |
| 21 | + * |
| 22 | + * @credit <a href="https://codeigniter.com">CodeIgniter 4.6 - CodeIgniter\HotReloader\DirectoryHasher</a> |
| 23 | + */ |
| 24 | +final class DirectoryHasher |
| 25 | +{ |
| 26 | + /** |
| 27 | + * Génère une valeur MD5 de tous les répertoires surveillés par le rechargeur à chaud, |
| 28 | + * comme défini dans le fichier app/Config/toolbar.php. |
| 29 | + * |
| 30 | + * Il s'agit de l'empreinte actuelle de l'application. |
| 31 | + */ |
| 32 | + public function hash(): string |
| 33 | + { |
| 34 | + return md5(implode('', $this->hashApp())); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Génère un tableau de hachages md5 pour tous les répertoires surveillés par le Hot Reloader, |
| 39 | + * comme défini dans app/Config/toolbar.php. |
| 40 | + */ |
| 41 | + public function hashApp(): array |
| 42 | + { |
| 43 | + $hashes = []; |
| 44 | + |
| 45 | + $watchedDirectories = config('toolbar.watched_directories', []); |
| 46 | + |
| 47 | + foreach ($watchedDirectories as $directory) { |
| 48 | + if (is_dir(ROOTPATH . $directory)) { |
| 49 | + $hashes[$directory] = $this->hashDirectory(ROOTPATH . $directory); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return array_unique(array_filter($hashes)); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Génère un hachage MD5 d'un répertoire donné et de tous ses fichiers * qui correspondent aux extensions surveillées |
| 58 | + * définies dans app/Config/toolbar.php. |
| 59 | + */ |
| 60 | + public function hashDirectory(string $path): string |
| 61 | + { |
| 62 | + if (! is_dir($path)) { |
| 63 | + throw FrameworkException::invalidDirectory($path); |
| 64 | + } |
| 65 | + |
| 66 | + $directory = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS); |
| 67 | + $filter = new IteratorFilter($directory); |
| 68 | + $iterator = new RecursiveIteratorIterator($filter); |
| 69 | + |
| 70 | + $hashes = []; |
| 71 | + |
| 72 | + foreach ($iterator as $file) { |
| 73 | + if ($file->isFile()) { |
| 74 | + $hashes[] = md5_file($file->getRealPath()); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return md5(implode('', $hashes)); |
| 79 | + } |
| 80 | +} |
0 commit comments