view src/Replacer/TableReplacer.php @ 19:19b7a8de0019 main-dev

updating namespace from typo
author Luka Sitas <sitas.luka.97@gmail.com>
date Wed, 26 Feb 2025 19:26:08 -0500
parents c969ed13c570
children f0b0d014e448
line wrap: on
line source

<?php

namespace Wizard\MagicForger\Replacer;

trait TableReplacer
{
    protected $columns;

    protected function get_columns()
    {
        if (is_null($this->columns)) {
            $this->columns = $this->getCurrentTable()->getColumns();
        }

        return $this->columns;
    }

    protected function get_attributes()
    {
    }

    protected function getValuesForCreation(): string
    {
        $insert = '';
        foreach ($this->get_columns() as $column) {
            $insert .= '$item->'.$column->getName().' = $validated["'.$column->getName().'"] ?? NULL;'."\n";
        }

        return $insert;
    }

    protected function getAttributes(): string
    {
        $insert = '';
        foreach ($this->get_columns() as $column) {
            $insert .= "'".$column->getName()."' => '',\n";
        }

        return $insert;
    }

    protected function getValuesForValidation(): string
    {
        $insert = '';
        foreach ($this->get_columns() as $column) {
            $insert .= "'".$column->getName()."' => 'nullable',\n";
        }

        return $insert;
    }

    public function apply_inserts(string $target): string
    {
        $inserts = $this->get_all_keywords($target);
        $available_replacements = $this->get_available_inserts();

        $target = str_replace(
            array_keys($available_replacements),
            $available_replacements,
            $target
        );

        return $target;
    }

    public function get_available_inserts()
    {
        $table_name = $this->getTableInput();
        $replacements = [
                        '// {{ valuesForCreation }}' => self::getValuesForCreation(),
                        '# {{ atributeInsertPoint }}' => self::getAttributes(),
                        '// {{ valuesForValidation }}' => self::getValuesForValidation(),
                    ];

        foreach ($replacements as $key => &$replacement) {
            $replacement = $replacement."\n".$key;
        }

        return $replacements;
    }
}