diff src/Helpers/FileModifier.php @ 34:f65ab84ee47f default

merge with codex
author luka
date Wed, 10 Sep 2025 21:00:47 -0400
parents 19b7a8de0019
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Helpers/FileModifier.php	Wed Sep 10 21:00:47 2025 -0400
@@ -0,0 +1,73 @@
+<?php
+
+namespace Wizard\MagicForger\Helpers;
+
+/*
+ * FileModifier
+ *
+ * A class that handles all file modifications
+ *
+ * General flow:
+ * Provide a file, a point to insert, and a value to insert.
+ * Insert the data.
+ *
+ * Replacements will consume the insert point.
+ * Inserts will maintain the insert point.
+ *
+ * */
+class FileModifier
+{
+    private $contents;
+
+    public $file_path;
+
+    public function __construct($file_path)
+    {
+        $this->get_file_contents($file_path);
+        $this->file_path = $file_path;
+    }
+
+    public function get_file_contents($file_path): void
+    {
+        // TODO: there needs to be more/any error checking
+        $f = fopen($file_path, 'r');
+        $this->contents = fread($f, filesize($file_path));
+        fclose($f);
+    }
+
+    public function write_to_path($file_path = null): void
+    {
+        $file_path = $file_path ?? $this->file_path;
+
+        $f = fopen($file_path, 'w');
+        fwrite($f, $this->contents);
+        fclose($f);
+    }
+
+    /**
+     * Replaces the replacement point with the value in the current contents.
+     */
+    public function replace($value, $replacement_point): void
+    {
+        $this->contents = str_replace($replacement_point, $value, $this->contents);
+    }
+
+    /**
+     * Inserts the value above the insert point in the current contents.
+     */
+    public function insert($value, $insert_point): void
+    {
+        // seperate on new lines into an array
+        $file_arr = explode("\n", $this->contents);
+        $temp_arr = [];
+
+        foreach ($file_arr as $line) {
+            if (str_contains($line, $insert_point)) {
+                $temp_arr[] = $value;
+            }
+            $temp_arr[] = $line;
+        }
+
+        $this->contents = implode("\n", $temp_arr);
+    }
+}