]> git.andy128k.dev Git - ipf-legacy-orm.git/commitdiff
simplify model builder
authorAndrey Kutejko <andy128k@gmail.com>
Thu, 11 Jul 2013 18:24:36 +0000 (21:24 +0300)
committerAndrey Kutejko <andy128k@gmail.com>
Thu, 11 Jul 2013 18:24:36 +0000 (21:24 +0300)
ipf/orm.php
ipf/orm/import/builder.php
ipf/orm/import/schema.php

index af280d630ba02cdc6f5b19b957ccbb6d6e2fb91e..bb5854ddb18e6f74b6f40dce804ff613cf16c939 100644 (file)
@@ -193,13 +193,14 @@ final class IPF_ORM
         $definitions = $import->importSchema($directory . '/models.yml', $extraAllwedReferences);
 
         // build
-        $builder = new IPF_ORM_Import_Builder;
-        $builder->setTargetPath($directory . '/models');
-
+        $targetPath = $directory . '/models';
         $models = array();
         foreach ($definitions as $name => $definition) {
             print "    $name\n";
-            $builder->buildRecord($definition);
+
+            $builder = new IPF_ORM_Import_Builder;
+            $builder->buildRecord($definition, $targetPath);
+
             $models[] = $name;
         }
 
index 862e2f9272dbfb56a6c3103121f60556f6658241..246e87b247c11170c4817a1eda97c0027a3ee611 100644 (file)
 
 class IPF_ORM_Import_Builder
 {
-    protected $_path = '';
-    protected $_packagesPrefix = 'Package';
-    protected $_packagesPath = '';
-    protected $_packagesFolderName = 'packages';
-    protected $_suffix = '.php';
-    protected $_baseClassPrefix = 'Base';
-    protected $_baseClassesDirectory = IPF_ORM::BASE_CLASSES_DIRECTORY;
-    protected $_baseClassName = 'IPF_ORM_Record';
-    protected $_generateAccessors = false;
-    protected static $_tpl;
+    private $_baseClassPrefix = 'Base';
+    private $_baseClassesDirectory = IPF_ORM::BASE_CLASSES_DIRECTORY;
 
     private static function varExport($var)
     {
         $export = var_export($var, true);
-        $export = str_replace("\n", '', $export);
-        $export = str_replace('  ', ' ', $export);
-        $export = str_replace('array ( ', 'array(', $export);
-        $export = str_replace('array( ', 'array(', $export);
-        $export = str_replace(',)', ')', $export);
-        $export = str_replace(', )', ')', $export);
-        $export = str_replace('  ', ' ', $export);
+        $export = preg_replace('#\s*\(\s*#', '(', $export);
+        $export = preg_replace('#[\s,]+\)#', ')', $export);
+        $export = preg_replace('#\s+#', ' ', $export);
         return $export;
     }
 
-    public function __construct()
-    {
-        $this->loadTemplate();
-    }
-
-    public function setTargetPath($path)
-    {
-        if ($path) {
-            if ( ! $this->_packagesPath) {
-                $this->setPackagesPath($path . DIRECTORY_SEPARATOR . $this->_packagesFolderName);
-            }
-
-            $this->_path = $path;
-        }
-    }
-
-    public function setPackagesPrefix($packagesPrefix)
-    {
-        $this->_packagesPrefix = $packagesPrefix;
-    }
-
-    public function setPackagesPath($packagesPath)
-    {
-        if ($packagesPath) {
-            $this->_packagesPath = $packagesPath;
-        }
-    }
-
-    public function generateAccessors($bool = null)
-    {
-      if ($bool !== null) {
-          $this->_generateAccessors = $bool;
-      }
-
-      return $this->_generateAccessors;
-    }
-
-    public function setBaseClassPrefix($prefix)
-    {
-        $this->_baseClassPrefix = $prefix;
-    }
-
-    public function getBaseClassPrefix()
-    {
-        return $this->_baseClassPrefix;
-    }
-
-    public function setbaseClassesDirectory($baseClassesDirectory)
-    {
-        $this->_baseClassesDirectory = $baseClassesDirectory;
-    }
-
-    public function setBaseClassName($className)
-    {
-        $this->_baseClassName = $className;
-    }
-
-    public function setSuffix($suffix)
-    {
-        $this->_suffix = $suffix;
-    }
-
-    public function getTargetPath()
-    {
-        return $this->_path;
-    }
-
-    public function setOptions($options)
-    {
-        if ( ! empty($options)) {
-            foreach ($options as $key => $value) {
-                $this->setOption($key, $value);
-            }
-        }
-    }
-
-    public function setOption($key, $value)
-    {
-        $name = 'set' . IPF_ORM_Inflector::classify($key);
-
-        if (method_exists($this, $name)) {
-            $this->$name($value);
-        } else {
-            $key = '_' . $key;
-            $this->$key = $value;
-        }
-    }
-
-    public function loadTemplate()
-    {
-        if (isset(self::$_tpl)) {
-            return;
-        }
-
-        self::$_tpl = '/**' . PHP_EOL
-                    . ' * This class has been auto-generated by the IPF_ORM Framework' . PHP_EOL
-                    . ' */' . PHP_EOL
-                    . '%sclass %s extends %s' . PHP_EOL
-                    . '{'
-                    . '%s' . PHP_EOL
-                    . '%s' . PHP_EOL
-                    . '%s'
-                    . '}';
-    }
-
-    public function buildTableDefinition(array $definition)
+    private function buildTableDefinition(array $definition)
     {
         if (isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) {
             return;
         }
 
-        $ret = array();
+        $ret = array(
+            '  public function setTableDefinition()',
+            '  {',
+        );
 
-        $i = 0;
+        if (isset($definition['inheritance']['type']) && $definition['inheritance']['type'] == 'concrete')
+            $ret[] = "    parent::setTableDefinition();";
 
-        if (isset($definition['inheritance']['type']) && $definition['inheritance']['type'] == 'concrete') {
-            $ret[$i] = "    parent::setTableDefinition();";
-            $i++;
-        }
+        if (isset($definition['tableName']) && !empty($definition['tableName']))
+            $ret[] = "    ".'$this->setTableName(\''. $definition['tableName'].'\');';
 
-        if (isset($definition['tableName']) && !empty($definition['tableName'])) {
-            $ret[$i] = "    ".'$this->setTableName(\''. $definition['tableName'].'\');';
-            $i++;
-        }
+        if (isset($definition['columns']) && is_array($definition['columns']) && !empty($definition['columns']))
+            $ret[] = $this->buildColumns($definition['columns']);
 
-        if (isset($definition['columns']) && is_array($definition['columns']) && !empty($definition['columns'])) {
-            $ret[$i] = $this->buildColumns($definition['columns']);
-            $i++;
-        }
-
-        if (isset($definition['indexes']) && is_array($definition['indexes']) && !empty($definition['indexes'])) {
-            $ret[$i] = $this->buildIndexes($definition['indexes']);
-            $i++;
-        }
+        if (isset($definition['indexes']) && is_array($definition['indexes']) && !empty($definition['indexes']))
+            foreach ($definition['indexes'] as $indexName => $definitions)
+                $ret[] = "    \$this->index('" . $indexName . "', " . self::varExport($definitions) . ');';
 
-        if (isset($definition['attributes']) && is_array($definition['attributes']) && !empty($definition['attributes'])) {
-            $ret[$i] = $this->buildAttributes($definition['attributes']);
-            $i++;
-        }
+        if (isset($definition['attributes']) && is_array($definition['attributes']) && !empty($definition['attributes']))
+            $ret[] = $this->buildAttributes($definition['attributes']);
 
-        if (isset($definition['options']) && is_array($definition['options']) && !empty($definition['options'])) {
-            $ret[$i] = $this->buildOptions($definition['options']);
-            $i++;
-        }
+        if (isset($definition['options']) && is_array($definition['options']) && !empty($definition['options']))
+            $ret[] = $this->buildOptions($definition['options']);
 
-        if (isset($definition['inheritance']['subclasses']) && ! empty($definition['inheritance']['subclasses'])) {
-            $ret[$i] = "    ".'$this->setSubClasses('. self::varExport($definition['inheritance']['subclasses']).');';
-            $i++;
-        }
+        if (isset($definition['inheritance']['subclasses']) && ! empty($definition['inheritance']['subclasses']))
+            $ret[] = "    ".'$this->setSubClasses('. self::varExport($definition['inheritance']['subclasses']).');';
 
-        $code = implode(PHP_EOL, $ret);
-        $code = trim($code);
+        $ret[] = '  }';
 
-        return PHP_EOL . "  public function setTableDefinition()" . PHP_EOL . '  {' . PHP_EOL . '    ' . $code . PHP_EOL . '  }';
+        return implode(PHP_EOL, $ret);
     }
 
-    public function buildSetUp(array $definition)
+    private function buildSetUp(array $definition)
     {
         $ret = array();
         $i = 0;
@@ -263,9 +133,8 @@ class IPF_ORM_Import_Builder
         }
 
         if (isset($definition['listeners']) && is_array($definition['listeners']) && !empty($definition['listeners'])) {
-            foreach($definition['listeners'] as $listener)
-            {
-                $ret[$i] = $this->buildListener($listener);
+            foreach($definition['listeners'] as $listener) {
+                $ret[$i] = PHP_EOL.'    $this->getTable()->listeners[\''.$listener.'\'] = new '.$listener.'();';
                 $i++;
             }
         }
@@ -287,15 +156,14 @@ class IPF_ORM_Import_Builder
         if ($code) {
             return '  public function setUp()' . PHP_EOL . '  {' . PHP_EOL . '    ' . $code . PHP_EOL . '  }';
         }
-        
     }
 
-    public function buildColumns(array $columns)
+    private function buildColumns(array $columns)
     {
-        $build = null;
+        $result = array();
         foreach ($columns as $name => $column) {
             $columnName = isset($column['name']) ? $column['name']:$name;
-            $build .= "    ".'$this->hasColumn(\'' . $columnName . '\', \'' . $column['type'] . '\'';
+            $build = "    ".'$this->hasColumn(\'' . $columnName . '\', \'' . $column['type'] . '\'';
 
             if ($column['length']) {
                 $build .= ', ' . $column['length'];
@@ -341,42 +209,15 @@ class IPF_ORM_Import_Builder
                 $build .= ', ' . self::varExport($options);
             }
 
-            $build .= ');' . PHP_EOL;
-        }
-
-        return $build;
-    }
-
-    public function buildAccessors(array $definition)
-    {
-        $accessors = array();
-        foreach (array_keys($definition['columns']) as $name) {
-            $accessors[] = $name;
-        }
-
-        foreach ($definition['relations'] as $relation) {
-            $accessors[] = $relation['alias'];
-        }
+            $build .= ');';
 
-        $ret = '';
-        foreach ($accessors as $name) {
-            // getters
-            $ret .= PHP_EOL . '  public function get' . IPF_ORM_Inflector::classify(IPF_ORM_Inflector::tableize($name)) . "(\$load = true)" . PHP_EOL;
-            $ret .= "  {" . PHP_EOL;
-            $ret .= "    return \$this->get('{$name}', \$load);" . PHP_EOL;
-            $ret .= "  }" . PHP_EOL;
-
-            // setters
-            $ret .= PHP_EOL . '  public function set' . IPF_ORM_Inflector::classify(IPF_ORM_Inflector::tableize($name)) . "(\${$name}, \$load = true)" . PHP_EOL;
-            $ret .= "  {" . PHP_EOL;
-            $ret .= "    return \$this->set('{$name}', \${$name}, \$load);" . PHP_EOL;
-            $ret .= "  }" . PHP_EOL;
+            $result[] = $build;
         }
 
-        return $ret;
+        return implode(PHP_EOL, $result);
     }
 
-    public function buildTemplates(array $templates)
+    private function buildTemplates(array $templates)
     {
         $build = '';
         foreach ($templates as $name => $options) {
@@ -417,7 +258,7 @@ class IPF_ORM_Import_Builder
         return "    \$this->actAs(\$" . strtolower($name) . "$level);" . PHP_EOL;
     }
 
-    public function buildActAs($actAs)
+    private function buildActAs($actAs)
     {
         $emittedActAs = array();
         $build = $this->innerBuildActAs($actAs, 0, null, $emittedActAs);
@@ -485,23 +326,16 @@ class IPF_ORM_Import_Builder
         return $build;
     }
 
-    public function buildListener($listener)
-    {
-        return PHP_EOL.'    $this->getTable()->listeners[\''.$listener.'\'] = new '.$listener.'();';
-    }
-
-    public function buildAttributes(array $attributes)
+    private function buildAttributes(array $attributes)
     {
         $build = PHP_EOL;
         foreach ($attributes as $key => $value) {
 
-            if (is_bool($value))
-            {
-              $values = $value ? 'true':'false';
+            if (is_bool($value)) {
+                $values = $value ? 'true':'false';
             } else {
-                if ( ! is_array($value)) {
+                if (!is_array($value))
                     $value = array($value);
-                }
 
                 $values = '';
                 foreach ($value as $attr) {
@@ -518,7 +352,7 @@ class IPF_ORM_Import_Builder
         return $build;
     }
 
-    public function buildOptions(array $options)
+    private function buildOptions(array $options)
     {
         $build = '';
         foreach ($options as $name => $value) {
@@ -528,180 +362,68 @@ class IPF_ORM_Import_Builder
         return $build;
     }
 
-    public function buildIndexes(array $indexes)
+    public function buildRecord(array $definition, $targetPath)
     {
-      $build = '';
-
-      foreach ($indexes as $indexName => $definitions) {
-          $build .= PHP_EOL . "    \$this->index('" . $indexName . "'";
-          $build .= ', ' . self::varExport($definitions);
-          $build .= ');';
-      }
-
-      return $build;
-    }
-
-    public function buildDefinition(array $definition)
-    {
-        if ( ! isset($definition['className'])) {
+        if (!isset($definition['className']))
             throw new IPF_ORM_Exception('Missing class name.');
-        }
-
-        $abstract = isset($definition['abstract']) && $definition['abstract'] === true ? 'abstract ':null;
-        $className = $definition['className'];
-        $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends']:$this->_baseClassName;
-
-        if ( ! (isset($definition['no_definition']) && $definition['no_definition'] === true)) {
-            $tableDefinitionCode = $this->buildTableDefinition($definition);
-            $setUpCode = $this->buildSetUp($definition);
-        } else {
-            $tableDefinitionCode = null;
-            $setUpCode = null;
-        }
-
-        if ($tableDefinitionCode && $setUpCode) {
-            $setUpCode = PHP_EOL . $setUpCode;
-        }
-
-        if ( ! isset($definition['generate_accessors']) || !$definition['generate_accessors']) {
-          $definition['generate_accessors'] = $this->generateAccessors();
-        }
-
-        $accessorsCode = (isset($definition['generate_accessors']) && $definition['generate_accessors'] === true) ? $this->buildAccessors($definition):null;
 
-        $content = sprintf(self::$_tpl, $abstract,
-                                       $className,
-                                       $extends,
-                                       $tableDefinitionCode,
-                                       $setUpCode,
-                                       $accessorsCode);
-
-        return $content;
+        $this->writeBaseDefinition($definition, $targetPath);
+        $this->writeModelDefinition($definition, $targetPath);
     }
 
-    public function buildRecord(array $definition)
+    private function writeBaseDefinition(array $definition, $targetPath)
     {
-        if (!isset($definition['className']))
-            throw new IPF_ORM_Exception('Missing class name.');
-
-        $definition['topLevelClassName'] = $definition['className'];
-        $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true:false;
-
-        if ($definition['is_package']) {
-            $e = explode('.', trim($definition['package']));
-            $definition['package_name'] = $e[0];
+        $code = array(
+            '<?php',
+            '',
+            '/**',
+            ' * This class has been auto-generated by the IPF_ORM Framework.',
+            ' * Changes to this file may cause incorrect behavior',
+            ' * and will be lost if the code is regenerated.',
+            ' */',
+            '',
+        );
 
-            $definition['package_path'] = ! empty($e) ? implode(DIRECTORY_SEPARATOR, $e):$definition['package_name'];
-        }
-        // Top level definition that extends from all the others
-        $topLevel = $definition;
-        unset($topLevel['tableName']);
-
-        // If we have a package then we need to make this extend the package definition and not the base definition
-        // The package definition will then extends the base definition
-        $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix . $topLevel['className']:$this->_baseClassPrefix . $topLevel['className'];
-        $topLevel['no_definition'] = true;
-        $topLevel['generate_once'] = true;
-        $topLevel['is_main_class'] = true;
-        unset($topLevel['connection']);
-
-        // Package level definition that extends from the base definition
-        if (isset($definition['package'])) {
-
-            $packageLevel = $definition;
-            $packageLevel['className'] = $topLevel['inheritance']['extends'];
-            $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix . $topLevel['className'];
-            $packageLevel['no_definition'] = true;
-            $packageLevel['abstract'] = true;
-            $packageLevel['override_parent'] = true;
-            $packageLevel['generate_once'] = true;
-            $packageLevel['is_package_class'] = true;
-            unset($packageLevel['connection']);
+        if (isset($definition['connection']) && $definition['connection']) {
+            $code[] = '// Connection Component Binding';
+            $code[] = "IPF_ORM_Manager::getInstance()->bindComponent('" . $definition['connectionClassName'] . "', '" . $definition['connection'] . "');";
+            $code[] = '';
         }
 
-        $baseClass = $definition;
-        $baseClass['className'] = $this->_baseClassPrefix . $baseClass['className'];
-        $baseClass['abstract'] = true;
-        $baseClass['override_parent'] = false;
-        $baseClass['is_base_class'] = true;
+        $code[] = 'abstract class '.$this->_baseClassPrefix.$definition['className'].' extends IPF_ORM_Record';
+        $code[] = '{';
+        $code[] = $this->buildTableDefinition($definition);
+        $code[] = '';
+        $code[] = $this->buildSetUp($definition);
+        $code[] = '}';
 
-        $this->writeDefinition($baseClass);
-
-        if ( ! empty($packageLevel)) {
-            $this->writeDefinition($packageLevel);
-        }
+        $fileName = $this->_baseClassPrefix . $definition['className'] . '.php';
+        $writePath = $targetPath . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory;
+        IPF_Utils::makeDirectories($writePath);
+        $writePath .= DIRECTORY_SEPARATOR . $fileName;
 
-        $this->writeDefinition($topLevel);
+        if (file_put_contents($writePath, implode(PHP_EOL, $code)) === false)
+            throw new IPF_ORM_Exception("Couldn't write file " . $writePath);
     }
 
-    public function writeDefinition(array $definition)
+    private function writeModelDefinition(array $definition, $targetPath)
     {
-        $definitionCode = $this->buildDefinition($definition);
-
-        $fileName = $definition['className'] . $this->_suffix;
-
-        $packagesPath = $this->_packagesPath ? $this->_packagesPath:$this->_path;
-
-        // If this is a main class that either extends from Base or Package class
-        if (isset($definition['is_main_class']) && $definition['is_main_class']) {
-            // If is package then we need to put it in a package subfolder
-            if (isset($definition['is_package']) && $definition['is_package']) {
-                $writePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name'];
-            // Otherwise lets just put it in the root of the path
-            } else {
-                $writePath = $this->_path;
-            }
-        }
-        // If is the package class then we need to make the path to the complete package
-        else if (isset($definition['is_package_class']) && $definition['is_package_class']) {
-            $writePath = $packagesPath . DIRECTORY_SEPARATOR . $definition['package_path'];
-        }
-        // If it is the base class of the IPF_ORM record definition
-        else if (isset($definition['is_base_class']) && $definition['is_base_class']) {
-            // If it is a part of a package then we need to put it in a package subfolder
-            if (isset($definition['is_package']) && $definition['is_package']) {
-                $basePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name'];
-                $writePath = $basePath . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory;
-            // Otherwise lets just put it in the root generated folder
-            } else {
-                $writePath = $this->_path . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory;
-            }
-        }
-
-        // If we have a writePath from the if else conditionals above then use it
-        if (isset($writePath)) {
-            IPF_Utils::makeDirectories($writePath);
-
-            $writePath .= DIRECTORY_SEPARATOR . $fileName;
-        // Otherwise none of the conditions were met and we aren't generating base classes
-        } else {
-            IPF_Utils::makeDirectories($this->_path);
-
-            $writePath = $this->_path . DIRECTORY_SEPARATOR . $fileName;
-        }
-
-        $code = "<?php" . PHP_EOL;
-
-        if (isset($definition['connection']) && $definition['connection']) {
-            $code .= "// Connection Component Binding" . PHP_EOL;
-            $code .= "IPF_ORM_Manager::getInstance()->bindComponent('" . $definition['connectionClassName'] . "', '" . $definition['connection'] . "');" . PHP_EOL;
-        }
+        $className = $definition['className'];
 
-        $code .= PHP_EOL . $definitionCode;
+        $writePath = $targetPath . DIRECTORY_SEPARATOR . $className . '.php';
+        if (file_exists($writePath))
+            return;
 
-        if (isset($definition['generate_once']) && $definition['generate_once'] === true) {
-            if ( ! file_exists($writePath)) {
-                $bytes = file_put_contents($writePath, $code);
-            }
-        } else {
-            $bytes = file_put_contents($writePath, $code);
-        }
+        $code = sprintf("<?php\n\nclass %s extends %s%s\n{\n}\n",
+            $className,
+            $this->_baseClassPrefix,
+            $className);
 
-        if (isset($bytes) && $bytes === false) {
+        IPF_Utils::makeDirectories($targetPath);
+        if (file_put_contents($writePath, $code) === false)
             throw new IPF_ORM_Exception("Couldn't write file " . $writePath);
-        }
 
-        IPF_ORM::loadModel($definition['className'], $writePath);
+        IPF_ORM::loadModel($className, $writePath);
     }
 }
 
index 7262e75c6c737068643aa5969262f1e035b2eaf2..b62fe8d51dd7c43d9238f0f29e7448fc6964b781 100644 (file)
@@ -18,10 +18,8 @@ class IPF_ORM_Import_Schema
             'templates',
             'actAs',
             'options',
-            'package',
             'inheritance',
             'detect_relations',
-            'generate_accessors',
             'listeners',
         ),
         'column' => array(
@@ -99,10 +97,8 @@ class IPF_ORM_Import_Schema
                           'templates'           =>  array(),
                           'actAs'               =>  array(),
                           'options'             =>  array(),
-                          'package'             =>  null,
                           'inheritance'         =>  array(),
-                          'detect_relations'    =>  false,
-                          'generate_accessors'  =>  false);
+                          'detect_relations'    =>  false);
         
         $array = IPF_ORM_Parser::load($schema, $type);
 
@@ -113,10 +109,8 @@ class IPF_ORM_Import_Schema
                             'templates',
                             'actAs',
                             'options',
-                            'package',
                             'inheritance',
-                            'detect_relations',
-                            'generate_accessors');
+                            'detect_relations');
 
         // Loop over and build up all the global values and remove them from the array
         foreach ($array as $key => $value) {