コード例 #1
0
 public function createClassTemplate($taskName, $time = null)
 {
     if (!$time) {
         $time = time();
     } elseif (is_string($time)) {
         $time = strtotime($time);
     }
     $className = $taskName . '_' . $time;
     $template = new ClassFile($className);
     $template->extendClass('LazyRecord\\Migration\\Migration');
     return $template;
 }
コード例 #2
0
 public static function create(DeclareSchema $schema, $baseCollectionClass)
 {
     $cTemplate = new ClassFile($schema->getBaseCollectionClass());
     $cTemplate->addConsts(array('SCHEMA_PROXY_CLASS' => $schema->getSchemaProxyClass(), 'MODEL_CLASS' => $schema->getModelClass(), 'TABLE' => $schema->getTable(), 'READ_SOURCE_ID' => $schema->getReadSourceId(), 'WRITE_SOURCE_ID' => $schema->getWriteSourceId(), 'PRIMARY_KEY' => $schema->primaryKey));
     if ($traitClasses = $schema->getCollectionTraitClasses()) {
         foreach ($traitClasses as $traitClass) {
             $cTemplate->useTrait($traitClass);
         }
     }
     $cTemplate->extendClass('\\' . $baseCollectionClass);
     // interfaces
     if ($ifs = $schema->getCollectionInterfaces()) {
         foreach ($ifs as $iface) {
             $cTemplate->implementClass($iface);
         }
     }
     return $cTemplate;
 }
コード例 #3
0
 public static function create(DeclareSchema $schema, $baseCollectionClass)
 {
     $cTemplate = new ClassFile($schema->getBaseCollectionClass());
     $cTemplate->addConsts(array('schema_proxy_class' => $schema->getSchemaProxyClass(), 'model_class' => $schema->getModelClass(), 'table' => $schema->getTable(), 'read_source_id' => $schema->getReadSourceId(), 'write_source_id' => $schema->getWriteSourceId()));
     if ($traitClasses = $schema->getCollectionTraitClasses()) {
         foreach ($traitClasses as $traitClass) {
             $cTemplate->useTrait($traitClass);
         }
     }
     $cTemplate->extendClass('\\' . $baseCollectionClass);
     // interfaces
     if ($ifs = $schema->getCollectionInterfaces()) {
         foreach ($ifs as $iface) {
             $cTemplate->implementClass($iface);
         }
     }
     return $cTemplate;
 }
コード例 #4
0
ファイル: SchemaGenerator.php プロジェクト: azole/LazyRecord
 /**
  * Write class template to the schema directory.
  *
  * @param string $directory The schema class directory.
  * @param ClassTemplate\ClassFile class template object.
  * @param boolean $overwrite Overwrite class file. 
  * @return array
  */
 public function writeClassTemplateToPath(ClassFile $cTemplate, $filepath, $overwrite = false)
 {
     if (!file_exists($filepath) || $overwrite) {
         if (false === file_put_contents($filepath, $cTemplate->render())) {
             throw RuntimeException("Can not write file {$filepath}");
         }
         return true;
     } elseif (file_exists($filepath)) {
         return true;
     }
     return false;
 }
コード例 #5
0
 public static function create(DeclareSchema $schema)
 {
     $cTemplate = new ClassFile($schema->getCollectionClass());
     $cTemplate->extendClass('\\' . $schema->getBaseCollectionClass());
     return $cTemplate;
 }
コード例 #6
0
 public static function create(DeclareSchema $schema, $baseClass)
 {
     $cTemplate = new ClassFile($schema->getBaseModelClass());
     $cTemplate->addConsts(array('schema_proxy_class' => $schema->getSchemaProxyClass(), 'collection_class' => $schema->getCollectionClass(), 'model_class' => $schema->getModelClass(), 'table' => $schema->getTable(), 'read_source_id' => $schema->getReadSourceId(), 'write_source_id' => $schema->getWriteSourceId(), 'primary_key' => $schema->primaryKey));
     $cTemplate->addMethod('public', 'getSchema', [], ['if ($this->_schema) {', '   return $this->_schema;', '}', 'return $this->_schema = \\LazyRecord\\Schema\\SchemaLoader::load(' . var_export($schema->getSchemaProxyClass(), true) . ');']);
     $cTemplate->addStaticVar('column_names', $schema->getColumnNames());
     $cTemplate->addStaticVar('column_hash', array_fill_keys($schema->getColumnNames(), 1));
     $cTemplate->addStaticVar('mixin_classes', array_reverse($schema->getMixinSchemaClasses()));
     if ($traitClasses = $schema->getModelTraitClasses()) {
         foreach ($traitClasses as $traitClass) {
             $cTemplate->useTrait($traitClass);
         }
     }
     $cTemplate->extendClass('\\' . $baseClass);
     // interfaces
     if ($ifs = $schema->getModelInterfaces()) {
         foreach ($ifs as $iface) {
             $cTemplate->implementClass($iface);
         }
     }
     // Create column accessor
     if ($schema->enableColumnAccessors) {
         foreach ($schema->getColumnNames() as $columnName) {
             $accessorMethodName = 'get' . ucfirst(Inflector::camelize($columnName));
             $cTemplate->addMethod('public', $accessorMethodName, [], ['if (isset($this->_data[' . var_export($columnName, true) . '])) {', '    return $this->_data[' . var_export($columnName, true) . '];', '}']);
         }
     }
     return $cTemplate;
 }
コード例 #7
0
 public static function create(DeclareSchema $schema)
 {
     $schemaClass = get_class($schema);
     $schemaArray = $schema->export();
     $cTemplate = new ClassFile($schema->getSchemaProxyClass());
     $cTemplate->extendClass('\\LazyRecord\\Schema\\RuntimeSchema');
     $cTemplate->addConsts(array('schema_class' => $schemaClass, 'model_name' => $schema->getModelName(), 'model_namespace' => $schema->getNamespace(), 'COLLECTION_CLASS' => $schemaArray['collection_class'], 'MODEL_CLASS' => $schemaArray['model_class'], 'PRIMARY_KEY' => $schema->getPrimaryKey(), 'TABLE' => $schema->getTable(), 'LABEL' => $schema->getLabel()));
     $cTemplate->useClass('\\LazyRecord\\Schema\\RuntimeColumn');
     $cTemplate->useClass('\\LazyRecord\\Schema\\Relationship');
     $cTemplate->addPublicProperty('columnNames', $schema->getColumnNames());
     $cTemplate->addPublicProperty('primaryKey', $schema->getPrimaryKey());
     $cTemplate->addPublicProperty('columnNamesIncludeVirtual', $schema->getColumnNames(true));
     $cTemplate->addPublicProperty('label', $schemaArray['label']);
     $cTemplate->addPublicProperty('readSourceId', $schemaArray['read_data_source']);
     $cTemplate->addPublicProperty('writeSourceId', $schemaArray['write_data_source']);
     $cTemplate->addPublicProperty('relations', array());
     $cTemplate->addStaticVar('column_hash', array_fill_keys($schema->getColumnNames(), 1));
     $cTemplate->addStaticVar('mixin_classes', array_reverse($schema->getMixinSchemaClasses()));
     $constructor = $cTemplate->addMethod('public', '__construct', []);
     if (!empty($schemaArray['relations'])) {
         $constructor->block[] = '$this->relations = ' . php_var_export($schemaArray['relations']) . ';';
     }
     foreach ($schemaArray['column_data'] as $columnName => $columnAttributes) {
         // $this->columns[ $column->name ] = new RuntimeColumn($column->name, $column->export());
         $constructor->block[] = '$this->columns[ ' . var_export($columnName, true) . ' ] = new RuntimeColumn(' . var_export($columnName, true) . ',' . php_var_export($columnAttributes['attributes']) . ');';
     }
     // $method->block[] = 'parent::__construct();';
     /*
     // export column names including virutal columns
     // Aggregate basic translations from labels
     $msgIds = $schema->getMsgIds();
     $cTemplate->setMsgIds($msgIds);
     */
     return $cTemplate;
 }
コード例 #8
0
 public static function create(DeclareSchema $schema, $baseClass)
 {
     $cTemplate = new ClassFile($schema->getBaseModelClass());
     $cTemplate->useClass('LazyRecord\\Schema\\SchemaLoader');
     $cTemplate->useClass('LazyRecord\\Result');
     $cTemplate->useClass('SQLBuilder\\Bind');
     $cTemplate->useClass('SQLBuilder\\ArgumentArray');
     $cTemplate->useClass('PDO');
     $cTemplate->useClass('SQLBuilder\\Universal\\Query\\InsertQuery');
     $cTemplate->addConsts(array('SCHEMA_PROXY_CLASS' => $schema->getSchemaProxyClass(), 'COLLECTION_CLASS' => $schema->getCollectionClass(), 'MODEL_CLASS' => $schema->getModelClass(), 'TABLE' => $schema->getTable(), 'READ_SOURCE_ID' => $schema->getReadSourceId(), 'WRITE_SOURCE_ID' => $schema->getWriteSourceId(), 'PRIMARY_KEY' => $schema->primaryKey));
     $cTemplate->addProtectedProperty('table', $schema->getTable());
     $cTemplate->addPublicProperty('readSourceId', $schema->getReadSourceId() ?: 'default');
     $cTemplate->addPublicProperty('writeSourceId', $schema->getWriteSourceId() ?: 'default');
     $cTemplate->addMethod('public', 'getSchema', [], ['if ($this->_schema) {', '   return $this->_schema;', '}', 'return $this->_schema = SchemaLoader::load(' . var_export($schema->getSchemaProxyClass(), true) . ');']);
     $cTemplate->addStaticVar('column_names', $schema->getColumnNames());
     $cTemplate->addStaticVar('column_hash', array_fill_keys($schema->getColumnNames(), 1));
     $cTemplate->addStaticVar('mixin_classes', array_reverse($schema->getMixinSchemaClasses()));
     if ($traitClasses = $schema->getModelTraitClasses()) {
         foreach ($traitClasses as $traitClass) {
             $cTemplate->useTrait($traitClass);
         }
     }
     $schemaReflection = new ReflectionClass($schema);
     $schemaDocComment = $schemaReflection->getDocComment();
     // TODO: apply settings from schema...
     $codegenSettings = [];
     preg_match_all('/@codegen (\\w+)(?:\\s*=\\s*(\\S+))?$/m', $schemaDocComment, $allMatches);
     for ($i = 0; $i < count($allMatches[0]); $i++) {
         $key = $allMatches[1][$i];
         $value = $allMatches[2][$i];
         if ($value === "") {
             $value = true;
         } else {
             if (strcasecmp($value, "true") == 0 || strcasecmp($value, "false") == 0) {
                 $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
             } else {
                 if (preg_match('/^\\d+$/', $value)) {
                     $value = intval($value);
                 }
             }
         }
         $codegenSettings[$key] = $value;
     }
     /*
     if ($codegenSettings['validateColumn']) {
         $codegenSettings['handleValidationError'] = true;
     }
     */
     if (!empty($codegenSettings)) {
         $reflectionModel = new ReflectionClass('LazyRecord\\BaseModel');
         $createMethod = $reflectionModel->getMethod('create');
         $methodFile = $createMethod->getFilename();
         $startLine = $createMethod->getStartLine();
         $endLine = $createMethod->getEndLine();
         $lines = file($methodFile);
         $methodLines = array_slice($lines, $startLine + 1, $endLine - $startLine - 2);
         // exclude '{', '}'
         $blockRanges = array();
         $blockLines = array();
         // parse code blocks
         for ($i = 0; $i < count($methodLines); $i++) {
             $line = rtrim($methodLines[$i]);
             if (preg_match('/@codegenBlock (\\w+)/', $line, $matches)) {
                 $blockId = $matches[1];
                 for ($j = $i; $j < count($methodLines); $j++) {
                     $line = rtrim($methodLines[$j]);
                     $blockLines[$blockId][] = $line;
                     if (preg_match('/@codegenBlockEnd/', $line)) {
                         $blockRanges[$blockId] = [$i, $j];
                         $i = $j;
                         break;
                     }
                 }
             }
         }
         $overrideCreateMethod = $cTemplate->addMethod('public', 'create', ['array $args', 'array $options = array()']);
         $overrideBlock = $overrideCreateMethod->getBlock();
         for ($i = 0; $i < count($methodLines); $i++) {
             $line = rtrim($methodLines[$i]);
             if (preg_match('/@codegenBlock (\\w+)/', $line, $matches)) {
                 $blockId = $matches[1];
                 if (isset($codegenSettings[$matches[1]]) && isset($blockLines[$blockId])) {
                     if ($codegenSettings[$matches[1]]) {
                         $overrideBlock[] = $blockLines[$blockId];
                         list($startLine, $endLine) = $blockRanges[$blockId];
                         $i = $endLine;
                         continue;
                     } else {
                         list($startLine, $endLine) = $blockRanges[$blockId];
                         $i = $endLine;
                         continue;
                     }
                 }
             }
             $overrideBlock[] = $line;
         }
     }
     // TODO: refacory this into factory method
     // Generate findByPrimaryKey SQL query
     $arguments = new ArgumentArray();
     $findByPrimaryKeyQuery = new SelectQuery();
     $findByPrimaryKeyQuery->from($schema->getTable());
     $primaryKey = $schema->primaryKey;
     $readFrom = $schema->getReadSourceId();
     $readConnection = ConnectionManager::getInstance()->getConnection($readFrom);
     $readQueryDriver = $readConnection->createQueryDriver();
     $primaryKeyColumn = $schema->getColumn($primaryKey);
     $findByPrimaryKeyQuery->select('*')->where()->equal($primaryKey, new Bind($primaryKey));
     $findByPrimaryKeyQuery->limit(1);
     $findByPrimaryKeySql = $findByPrimaryKeyQuery->toSql($readQueryDriver, $arguments);
     $cTemplate->addConst('FIND_BY_PRIMARY_KEY_SQL', $findByPrimaryKeySql);
     foreach ($schema->getColumns() as $column) {
         if (!$column->findable) {
             continue;
         }
         $columnName = $column->name;
         $findMethodName = 'findBy' . ucfirst(Inflector::camelize($columnName));
         $findMethod = $cTemplate->addMethod('public', $findMethodName, ['$value']);
         $block = $findMethod->block;
         $arguments = new ArgumentArray();
         $findByColumnQuery = new SelectQuery();
         $findByColumnQuery->from($schema->getTable());
         $columnName = $column->name;
         $readFrom = $schema->getReadSourceId();
         $findByColumnQuery->select('*')->where()->equal($columnName, new Bind($columnName));
         $findByColumnQuery->limit(1);
         $findByColumnSql = $findByColumnQuery->toSql($readQueryDriver, $arguments);
         $block[] = '$conn  = $this->getReadConnection();';
         $block[] = 'if (!isset($this->_preparedFindStms[' . var_export($columnName, true) . '])) {';
         $block[] = '    $this->_preparedFindStms[' . var_export($columnName, true) . '] = $conn->prepare(' . var_export($findByColumnSql, true) . ');';
         $block[] = '}';
         $block[] = '$this->_preparedFindStms[' . var_export($columnName, true) . ']->execute([' . var_export(":{$columnName}", true) . ' => $value ]);';
         $block[] = 'if (false === ($this->_data = $this->_preparedFindStms[' . var_export($columnName, true) . ']->fetch(PDO::FETCH_ASSOC)) ) {';
         $block[] = '    return $this->reportError("Record not found", [';
         $block[] = '        "sql" => ' . var_export($findByColumnSql, true) . ',';
         $block[] = '    ]);';
         $block[] = '}';
         $block[] = '$this->_preparedFindStms[' . var_export($columnName, true) . ']->closeCursor();';
         $block[] = 'return $this->reportSuccess( "Data loaded", array( ';
         $block[] = '    "sql" => ' . var_export($findByColumnSql, true) . ',';
         $block[] = '    "type" => Result::TYPE_LOAD,';
         $block[] = '));';
     }
     $cTemplate->extendClass('\\' . $baseClass);
     // interfaces
     if ($ifs = $schema->getModelInterfaces()) {
         foreach ($ifs as $iface) {
             $cTemplate->implementClass($iface);
         }
     }
     // Create column accessor
     if ($schema->enableColumnAccessors) {
         foreach ($schema->getColumnNames() as $columnName) {
             $accessorMethodName = 'get' . ucfirst(Inflector::camelize($columnName));
             $cTemplate->addMethod('public', $accessorMethodName, [], ['    return $this->get(' . var_export($columnName, true) . ');']);
         }
     }
     return $cTemplate;
 }
コード例 #9
0
 /**
  * @return ClassTemplate\ClassFile
  */
 public function createClassTemplate($taskName, $time = null)
 {
     if (!$time) {
         $time = time();
     } elseif (is_string($time)) {
         $time = strtotime($time);
     }
     $className = $taskName . '_' . $time;
     $template = new ClassFile($className);
     $template->useClass('SQLBuilder\\Universal\\Syntax\\Column');
     $template->useClass('SQLBuilder\\Universal\\Query\\AlterTableQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\CreateTableQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\UpdateTableQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\DeleteTableQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\InsertTableQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\CreateIndexQuery');
     $template->useClass('SQLBuilder\\Universal\\Query\\UnionQuery');
     $template->useClass('SQLBuilder\\Bind');
     $template->useClass('SQLBuilder\\ArgumentArray');
     $template->useClass('SQLBuilder\\Literal');
     $template->extendClass('LazyRecord\\Migration\\Migration');
     return $template;
 }
コード例 #10
0
 /**
  * Write class template to the schema directory.
  *
  * @param string $directory The schema class directory.
  * @param ClassTemplate\ClassFile class template object.
  * @param bool $overwrite Overwrite class file. 
  *
  * @return array
  */
 protected function writeClassTemplateToPath(ClassFile $cTemplate, $filepath)
 {
     if (false === file_put_contents($filepath, $cTemplate->render())) {
         throw RuntimeException("Can not write file {$filepath}");
     }
     return true;
 }