Mercurial > packages > magicforger
comparison src/Helpers/FileModifier.php @ 34:f65ab84ee47f default
merge with codex
| author | luka |
|---|---|
| date | Wed, 10 Sep 2025 21:00:47 -0400 |
| parents | 19b7a8de0019 |
| children |
comparison
equal
deleted
inserted
replaced
| 10:a9ff874afdbd | 34:f65ab84ee47f |
|---|---|
| 1 <?php | |
| 2 | |
| 3 namespace Wizard\MagicForger\Helpers; | |
| 4 | |
| 5 /* | |
| 6 * FileModifier | |
| 7 * | |
| 8 * A class that handles all file modifications | |
| 9 * | |
| 10 * General flow: | |
| 11 * Provide a file, a point to insert, and a value to insert. | |
| 12 * Insert the data. | |
| 13 * | |
| 14 * Replacements will consume the insert point. | |
| 15 * Inserts will maintain the insert point. | |
| 16 * | |
| 17 * */ | |
| 18 class FileModifier | |
| 19 { | |
| 20 private $contents; | |
| 21 | |
| 22 public $file_path; | |
| 23 | |
| 24 public function __construct($file_path) | |
| 25 { | |
| 26 $this->get_file_contents($file_path); | |
| 27 $this->file_path = $file_path; | |
| 28 } | |
| 29 | |
| 30 public function get_file_contents($file_path): void | |
| 31 { | |
| 32 // TODO: there needs to be more/any error checking | |
| 33 $f = fopen($file_path, 'r'); | |
| 34 $this->contents = fread($f, filesize($file_path)); | |
| 35 fclose($f); | |
| 36 } | |
| 37 | |
| 38 public function write_to_path($file_path = null): void | |
| 39 { | |
| 40 $file_path = $file_path ?? $this->file_path; | |
| 41 | |
| 42 $f = fopen($file_path, 'w'); | |
| 43 fwrite($f, $this->contents); | |
| 44 fclose($f); | |
| 45 } | |
| 46 | |
| 47 /** | |
| 48 * Replaces the replacement point with the value in the current contents. | |
| 49 */ | |
| 50 public function replace($value, $replacement_point): void | |
| 51 { | |
| 52 $this->contents = str_replace($replacement_point, $value, $this->contents); | |
| 53 } | |
| 54 | |
| 55 /** | |
| 56 * Inserts the value above the insert point in the current contents. | |
| 57 */ | |
| 58 public function insert($value, $insert_point): void | |
| 59 { | |
| 60 // seperate on new lines into an array | |
| 61 $file_arr = explode("\n", $this->contents); | |
| 62 $temp_arr = []; | |
| 63 | |
| 64 foreach ($file_arr as $line) { | |
| 65 if (str_contains($line, $insert_point)) { | |
| 66 $temp_arr[] = $value; | |
| 67 } | |
| 68 $temp_arr[] = $line; | |
| 69 } | |
| 70 | |
| 71 $this->contents = implode("\n", $temp_arr); | |
| 72 } | |
| 73 } |
