view 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
line wrap: on
line source

<?php

namespace Wizzard\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;

    /**
     * @var mixed
     */
    public $file_path;


    /**
     * @param mixed $file_path
     */
    public function __construct($file_path)
    {
        $this->get_file_contents($file_path);
        $this->file_path = $file_path;
    }


    /**
     * @param mixed $file_path
     * @return void
     */
    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);
    }


    /**
     * @param mixed $file_path
     */
    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
         *
     * @param mixed $value
     * @param mixed $replacement_point
     */
    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
         *
     * @param mixed $value
     * @param mixed $insert_point
     * @return void
     */
    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);
    }
}