PageRenderTime 81ms CodeModel.GetById 47ms RepoModel.GetById 2ms app.codeStats 0ms

/blog/www/system/library/Doctrine/Migration/Diff.php

https://bitbucket.org/vmihailenco/vladimirwebdev
PHP | 379 lines | 220 code | 32 blank | 127 comment | 36 complexity | 2160421c571945ef40255930ce5fc81f MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*
  3. * $Id: Diff.php 1080 2007-02-10 18:17:08Z jwage $
  4. *
  5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. *
  17. * This software consists of voluntary contributions made by many individuals
  18. * and is licensed under the LGPL. For more information, see
  19. * <http://www.phpdoctrine.org>.
  20. */
  21. /**
  22. * Doctrine_Migration_Diff - class used for generating differences and migration
  23. * classes from 'from' and 'to' schema information.
  24. *
  25. * @package Doctrine
  26. * @subpackage Migration
  27. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  28. * @link www.phpdoctrine.org
  29. * @since 1.0
  30. * @version $Revision: 1080 $
  31. * @author Jonathan H. Wage <jonwage@gmail.com>
  32. */
  33. class Doctrine_Migration_Diff
  34. {
  35. protected $_from,
  36. $_to,
  37. $_changes = array('created_tables' => array(),
  38. 'dropped_tables' => array(),
  39. 'created_foreign_keys'=> array(),
  40. 'dropped_foreign_keys'=> array(),
  41. 'created_columns' => array(),
  42. 'dropped_columns' => array(),
  43. 'changed_columns' => array(),
  44. 'created_indexes' => array(),
  45. 'dropped_indexes' => array()),
  46. $_migration,
  47. $_startingModelFiles = array(),
  48. $_tmpPath;
  49. protected static $_toPrefix = 'ToPrfx',
  50. $_fromPrefix = 'FromPrfx';
  51. /**
  52. * Instantiate new Doctrine_Migration_Diff instance
  53. *
  54. * <code>
  55. * $diff = new Doctrine_Migration_Diff('/path/to/old_models', '/path/to/new_models', '/path/to/migrations');
  56. * $diff->generateMigrationClasses();
  57. * </code>
  58. *
  59. * @param string $from The from schema information source
  60. * @param string $to The to schema information source
  61. * @param mixed $migration Instance of Doctrine_Migration or path to migration classes
  62. * @return void
  63. */
  64. public function __construct($from, $to, $migration)
  65. {
  66. $this->_from = $from;
  67. $this->_to = $to;
  68. $this->_startingModelFiles = Doctrine_Core::getLoadedModelFiles();
  69. $this->setTmpPath(sys_get_temp_dir() . DIRECTORY_SEPARATOR . getmypid());
  70. if ($migration instanceof Doctrine_Migration) {
  71. $this->_migration = $migration;
  72. } else if (is_dir($migration)) {
  73. $this->_migration = new Doctrine_Migration($migration);
  74. }
  75. }
  76. /**
  77. * Set the temporary path to store the generated models for generating diffs
  78. *
  79. * @param string $tmpPath
  80. * @return void
  81. */
  82. public function setTmpPath($tmpPath)
  83. {
  84. if ( ! is_dir($tmpPath)) {
  85. mkdir($tmpPath, 0777, true);
  86. }
  87. $this->_tmpPath = $tmpPath;
  88. }
  89. /**
  90. * Get unique hash id for this migration instance
  91. *
  92. * @return string $uniqueId
  93. */
  94. protected function getUniqueId()
  95. {
  96. return md5($this->_from . $this->_to);
  97. }
  98. /**
  99. * Generate an array of changes found between the from and to schema information.
  100. *
  101. * @return array $changes
  102. */
  103. public function generateChanges()
  104. {
  105. $this->_cleanup();
  106. $from = $this->_generateModels(self::$_fromPrefix, $this->_from);
  107. $to = $this->_generateModels(self::$_toPrefix, $this->_to);
  108. return $this->_diff($from, $to);
  109. }
  110. /**
  111. * Generate a migration class for the changes in this diff instance
  112. *
  113. * @return array $changes
  114. */
  115. public function generateMigrationClasses()
  116. {
  117. $builder = new Doctrine_Migration_Builder($this->_migration);
  118. return $builder->generateMigrationsFromDiff($this);
  119. }
  120. /**
  121. * Generate a diff between the from and to schema information
  122. *
  123. * @param string $from Path to set of models to migrate from
  124. * @param string $to Path to set of models to migrate to
  125. * @return array $changes
  126. */
  127. protected function _diff($from, $to)
  128. {
  129. // Load the from and to models
  130. $fromModels = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($from));
  131. $toModels = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($to));
  132. // Build schema information for the models
  133. $fromInfo = $this->_buildModelInformation($fromModels);
  134. $toInfo = $this->_buildModelInformation($toModels);
  135. // Build array of changes between the from and to information
  136. $changes = $this->_buildChanges($fromInfo, $toInfo);
  137. $this->_cleanup();
  138. return $changes;
  139. }
  140. /**
  141. * Build array of changes between the from and to array of schema information
  142. *
  143. * @param array $from Array of schema information to generate changes from
  144. * @param array $to Array of schema information to generate changes for
  145. * @return array $changes
  146. */
  147. protected function _buildChanges($from, $to)
  148. {
  149. // Loop over the to schema information and compare it to the from
  150. foreach ($to as $className => $info) {
  151. // If the from doesn't have this class then it is a new table
  152. if ( ! isset($from[$className])) {
  153. $names = array('type', 'charset', 'collate', 'indexes', 'foreignKeys', 'primary');
  154. $options = array();
  155. foreach ($names as $name) {
  156. if (isset($info['options'][$name]) && $info['options'][$name]) {
  157. $options[$name] = $info['options'][$name];
  158. }
  159. }
  160. $table = array('tableName' => $info['tableName'],
  161. 'columns' => $info['columns'],
  162. 'options' => $options);
  163. $this->_changes['created_tables'][$info['tableName']] = $table;
  164. }
  165. // Check for new and changed columns
  166. foreach ($info['columns'] as $name => $column) {
  167. // If column doesn't exist in the from schema information then it is a new column
  168. if (isset($from[$className]) && ! isset($from[$className]['columns'][$name])) {
  169. $this->_changes['created_columns'][$info['tableName']][$name] = $column;
  170. }
  171. // If column exists in the from schema information but is not the same then it is a changed column
  172. if (isset($from[$className]['columns'][$name]) && $from[$className]['columns'][$name] != $column) {
  173. $this->_changes['changed_columns'][$info['tableName']][$name] = $column;
  174. }
  175. }
  176. // Check for new foreign keys
  177. foreach ($info['options']['foreignKeys'] as $name => $foreignKey) {
  178. $foreignKey['name'] = $name;
  179. // If foreign key doesn't exist in the from schema information then we need to add a index and the new fk
  180. if ( ! isset($from[$className]['options']['foreignKeys'][$name])) {
  181. $this->_changes['created_foreign_keys'][$info['tableName']][$name] = $foreignKey;
  182. $indexName = Doctrine_Manager::connection()->generateUniqueIndexName($info['tableName'], $foreignKey['local']);
  183. $this->_changes['created_indexes'][$info['tableName']][$indexName] = array('fields' => array($foreignKey['local']));
  184. // If foreign key does exist then lets see if anything has changed with it
  185. } else if (isset($from[$className]['options']['foreignKeys'][$name])) {
  186. $oldForeignKey = $from[$className]['options']['foreignKeys'][$name];
  187. $oldForeignKey['name'] = $name;
  188. // If the foreign key has changed any then we need to drop the foreign key and readd it
  189. if ($foreignKey !== $oldForeignKey) {
  190. $this->_changes['dropped_foreign_keys'][$info['tableName']][$name] = $oldForeignKey;
  191. $this->_changes['created_foreign_keys'][$info['tableName']][$name] = $foreignKey;
  192. }
  193. }
  194. }
  195. // Check for new indexes
  196. foreach ($info['options']['indexes'] as $name => $index) {
  197. // If index doesn't exist in the from schema information
  198. if ( ! isset($from[$className]['options']['indexes'][$name])) {
  199. $this->_changes['created_indexes'][$info['tableName']][$name] = $index;
  200. }
  201. }
  202. }
  203. // Loop over the from schema information and compare it to the to schema information
  204. foreach ($from as $className => $info) {
  205. // If the class exists in the from but not in the to then it is a dropped table
  206. if ( ! isset($to[$className])) {
  207. $table = array('tableName' => $info['tableName'],
  208. 'columns' => $info['columns'],
  209. 'options' => array('type' => $info['options']['type'],
  210. 'charset' => $info['options']['charset'],
  211. 'collate' => $info['options']['collate'],
  212. 'indexes' => $info['options']['indexes'],
  213. 'foreignKeys' => $info['options']['foreignKeys'],
  214. 'primary' => $info['options']['primary']));
  215. $this->_changes['dropped_tables'][$info['tableName']] = $table;
  216. }
  217. // Check for removed columns
  218. foreach ($info['columns'] as $name => $column) {
  219. // If column exists in the from but not in the to then we need to remove it
  220. if (isset($to[$className]) && ! isset($to[$className]['columns'][$name])) {
  221. $this->_changes['dropped_columns'][$info['tableName']][$name] = $column;
  222. }
  223. }
  224. // Check for dropped foreign keys
  225. foreach ($info['options']['foreignKeys'] as $name => $foreignKey) {
  226. // If the foreign key exists in the from but not in the to then we need to drop it
  227. if ( ! isset($to[$className]['options']['foreignKeys'][$name])) {
  228. $this->_changes['dropped_foreign_keys'][$info['tableName']][$name] = $foreignKey;
  229. }
  230. }
  231. // Check for removed indexes
  232. foreach ($info['options']['indexes'] as $name => $index) {
  233. // If the index exists in the from but not the to then we need to remove it
  234. if ( ! isset($to[$className]['options']['indexes'][$name])) {
  235. $this->_changes['dropped_indexes'][$info['tableName']][$name] = $index;
  236. }
  237. }
  238. }
  239. return $this->_changes;
  240. }
  241. /**
  242. * Build all the model schema information for the passed array of models
  243. *
  244. * @param array $models Array of models to build the schema information for
  245. * @return array $info Array of schema information for all the passed models
  246. */
  247. protected function _buildModelInformation(array $models)
  248. {
  249. $info = array();
  250. foreach ($models as $key => $model) {
  251. $table = Doctrine_Core::getTable($model);
  252. if ($table->getTableName() !== $this->_migration->getTableName()) {
  253. $info[$model] = $table->getExportableFormat();
  254. }
  255. }
  256. $info = $this->_cleanModelInformation($info);
  257. return $info;
  258. }
  259. /**
  260. * Clean the produced model information of any potential prefix text
  261. *
  262. * @param mixed $info Either array or string to clean of prefixes
  263. * @return mixed $info Cleaned value which is either an array or string
  264. */
  265. protected function _cleanModelInformation($info)
  266. {
  267. if (is_array($info)) {
  268. foreach ($info as $key => $value) {
  269. unset($info[$key]);
  270. $key = $this->_cleanModelInformation($key);
  271. $info[$key] = $this->_cleanModelInformation($value);
  272. }
  273. return $info;
  274. } else {
  275. $find = array(
  276. self::$_toPrefix,
  277. self::$_fromPrefix,
  278. Doctrine_Inflector::tableize(self::$_toPrefix) . '_',
  279. Doctrine_Inflector::tableize(self::$_fromPrefix) . '_',
  280. Doctrine_Inflector::tableize(self::$_toPrefix),
  281. Doctrine_Inflector::tableize(self::$_fromPrefix)
  282. );
  283. return str_replace($find, null, $info);
  284. }
  285. }
  286. /**
  287. * Generate a set of models for the schema information source
  288. *
  289. * @param string $prefix Prefix to generate the models with
  290. * @param mixed $item The item to generate the models from
  291. * @return string $path The path where the models were generated
  292. * @throws Doctrine_Migration_Exception $e
  293. */
  294. protected function _generateModels($prefix, $item)
  295. {
  296. $path = $this->_tmpPath . DIRECTORY_SEPARATOR . strtolower($prefix) . '_doctrine_tmp_dirs';
  297. $options = array(
  298. 'classPrefix' => $prefix,
  299. 'generateBaseClasses' => false
  300. );
  301. if (is_string($item) && file_exists($item)) {
  302. if (is_dir($item)) {
  303. $files = glob($item . DIRECTORY_SEPARATOR . '*.*');
  304. } else {
  305. $files = array($item);
  306. }
  307. if (isset($files[0])) {
  308. $pathInfo = pathinfo($files[0]);
  309. $extension = $pathInfo['extension'];
  310. }
  311. if ($extension === 'yml') {
  312. Doctrine_Core::generateModelsFromYaml($item, $path, $options);
  313. return $path;
  314. } else if ($extension === 'php') {
  315. Doctrine_Lib::copyDirectory($item, $path);
  316. return $path;
  317. } else {
  318. throw new Doctrine_Migration_Exception('No php or yml files found at path: "' . $item . '"');
  319. }
  320. } else {
  321. try {
  322. Doctrine_Core::generateModelsFromDb($path, (array) $item, $options);
  323. return $path;
  324. } catch (Exception $e) {
  325. throw new Doctrine_Migration_Exception('Could not generate models from connection: ' . $e->getMessage());
  326. }
  327. }
  328. }
  329. /**
  330. * Cleanup temporary generated models after a diff is performed
  331. *
  332. * @return void
  333. */
  334. protected function _cleanup()
  335. {
  336. $modelFiles = Doctrine_Core::getLoadedModelFiles();
  337. $filesToClean = array_diff($modelFiles, $this->_startingModelFiles);
  338. foreach ($filesToClean as $file) {
  339. if (file_exists($file)) {
  340. unlink($file);
  341. }
  342. }
  343. // clean up tmp directories
  344. Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_fromPrefix) . '_doctrine_tmp_dirs');
  345. Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_toPrefix) . '_doctrine_tmp_dirs');
  346. }
  347. }