Zazalt/EntityMaker

View on GitHub
src/EntityMaker.php

Summary

Maintainability
C
1 day
Test Coverage
<?php

namespace Zazalt\EntityMaker;

class EntityMaker extends \Zazalt\Databaser\Databaser
{
    private $System;
    private $exportTo;
    private $namespace;
    private $extends;
    private $constructInject;

    public function __construct()
    {
        $this->System = new \Zazalt\System\System();
    }

    /**
     * @return $this
     */
    public function setNamespace($namespace)
    {
        $this->namespace = $namespace;
        return $this;
    }

    /**
     * @return $this
     */
    public function setExtends($extends)
    {
        $this->extends = $extends;
        return $this;
    }

    /**
     * @return $this
     */
    public function setConstructInject($parameters)
    {
        $this->constructInject = $parameters;
        return $this;
    }

    /**
     * @return $this
     */
    public function exportTo($exportTo)
    {
        $this->exportTo = $exportTo;
        return $this;
    }

    public function run()
    {
        // Call Databaser to return all DB tables and rows
        $entities = parent::run();

        $this->System->recursiveCreateDirectory($this->exportTo . '/AutoGenerated/Model');
        $this->System->recursiveCreateDirectory($this->exportTo . '/AutoGenerated/Repository');

        foreach ($entities as $entity => $rows) {
            $this->createEntity([$entity => $rows]);
        }
    }

    /**
     * Will create the entity only once, if not exits
     */
    private function createEntity(array $entity): void
    {
        $entityNameCamelCase         =   \Zazalt\Strink\Strink::turn(key($entity))->snakeCaseToCamelCase(true);
        $fileTemplateContent         =   file_get_contents(dirname(__FILE__).'/Templates/Entity.php');

        $fileTemplateContent = strtr($fileTemplateContent, [
            '___CLASS___'       =>  $entityNameCamelCase,
            '___NAMESPACE___'   =>  $this->namespace,
            '___TABLE___'       =>  key($entity),
            '___DATETIME___'    =>  date('Y-m-d H:i:s'),
            '##extends##'       =>  'extends \\'. $this->namespace .'\AutoGenerated\Model\\'. $entityNameCamelCase,
            '##construct##'     =>  "public function __construct()\n\t{\n\t\tparent::__construct();\n\t}"
        ]);

        if($this->constructInject) {
            $fileTemplateContent = str_replace('::__construct()', "::__construct({$this->constructInject})", $fileTemplateContent);
            $fileTemplateContent = str_replace('parent::', "global {$this->constructInject};\n\t\tparent::", $fileTemplateContent);
        }

        $modelPath = $this->exportTo ."/{$entityNameCamelCase}.php";
        if(!file_exists($modelPath)) {
            file_put_contents($this->exportTo ."/{$entityNameCamelCase}.php", $fileTemplateContent);
        }

        /* extends */ $this->createAutoGeneratedRepository($entity);
        /* extends */ $this->creatAutoGeneratedModel($entity);
    }

    /**
     * Will create (ALL THE TIME) the files inside of /AutoGenerated/Repository/ directory
     */
    private function createAutoGeneratedRepository(array $entity)
    {
        $entityNameCamelCase     =   \Zazalt\Strink\Strink::turn(key($entity))->snakeCaseToCamelCase(true);
        $fileTemplateContent     =   file_get_contents(dirname(__FILE__).'/Templates/AutoGenerated/Repository/Repository.php');
        $fileTemplateContent     =   strtr($fileTemplateContent, [
            '___CLASS___'       =>  $entityNameCamelCase,
            '___NAMESPACE___'   =>  $this->namespace .'\AutoGenerated\Repository',
            '___TABLE___'       =>  key($entity),
            '___DATE___'        =>  date('Y-m-d H:i:s'),
            '##extends##'       =>  ($this->extends ? 'extends '. $this->extends : ''),
            '##construct##'     =>  ($this->extends ? "public function __construct()\n\t{\n\t\tparent::__construct();\n\t}" : '')
        ]);

        if($this->constructInject) {
            $fileTemplateContent = str_replace('__construct()', "__construct({$this->constructInject})", $fileTemplateContent);
        }

        /**
         * create()   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         */
        $create = '';
        $createToReturn = [];
        foreach($entity as $entityName => $rows) {
            $create .= "\$params = [";
            foreach ($rows as $rowName => $row) {
                $rowNameUcfCamelCase    = \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase(true);

                if(!boolval($row['primaryKey'])) {
                    $createToReturn[] = $rowName;
                    $create .= "\n\t\t\t'{$rowName}' => \$this->get{$rowNameUcfCamelCase}(),";
                } else {
                    $createToReturn[] = $rowName;
                }
            }
            $create .= "\n\t\t];";
        }
        $create .= "\n\t\treturn \$this->populateFromArray(\$this->insert(\$params, ['". implode("','", $createToReturn) ."']));";
        $fileTemplateContent = str_replace('#create()#', $create, $fileTemplateContent);

        /**
         * update()   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         */
        $update = '';
        $updateToReturn = [];
        foreach($entity as $entityName => $rows) {
            $update .= "\$params = [";
            foreach ($rows as $rowName => $row) {
                $rowNameUcfCamelCase    = \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase(true);

                if(!boolval($row['primaryKey'])) {
                    $updateToReturn[] = $rowName;
                    $update .= "\n\t\t\t'{$rowName}' => \$this->get{$rowNameUcfCamelCase}(),";
                } else {
                    $updateToReturn[] = $rowName;
                }
            }
            $update .= "\n\t\t];";
        }
        $update .= "\n\t\tif(\$this->updateRaw(\$params, [['id', '=', \$this->getId()]])) {}";
        $update .= "\n\t\treturn \$this->populateFromArray(\$params);";
        $fileTemplateContent = str_replace('#update()#', $update, $fileTemplateContent);

        /*
        $params = [
            'name' => $this->getName(),
        ];

        return $this->updateRaw($params, [
            ['id', '=', $this->getId()]
        ]);
         */

        /**
         * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         */

        $content = "return [";
        foreach ($createToReturn as $index => $rowName) {
            $rowNameUcfCamelCase    = \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase(true);
            $content .= "\n\t\t\t'{$rowName}' => \$this->get{$rowNameUcfCamelCase}(),";
        }
        $content .= "\n\t\t];";

        //$fileTemplateContent = str_replace('#toArray()#', "return [\n\t\t\t'". implode("' => \$this->get(),\n\t\t\t'", $createToReturn) ."' => \$this->get()\n\t\t];", $fileTemplateContent);
        $fileTemplateContent = str_replace('#toArray()#', $content, $fileTemplateContent);

        /**
         * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
         */

        //$create .= "\n\t\treturn \$this->populateFromArray(\$this->insert(\$params, ['". implode("','", $createToReturn) ."']));";

        // Final
        file_put_contents($this->exportTo ."/AutoGenerated/Repository/{$entityNameCamelCase}.php", $fileTemplateContent);
    }

    /**
     * Will create (ALL THE TIME) the files inside of /AutoGenerated/Model/ directory
     */
    private function creatAutoGeneratedModel(array $entity)
    {
        $entityNameCamelCase    =   \Zazalt\Strink\Strink::turn(key($entity))->snakeCaseToCamelCase(true);
        $fileTemplateContent    =   file_get_contents(dirname(__FILE__).'/Templates/AutoGenerated/Model/Model.php');
        $fileTemplateContent    =   str_replace("##construct##", "protected \$modelName = '". key($entity) ."';\n\n\t##construct##", $fileTemplateContent);
        $fileTemplateContent    =   strtr($fileTemplateContent, [
            '___CLASS___'       =>  $entityNameCamelCase,
            '___NAMESPACE___'   =>  $this->namespace .'\AutoGenerated\Model',
            '___TABLE___'       =>  key($entity),
            '___DATE___'        =>  date('Y-m-d H:i:s'),
            '##extends##'       =>  'extends \\'. $this->namespace .'\AutoGenerated\Repository\\'. $entityNameCamelCase,
            '##construct##'     =>  ($this->extends ? "public function __construct()\n\t{\n\t\tparent::__construct();\n\t}" : '')
        ]);

        $members = '';
        $methods = '';
        $index = 0;

        foreach($entity as $entityName => $rows) {

            foreach($rows as $rowName => $row) {
                $members .= ($index > 0 ? "\n" : null);
                $members .= "\n\t/**";
                $members .= "\n\t* @rowName\t\t". $rowName;
                //$members .= "\n\t* @nullable\t\t{$entity['is_nullable']}";
                $members .= "\n\t* @primaryKey\t". (boolval($row['primaryKey']) ? 'true' : 'false');
                $members .= "\n\t* @type\t\t\t{$row['type']}";
                $members .= "\n\t* @default\t\t{$row['default']}";
                $members .= "\n\t*/";
                $members .= "\n\t";
                $members .= 'protected $'. \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase(false) .';';
                ++$index;
            }

            /*
            foreach($rows as $rowName => $row) {
                if($row['primaryKey']) {
                    $rows = array_merge([
                        'primaryKey' => array_merge(['primaryKey' => $rowName], $row)
                    ], $rows);
                }
            }
            */

            //print_r($rows);die;

            foreach($rows as $rowName => $row) {
                $rowNameUcfCamelCase    = \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase(true);
                $rowNameCamelCase       = \Zazalt\Strink\Strink::turn($rowName)->snakeCaseToCamelCase();

                $methods .= "\n\n\t/**\n\t * @return {$entityNameCamelCase}\n\t */";
                $methods .= "\n\tpublic function set". $rowNameUcfCamelCase ."(\${$rowNameCamelCase})\n\t{\n\t\t\$this->{$rowNameCamelCase} = \${$rowNameCamelCase};\n\t\treturn \$this;\n\t}";
                $methods .= "\n\n\tpublic function get". $rowNameUcfCamelCase ."()\n\t{\n\t\treturn \$this->{$rowNameCamelCase};\n\t}";
            }
        }

        $fileTemplateContent = str_replace('##members##', $members, $fileTemplateContent);
        $fileTemplateContent = str_replace('##methods##', $methods, $fileTemplateContent);

        file_put_contents($this->exportTo ."/AutoGenerated/Model/{$entityNameCamelCase}.php", $fileTemplateContent);
    }
}