/** * @param PropelPHPParser $parser */ protected function replaceDoDeleteAll($parser) { $peerClassName = $this->builder->getStubPeerBuilder()->getClassname(); $search = "\$con->commit();"; $replace = "\$con->commit();\n {$peerClassName}::purgeCache();"; $script = $parser->findMethod('doDeleteAll'); $script = str_replace($search, $replace, $script); $parser->replaceMethod("doDeleteAll", $script); }
/** * @param string $code * @param DataModelBuilder $builder * @return string */ public function addCreateEntityToCode($code, DataModelBuilder $builder) { $className = $builder->getStubObjectBuilder()->getClassname(); $code .= ' /** * @return ' . $className . ' */ public function createEntity() { return new ' . $className . '(); } '; return $code; }
protected function addIncludes(&$script) { if (!DataModelBuilder::getBuildProperty('builderAddIncludes')) { return; } parent::addIncludes($script); }
/** * @see Platform::supportsNativeDeleteTrigger() */ public function supportsNativeDeleteTrigger() { $usingInnoDB = false; if (class_exists('DataModelBuilder', false)) { $usingInnoDB = strtolower(DataModelBuilder::getBuildProperty('mysqlTableType')) == 'innodb'; } return $usingInnoDB || false; }
public function main() { $this->validate(); if (!$this->mapperElement) { throw new BuildException("You must use a <mapper/> element to describe how names should be transformed."); } if ($this->packageObjectModel) { $dataModels = $this->packageDataModels(); } else { $dataModels = $this->getDataModels(); } // 1) first create a map of filenames to databases; this is used by other tasks like // the SQLExec task. $this->createSqlDbMap(); // 2) Now actually create the DDL based on the datamodel(s) from XML schema file. $targetDatabase = $this->getTargetDatabase(); DataModelBuilder::setBuildProperties($this->getPropelProperties()); $builderClazz = DataModelBuilder::getBuilderClass('ddl'); foreach ($dataModels as $package => $dataModel) { foreach ($dataModel->getDatabases() as $database) { // file we are going to create if (!$this->packageObjectModel) { $name = $dataModel->getName(); } else { $name = ($package ? $package . '.' : '') . 'schema.xml'; } $outFile = $this->getMappedFile($name); $this->log("Writing to SQL file: " . $outFile->getPath()); // First add any "header" SQL $ddl = call_user_func(array($builderClazz, 'getDatabaseStartDDL')); foreach ($database->getTables() as $table) { if (!$table->isSkipSql()) { $builder = DataModelBuilder::builderFactory($table, 'ddl'); $this->log("\t+ " . $table->getName() . " [builder: " . get_class($builder) . "]"); $ddl .= $builder->build(); foreach ($builder->getWarnings() as $warning) { $this->log($warning, PROJECT_MSG_WARN); } } else { $this->log("\t + (skipping) " . $table->getName()); } } // foreach database->getTables() // Finally check to see if there is any "footer" SQL $ddl .= call_user_func(array($builderClazz, 'getDatabaseEndDDL')); // Now we're done. Write the file! file_put_contents($outFile->getAbsolutePath(), $ddl); } // foreach database } //foreach datamodels }
/** * Gets the full path to the file for the current class. * @return string */ public function getClassFilePath() { return parent::getFilePath($this->getPackage(), $this->getClassname()); }
protected function addDoInsert(&$script) { $tmp = ''; parent::addDoInsert($tmp); if (DataModelBuilder::getBuildProperty('builderAddBehaviors')) { // add sfMixer call $pre_mixer_script = "\n\n foreach (sfMixer::getCallables('{$this->getClassname()}:doInsert:pre') as \$callable)\n {\n \$ret = call_user_func(\$callable, '{$this->getClassname()}', \$values, \$con);\n if (false !== \$ret)\n {\n return \$ret;\n }\n }\n\n"; $post_mixer_script = "\n foreach (sfMixer::getCallables('{$this->getClassname()}:doInsert:post') as \$callable)\n {\n call_user_func(\$callable, '{$this->getClassname()}', \$values, \$con, \$pk);\n }\n\n return"; $tmp = preg_replace('/{/', '{' . $pre_mixer_script, $tmp, 1); $tmp = preg_replace("/\t\treturn/", "\t\t" . $post_mixer_script, $tmp, 1); } $script .= $tmp; }
/** * Main method builds all the targets for a typical propel project. */ public function main() { // check to make sure task received all correct params $this->validate(); $basepath = $this->getOutputDirectory(); // Get new Capsule context $generator = $this->createContext(); $generator->put("basepath", $basepath); // make available to other templates $targetPlatform = $this->getTargetPlatform(); // convenience for embedding in strings below // we need some values that were loaded into the template context $basePrefix = $generator->get('basePrefix'); $project = $generator->get('project'); DataModelBuilder::setBuildProperties($this->getPropelProperties()); foreach ($this->getDataModels() as $dataModel) { $this->log("Processing Datamodel : " . $dataModel->getName()); foreach ($dataModel->getDatabases() as $database) { $this->log(" - processing database : " . $database->getName()); $generator->put("platform", $database->getPlatform()); foreach ($database->getTables() as $table) { if (!$table->isForReferenceOnly()) { $this->log("\t+ " . $table->getName()); // ----------------------------------------------------------------------------------------- // Create Peer, Object, and MapBuilder classes // ----------------------------------------------------------------------------------------- // these files are always created / overwrite any existing files foreach (array('peer', 'object', 'mapbuilder') as $target) { $builder = DataModelBuilder::builderFactory($table, $target); $this->build($builder); } // ----------------------------------------------------------------------------------------- // Create [empty] stub Peer and Object classes if they don't exist // ----------------------------------------------------------------------------------------- // these classes are only generated if they don't already exist foreach (array('peerstub', 'objectstub') as $target) { $builder = DataModelBuilder::builderFactory($table, $target); $this->build($builder, $overwrite = false); } // ----------------------------------------------------------------------------------------- // Create [empty] stub child Object classes if they don't exist // ----------------------------------------------------------------------------------------- // If table has enumerated children (uses inheritance) then create the empty child stub classes if they don't already exist. if ($table->getChildrenColumn()) { $col = $table->getChildrenColumn(); if ($col->isEnumeratedClasses()) { foreach ($col->getChildren() as $child) { $builder = DataModelBuilder::builderFactory($table, 'objectmultiextend'); $builder->setChild($child); $this->build($builder, $overwrite = false); } // foreach } // if col->is enumerated } // if tbl->getChildrenCol // ----------------------------------------------------------------------------------------- // Create [empty] Interface if it doesn't exist // ----------------------------------------------------------------------------------------- // Create [empty] interface if it does not already exist if ($table->getInterface()) { $builder = DataModelBuilder::builderFactory($table, 'interface'); $this->build($builder, $overwrite = false); } // ----------------------------------------------------------------------------------------- // Create tree Node classes // ----------------------------------------------------------------------------------------- if ($table->isTree()) { foreach (array('nodepeer', 'node') as $target) { $builder = DataModelBuilder::builderFactory($table, $target); $this->build($builder); } foreach (array('nodepeerstub', 'nodestub') as $target) { $builder = DataModelBuilder::builderFactory($table, $target); $this->build($builder, $overwrite = false); } } // if Table->isTree() } // if !$table->isForReferenceOnly() } // foreach table } // foreach database } // foreach dataModel }
protected function addSave(&$script) { $tmp = ''; parent::addSave($tmp); // add support for created_(at|on) and updated_(at|on) columns $date_script = ''; $updated = false; $created = false; foreach ($this->getTable()->getColumns() as $col) { $clo = strtolower($col->getName()); if (!$updated && in_array($clo, array('updated_at', 'updated_on'))) { $updated = true; $date_script .= "\n if (\$this->isModified() && !\$this->isColumnModified(" . $this->getColumnConstant($col) . "))\n {\n \$this->set" . $col->getPhpName() . "(time());\n }\n"; } else { if (!$created && in_array($clo, array('created_at', 'created_on'))) { $created = true; $date_script .= "\n if (\$this->isNew() && !\$this->isColumnModified(" . $this->getColumnConstant($col) . "))\n {\n \$this->set" . $col->getPhpName() . "(time());\n }\n"; } } } $tmp = preg_replace('/{/', '{' . $date_script, $tmp, 1); if (DataModelBuilder::getBuildProperty('builderAddBehaviors')) { // add sfMixer call $pre_mixer_script = "\n\n foreach (sfMixer::getCallables('{$this->getClassname()}:save:pre') as \$callable)\n {\n \$affectedRows = call_user_func(\$callable, \$this, \$con);\n if (is_int(\$affectedRows))\n {\n return \$affectedRows;\n }\n }\n\n"; $post_mixer_script = <<<EOF foreach (sfMixer::getCallables('{$this->getClassname()}:save:post') as \$callable) { call_user_func(\$callable, \$this, \$con, \$affectedRows); } EOF; $tmp = preg_replace('/{/', '{' . $pre_mixer_script, $tmp, 1); $tmp = preg_replace('/(\\$con\\->commit\\(\\);)/', '$1' . $post_mixer_script, $tmp); } // update current script $script .= $tmp; }
/** * Adds the doCount() method. * @param string &$script The script will be modified in this method. */ protected function addDoCount(&$script) { $script .= "\n\t/**\n\t * Returns the number of rows matching criteria.\n\t *\n\t * @param Criteria \$criteria\n\t * @param boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.\n\t * @param PropelPDO \$con\n\t * @return int Number of matching rows.\n\t */\n\tpublic static function doCount(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null)\n\t{\n\t\t// we may modify criteria, so copy it first\n\t\t\$criteria = clone \$criteria;\n\n\t\t// We need to set the primary table name, since in the case that there are no WHERE columns\n\t\t// it will be impossible for the BasePeer::createSelectSql() method to determine which\n\t\t// tables go into the FROM clause.\n\t\t\$criteria->setPrimaryTableName(" . $this->getPeerClassname() . "::TABLE_NAME);\n\n\t\tif (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) {\n\t\t\t\$criteria->setDistinct();\n\t\t}\n\n\t\tif (!\$criteria->hasSelectClause()) {\n\t\t\t" . $this->getPeerClassname() . "::addSelectColumns(\$criteria);\n\t\t}\n\n\t\t\$criteria->clearOrderByColumns(); // ORDER BY won't ever affect the count\n\t\t\$criteria->setDbName(self::DATABASE_NAME); // Set the correct dbName\n\n\t\tif (\$con === null) {\n\t\t\t\$con = Propel::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_READ);\n\t\t}\n"; if (DataModelBuilder::getBuildProperty('builderAddBehaviors')) { $script .= "\n\n foreach (sfMixer::getCallables('{$this->getClassname()}:doCount:doCount') as \$callable)\n {\n call_user_func(\$callable, '{$this->getClassname()}', \$criteria, \$con);\n }\n\n"; } $script .= "\n\t\t// BasePeer returns a PDOStatement\n\t\t\$stmt = " . $this->basePeerClassname . "::doCount(\$criteria, \$con);\n\n\t\tif (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {\n\t\t\t\$count = (int) \$row[0];\n\t\t} else {\n\t\t\t\$count = 0; // no rows returned; we infer that means 0 matches.\n\t\t}\n\t\t\$stmt->closeCursor();\n\t\treturn \$count;\n\t}"; }
/** * Main method parses the XML files and creates SQL files. * * @return void * @throws Exception If there is an error parsing the data xml. */ public function main() { $this->validate(); $targetDatabase = $this->getTargetDatabase(); $platform = $this->getPlatformForTargetDatabase(); // Load the Data XML -> DB Name properties $map = new Properties(); try { $map->load($this->getDataDbMap()); } catch (IOException $ioe) { throw new BuildException("Cannot open and process the datadbmap!", $ioe); } DataModelBuilder::setBuildProperties($this->getPropelProperties()); // Parse each file in teh data -> db map foreach ($map->keys() as $dataXMLFilename) { $dataXMLFile = new PhingFile($this->srcDir, $dataXMLFilename); // if file exists then proceed if ($dataXMLFile->exists()) { $dbname = $map->get($dataXMLFilename); $db = $this->getDatabase($dbname); if (!$db) { throw new BuildException("Cannot find instantiated Database for name '{$dbname}' from datadbmap file."); } $db->setPlatform($platform); $outFile = $this->getMappedFile($dataXMLFilename); $this->log("Creating SQL from XML data dump file: " . $dataXMLFile->getAbsolutePath()); try { $dataXmlParser = new XmlToData($db, $this->dbEncoding); $data = $dataXmlParser->parseFile($dataXMLFile->getAbsolutePath()); } catch (Exception $e) { throw new Exception("Exception parsing data XML: " . $e->getMessage()); } $fp = fopen($outFile->getAbsolutePath(), 'w'); $currTable = null; foreach ($data as $dataRow) { if ($currTable !== $dataRow->getTable()) { $currTable = $dataRow->getTable(); $builder = DataModelBuilder::builderFactory($currTable, 'datasql'); } $sql = $builder->buildRowSql($dataRow); fwrite($fp, $sql); } fclose($fp); // Place the generated SQL file(s) $p = new Properties(); if ($this->getSqlDbMap()->exists()) { $p->load($this->getSqlDbMap()); } $p->setProperty($outFile->getName(), $db->getName()); $p->store($this->getSqlDbMap(), "Sqlfile -> Database map"); } else { $this->log("File '" . $dataXMLFile->getAbsolutePath() . "' in datadbmap does not exist, so skipping it.", PROJECT_MSG_WARN); } } // foreach data xml file }
/** * Sets the [name transformed] build properties to use. * @param array Property values keyed by [transformed] prop names. */ public static function setBuildProperties($props) { self::$buildProperties = $props; }
/** * @param DataModelBuilder $builder * @return string */ public function postSave(DataModelBuilder $builder) { $peerClassName = $builder->getStubPeerBuilder()->getClassname(); return "{$peerClassName}::purgeCache();"; }
/** * @param DataModelBuilder $builder * @return string */ public function postDelete($builder) { $event = $builder->getTable()->getName() . '_' . __FUNCTION__; return ' // fire "' . $event . '" event \\Zpropel\\Model\\StaticManager::getEventManager()->trigger(\'' . $event . '\', $this); '; }
/** * @param DataModelBuilder $builder * @return string */ private function returnDatabaseNameIfMethodNamePrefixIsNotProvided(DataModelBuilder $builder) { $methodNamePrefix = is_null($this->parameters[self::PARAMETER_ENTITY_METHOD_NAME_PREFIX]) ? 'create' . ucfirst($builder->getDatabase()->getName()) : $this->parameters[self::PARAMETER_ENTITY_METHOD_NAME_PREFIX]; return $methodNamePrefix; }