|
12
|
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 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 {
|
|
14
|
32 // TODO: there needs to be more/any error checking
|
|
|
33 $f = fopen($file_path, 'r');
|
|
12
|
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
|
|
14
|
42 $f = fopen($file_path, 'w');
|
|
12
|
43 fwrite($f, $this->contents);
|
|
|
44 fclose($f);
|
|
|
45 }
|
|
|
46
|
|
|
47 /**
|
|
14
|
48 * Replaces the replacement point with the value in the current contents.
|
|
12
|
49 */
|
|
|
50 public function replace($value, $replacement_point): void
|
|
|
51 {
|
|
|
52 $this->contents = str_replace($replacement_point, $value, $this->contents);
|
|
|
53 }
|
|
|
54
|
|
|
55 /**
|
|
14
|
56 * Inserts the value above the insert point in the current contents.
|
|
12
|
57 */
|
|
|
58 public function insert($value, $insert_point): void
|
|
|
59 {
|
|
14
|
60 // seperate on new lines into an array
|
|
12
|
61 $file_arr = explode("\n", $this->contents);
|
|
|
62 $temp_arr = [];
|
|
|
63
|
|
14
|
64 foreach ($file_arr as $line) {
|
|
|
65 if (str_contains($line, $insert_point)) {
|
|
12
|
66 $temp_arr[] = $value;
|
|
|
67 }
|
|
|
68 $temp_arr[] = $line;
|
|
|
69 }
|
|
|
70
|
|
14
|
71 $this->contents = implode("\n", $temp_arr);
|
|
12
|
72 }
|
|
|
73 }
|