Parse and validate AT Protocol Lexicons with DTO generation for Laravel
at dev 2.7 kB view raw
1<?php 2 3namespace SocialDept\AtpSchema\Generator; 4 5use SocialDept\AtpSchema\Exceptions\GenerationException; 6 7class FileWriter 8{ 9 /** 10 * Whether to overwrite existing files. 11 */ 12 protected bool $overwrite = false; 13 14 /** 15 * Whether to create directories if they don't exist. 16 */ 17 protected bool $createDirectories = true; 18 19 /** 20 * Create a new FileWriter. 21 */ 22 public function __construct(bool $overwrite = false, bool $createDirectories = true) 23 { 24 $this->overwrite = $overwrite; 25 $this->createDirectories = $createDirectories; 26 } 27 28 /** 29 * Write content to a file. 30 */ 31 public function write(string $path, string $content): void 32 { 33 // Check if file exists and we're not allowed to overwrite 34 if (file_exists($path) && ! $this->overwrite) { 35 throw GenerationException::fileExists($path); 36 } 37 38 // Create directory if it doesn't exist 39 $directory = dirname($path); 40 41 if (! is_dir($directory)) { 42 if (! $this->createDirectories) { 43 throw GenerationException::directoryNotFound($directory); 44 } 45 46 if (! @mkdir($directory, 0755, true) && ! is_dir($directory)) { 47 throw GenerationException::cannotCreateDirectory($directory); 48 } 49 } 50 51 // Write file 52 $result = @file_put_contents($path, $content); 53 54 if ($result === false) { 55 throw GenerationException::cannotWriteFile($path); 56 } 57 } 58 59 /** 60 * Check if file exists. 61 */ 62 public function exists(string $path): bool 63 { 64 return file_exists($path); 65 } 66 67 /** 68 * Delete a file. 69 */ 70 public function delete(string $path): void 71 { 72 if (! file_exists($path)) { 73 return; 74 } 75 76 if (! @unlink($path)) { 77 throw GenerationException::cannotDeleteFile($path); 78 } 79 } 80 81 /** 82 * Read file content. 83 */ 84 public function read(string $path): string 85 { 86 if (! file_exists($path)) { 87 throw GenerationException::fileNotFound($path); 88 } 89 90 $content = @file_get_contents($path); 91 92 if ($content === false) { 93 throw GenerationException::cannotReadFile($path); 94 } 95 96 return $content; 97 } 98 99 /** 100 * Set whether to overwrite existing files. 101 */ 102 public function setOverwrite(bool $overwrite): void 103 { 104 $this->overwrite = $overwrite; 105 } 106 107 /** 108 * Set whether to create directories. 109 */ 110 public function setCreateDirectories(bool $createDirectories): void 111 { 112 $this->createDirectories = $createDirectories; 113 } 114}