| Total Complexity | 13 |
| Total Lines | 85 |
| Duplicated Lines | 0 % |
| Changes | 3 | ||
| Bugs | 1 | Features | 0 |
| 1 | <?php |
||
| 7 | abstract class FileUtils |
||
| 8 | { |
||
| 9 | /** |
||
| 10 | * Adds a new $line at the end of a $file without duplication. |
||
| 11 | * |
||
| 12 | * @param string $file |
||
| 13 | * @param string $line |
||
| 14 | * |
||
| 15 | * @return bool |
||
| 16 | */ |
||
| 17 | public static function addLine(string $file, string $line): bool |
||
| 18 | { |
||
| 19 | if (!file_exists($file)) { |
||
| 20 | return false; |
||
| 21 | } |
||
| 22 | |||
| 23 | $handle = fopen($file, 'r+'); |
||
| 24 | |||
| 25 | while (($currentLine = fgets($handle)) !== false) { |
||
|
|
|||
| 26 | if (trim($currentLine) == $line) { |
||
| 27 | return false; |
||
| 28 | } |
||
| 29 | } |
||
| 30 | |||
| 31 | fwrite($handle, $line.PHP_EOL); |
||
| 32 | |||
| 33 | fclose($handle); |
||
| 34 | |||
| 35 | return true; |
||
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Counts the number of lines in a $file. |
||
| 40 | * |
||
| 41 | * @param string $file |
||
| 42 | * @param bool $countEmpty |
||
| 43 | * |
||
| 44 | * @return int|null |
||
| 45 | */ |
||
| 46 | public static function count(string $file, bool $countEmpty = false): ?int |
||
| 47 | { |
||
| 48 | if (!file_exists($file)) { |
||
| 49 | return null; |
||
| 50 | } |
||
| 51 | |||
| 52 | $lines = 0; |
||
| 53 | $handle = fopen($file, 'r'); |
||
| 54 | while (!feof($handle)) { |
||
| 55 | $line = fgets($handle, 8192); |
||
| 56 | |||
| 57 | if (false === $line) { |
||
| 58 | continue; |
||
| 59 | } |
||
| 60 | |||
| 61 | $lastChar = mb_strlen((string) $line) - 1; |
||
| 62 | |||
| 63 | if ($lastChar == 0) { |
||
| 64 | if ($countEmpty) { |
||
| 65 | ++$lines; |
||
| 66 | } |
||
| 67 | continue; |
||
| 68 | } |
||
| 69 | |||
| 70 | if ($line[$lastChar] == "\n" || $line[$lastChar] == "\r") { |
||
| 71 | ++$lines; |
||
| 72 | } |
||
| 73 | } |
||
| 74 | |||
| 75 | fclose($handle); |
||
| 76 | |||
| 77 | return $lines; |
||
| 78 | } |
||
| 79 | |||
| 80 | /** |
||
| 81 | * Extracts the extension (without the dot) of a filename alone or contained in a path. |
||
| 82 | * |
||
| 83 | * @param string $filename |
||
| 84 | * |
||
| 85 | * @return string |
||
| 86 | */ |
||
| 87 | public static function extractExtension(string $filename): string |
||
| 92 | } |
||
| 93 | } |
||
| 94 |