|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of fast-forward/dev-tools. |
| 7 | + * |
| 8 | + * This source file is subject to the license bundled |
| 9 | + * with this source code in the file LICENSE. |
| 10 | + * |
| 11 | + * @copyright Copyright (c) 2026 Felipe Sayão Lobato Abreu <github@mentordosnerds.com> |
| 12 | + * @license https://opensource.org/licenses/MIT MIT License |
| 13 | + * |
| 14 | + * @see https://github.com/php-fast-forward/dev-tools |
| 15 | + * @see https://github.com/php-fast-forward |
| 16 | + * @see https://datatracker.ietf.org/doc/html/rfc2119 |
| 17 | + */ |
| 18 | + |
| 19 | +namespace FastForward\DevTools\GitIgnore; |
| 20 | + |
| 21 | +use function Safe\preg_match; |
| 22 | + |
| 23 | +/** |
| 24 | + * Classifies .gitignore entries as directories or files. |
| 25 | + */ |
| 26 | +final class Classifier |
| 27 | +{ |
| 28 | + private const string DIRECTORY = 'directory'; |
| 29 | + |
| 30 | + private const string FILE = 'file'; |
| 31 | + |
| 32 | + /** |
| 33 | + * Classifies a .gitignore entry as directory or file pattern. |
| 34 | + * |
| 35 | + * @param string $entry the .gitignore entry |
| 36 | + * |
| 37 | + * @return 'directory'|'file' the classification |
| 38 | + */ |
| 39 | + public function classify(string $entry): string |
| 40 | + { |
| 41 | + $entry = trim($entry); |
| 42 | + |
| 43 | + if ('' === $entry) { |
| 44 | + return self::FILE; |
| 45 | + } |
| 46 | + |
| 47 | + if (str_starts_with($entry, '#')) { |
| 48 | + return self::FILE; |
| 49 | + } |
| 50 | + |
| 51 | + if (str_ends_with($entry, '/')) { |
| 52 | + return self::DIRECTORY; |
| 53 | + } |
| 54 | + |
| 55 | + if (1 === preg_match('/^[^.*]+[\/*]+$/', $entry)) { |
| 56 | + return self::DIRECTORY; |
| 57 | + } |
| 58 | + |
| 59 | + if (str_contains($entry, '*/')) { |
| 60 | + return self::DIRECTORY; |
| 61 | + } |
| 62 | + |
| 63 | + if (str_starts_with($entry, '**/')) { |
| 64 | + return self::DIRECTORY; |
| 65 | + } |
| 66 | + |
| 67 | + return self::FILE; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Checks if an entry is a directory pattern. |
| 72 | + * |
| 73 | + * @param string $entry |
| 74 | + */ |
| 75 | + public function isDirectory(string $entry): bool |
| 76 | + { |
| 77 | + return self::DIRECTORY === $this->classify($entry); |
| 78 | + } |
| 79 | + |
| 80 | + /** |
| 81 | + * Checks if an entry is a file pattern. |
| 82 | + * |
| 83 | + * @param string $entry |
| 84 | + */ |
| 85 | + public function isFile(string $entry): bool |
| 86 | + { |
| 87 | + return self::FILE === $this->classify($entry); |
| 88 | + } |
| 89 | +} |
0 commit comments