comparison src/Helpers/FileModifier.php @ 12:4bb4daa9e3f1 development

Working with the new FileModifier
author luka
date Wed, 24 Apr 2024 19:52:35 -0400
parents
children c969ed13c570
comparison
equal deleted inserted replaced
4:a20439b1c9d3 12:4bb4daa9e3f1
1 <?php
2
3 namespace Wizzard\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 /**
23 * @var mixed
24 */
25 public $file_path;
26
27
28 /**
29 * @param mixed $file_path
30 */
31 public function __construct($file_path)
32 {
33 $this->get_file_contents($file_path);
34 $this->file_path = $file_path;
35 }
36
37
38 /**
39 * @param mixed $file_path
40 * @return void
41 */
42 public function get_file_contents($file_path): void
43 {
44 //TODO: there needs to be more/any error checking
45 $f = fopen($file_path, "r");
46 $this->contents = fread($f, filesize($file_path));
47 fclose($f);
48 }
49
50
51 /**
52 * @param mixed $file_path
53 */
54 public function write_to_path($file_path = null): void
55 {
56 $file_path = $file_path ?? $this->file_path;
57
58 $f = fopen($file_path, "w");
59 fwrite($f, $this->contents);
60 fclose($f);
61 }
62
63
64 /**
65 * Replaces the replacement point with the value in the current contents
66 *
67 * @param mixed $value
68 * @param mixed $replacement_point
69 */
70 public function replace($value, $replacement_point): void
71 {
72 $this->contents = str_replace($replacement_point, $value, $this->contents);
73 }
74
75
76 /**
77 * Inserts the value above the insert point in the current contents
78 *
79 * @param mixed $value
80 * @param mixed $insert_point
81 * @return void
82 */
83 public function insert($value, $insert_point): void
84 {
85 //seperate on new lines into an array
86 $file_arr = explode("\n", $this->contents);
87 $temp_arr = [];
88
89 foreach($file_arr as $line) {
90 if(str_contains($line, $insert_point)) {
91 $temp_arr[] = $value;
92 }
93 $temp_arr[] = $line;
94 }
95
96 $this->contents = implode("\n",$temp_arr);
97 }
98 }