PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Model/CakeSchema.php

https://bitbucket.org/daveschwan/ronin-group
PHP | 719 lines | 485 code | 74 blank | 160 comment | 135 complexity | 72ce1277383a5b3488a7856afea19e42 MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, MIT, BSD-3-Clause, Apache-2.0
  1. <?php
  2. /**
  3. * Schema database management for CakePHP.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Model
  15. * @since CakePHP(tm) v 1.2.0.5550
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Model', 'Model');
  19. App::uses('AppModel', 'Model');
  20. App::uses('ConnectionManager', 'Model');
  21. App::uses('File', 'Utility');
  22. /**
  23. * Base Class for Schema management
  24. *
  25. * @package Cake.Model
  26. */
  27. class CakeSchema extends Object {
  28. /**
  29. * Name of the schema
  30. *
  31. * @var string
  32. */
  33. public $name = null;
  34. /**
  35. * Path to write location
  36. *
  37. * @var string
  38. */
  39. public $path = null;
  40. /**
  41. * File to write
  42. *
  43. * @var string
  44. */
  45. public $file = 'schema.php';
  46. /**
  47. * Connection used for read
  48. *
  49. * @var string
  50. */
  51. public $connection = 'default';
  52. /**
  53. * plugin name.
  54. *
  55. * @var string
  56. */
  57. public $plugin = null;
  58. /**
  59. * Set of tables
  60. *
  61. * @var array
  62. */
  63. public $tables = array();
  64. /**
  65. * Constructor
  66. *
  67. * @param array $options optional load object properties
  68. */
  69. public function __construct($options = array()) {
  70. parent::__construct();
  71. if (empty($options['name'])) {
  72. $this->name = preg_replace('/schema$/i', '', get_class($this));
  73. }
  74. if (!empty($options['plugin'])) {
  75. $this->plugin = $options['plugin'];
  76. }
  77. if (strtolower($this->name) === 'cake') {
  78. $this->name = Inflector::camelize(Inflector::slug(Configure::read('App.dir')));
  79. }
  80. if (empty($options['path'])) {
  81. $this->path = APP . 'Config' . DS . 'Schema';
  82. }
  83. $options = array_merge(get_object_vars($this), $options);
  84. $this->build($options);
  85. }
  86. /**
  87. * Builds schema object properties
  88. *
  89. * @param array $data loaded object properties
  90. * @return void
  91. */
  92. public function build($data) {
  93. $file = null;
  94. foreach ($data as $key => $val) {
  95. if (!empty($val)) {
  96. if (!in_array($key, array('plugin', 'name', 'path', 'file', 'connection', 'tables', '_log'))) {
  97. if ($key[0] === '_') {
  98. continue;
  99. }
  100. $this->tables[$key] = $val;
  101. unset($this->{$key});
  102. } elseif ($key !== 'tables') {
  103. if ($key === 'name' && $val !== $this->name && !isset($data['file'])) {
  104. $file = Inflector::underscore($val) . '.php';
  105. }
  106. $this->{$key} = $val;
  107. }
  108. }
  109. }
  110. if (file_exists($this->path . DS . $file) && is_file($this->path . DS . $file)) {
  111. $this->file = $file;
  112. } elseif (!empty($this->plugin)) {
  113. $this->path = CakePlugin::path($this->plugin) . 'Config' . DS . 'Schema';
  114. }
  115. }
  116. /**
  117. * Before callback to be implemented in subclasses
  118. *
  119. * @param array $event schema object properties
  120. * @return boolean Should process continue
  121. */
  122. public function before($event = array()) {
  123. return true;
  124. }
  125. /**
  126. * After callback to be implemented in subclasses
  127. *
  128. * @param array $event schema object properties
  129. * @return void
  130. */
  131. public function after($event = array()) {
  132. }
  133. /**
  134. * Reads database and creates schema tables
  135. *
  136. * @param array $options schema object properties
  137. * @return array Set of name and tables
  138. */
  139. public function load($options = array()) {
  140. if (is_string($options)) {
  141. $options = array('path' => $options);
  142. }
  143. $this->build($options);
  144. extract(get_object_vars($this));
  145. $class = $name . 'Schema';
  146. if (!class_exists($class)) {
  147. if (file_exists($path . DS . $file) && is_file($path . DS . $file)) {
  148. require_once $path . DS . $file;
  149. } elseif (file_exists($path . DS . 'schema.php') && is_file($path . DS . 'schema.php')) {
  150. require_once $path . DS . 'schema.php';
  151. }
  152. }
  153. if (class_exists($class)) {
  154. $Schema = new $class($options);
  155. return $Schema;
  156. }
  157. return false;
  158. }
  159. /**
  160. * Reads database and creates schema tables
  161. *
  162. * Options
  163. *
  164. * - 'connection' - the db connection to use
  165. * - 'name' - name of the schema
  166. * - 'models' - a list of models to use, or false to ignore models
  167. *
  168. * @param array $options schema object properties
  169. * @return array Array indexed by name and tables
  170. */
  171. public function read($options = array()) {
  172. extract(array_merge(
  173. array(
  174. 'connection' => $this->connection,
  175. 'name' => $this->name,
  176. 'models' => true,
  177. ),
  178. $options
  179. ));
  180. $db = ConnectionManager::getDataSource($connection);
  181. if (isset($this->plugin)) {
  182. App::uses($this->plugin . 'AppModel', $this->plugin . '.Model');
  183. }
  184. $tables = array();
  185. $currentTables = (array)$db->listSources();
  186. $prefix = null;
  187. if (isset($db->config['prefix'])) {
  188. $prefix = $db->config['prefix'];
  189. }
  190. if (!is_array($models) && $models !== false) {
  191. if (isset($this->plugin)) {
  192. $models = App::objects($this->plugin . '.Model', null, false);
  193. } else {
  194. $models = App::objects('Model');
  195. }
  196. }
  197. if (is_array($models)) {
  198. foreach ($models as $model) {
  199. $importModel = $model;
  200. $plugin = null;
  201. if ($model === 'AppModel') {
  202. continue;
  203. }
  204. if (isset($this->plugin)) {
  205. if ($model == $this->plugin . 'AppModel') {
  206. continue;
  207. }
  208. $importModel = $model;
  209. $plugin = $this->plugin . '.';
  210. }
  211. App::uses($importModel, $plugin . 'Model');
  212. if (!class_exists($importModel)) {
  213. continue;
  214. }
  215. $vars = get_class_vars($model);
  216. if (empty($vars['useDbConfig']) || $vars['useDbConfig'] != $connection) {
  217. continue;
  218. }
  219. try {
  220. $Object = ClassRegistry::init(array('class' => $model, 'ds' => $connection));
  221. } catch (CakeException $e) {
  222. continue;
  223. }
  224. if (!is_object($Object) || $Object->useTable === false) {
  225. continue;
  226. }
  227. $db = $Object->getDataSource();
  228. $fulltable = $table = $db->fullTableName($Object, false, false);
  229. if ($prefix && strpos($table, $prefix) !== 0) {
  230. continue;
  231. }
  232. if (!in_array($fulltable, $currentTables)) {
  233. continue;
  234. }
  235. $table = $this->_noPrefixTable($prefix, $table);
  236. $key = array_search($fulltable, $currentTables);
  237. if (empty($tables[$table])) {
  238. $tables[$table] = $this->_columns($Object);
  239. $tables[$table]['indexes'] = $db->index($Object);
  240. $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
  241. unset($currentTables[$key]);
  242. }
  243. if (empty($Object->hasAndBelongsToMany)) {
  244. continue;
  245. }
  246. foreach ($Object->hasAndBelongsToMany as $assocData) {
  247. if (isset($assocData['with'])) {
  248. $class = $assocData['with'];
  249. }
  250. if (!is_object($Object->$class)) {
  251. continue;
  252. }
  253. $withTable = $db->fullTableName($Object->$class, false, false);
  254. if ($prefix && strpos($withTable, $prefix) !== 0) {
  255. continue;
  256. }
  257. if (in_array($withTable, $currentTables)) {
  258. $key = array_search($withTable, $currentTables);
  259. $noPrefixWith = $this->_noPrefixTable($prefix, $withTable);
  260. $tables[$noPrefixWith] = $this->_columns($Object->$class);
  261. $tables[$noPrefixWith]['indexes'] = $db->index($Object->$class);
  262. $tables[$noPrefixWith]['tableParameters'] = $db->readTableParameters($withTable);
  263. unset($currentTables[$key]);
  264. }
  265. }
  266. }
  267. }
  268. if (!empty($currentTables)) {
  269. foreach ($currentTables as $table) {
  270. if ($prefix) {
  271. if (strpos($table, $prefix) !== 0) {
  272. continue;
  273. }
  274. $table = $this->_noPrefixTable($prefix, $table);
  275. }
  276. $Object = new AppModel(array(
  277. 'name' => Inflector::classify($table), 'table' => $table, 'ds' => $connection
  278. ));
  279. $systemTables = array(
  280. 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n'
  281. );
  282. $fulltable = $db->fullTableName($Object, false, false);
  283. if (in_array($table, $systemTables)) {
  284. $tables[$Object->table] = $this->_columns($Object);
  285. $tables[$Object->table]['indexes'] = $db->index($Object);
  286. $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable);
  287. } elseif ($models === false) {
  288. $tables[$table] = $this->_columns($Object);
  289. $tables[$table]['indexes'] = $db->index($Object);
  290. $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable);
  291. } else {
  292. $tables['missing'][$table] = $this->_columns($Object);
  293. $tables['missing'][$table]['indexes'] = $db->index($Object);
  294. $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable);
  295. }
  296. }
  297. }
  298. ksort($tables);
  299. return compact('name', 'tables');
  300. }
  301. /**
  302. * Writes schema file from object or options
  303. *
  304. * @param array|object $object schema object or options array
  305. * @param array $options schema object properties to override object
  306. * @return mixed false or string written to file
  307. */
  308. public function write($object, $options = array()) {
  309. if (is_object($object)) {
  310. $object = get_object_vars($object);
  311. $this->build($object);
  312. }
  313. if (is_array($object)) {
  314. $options = $object;
  315. unset($object);
  316. }
  317. extract(array_merge(
  318. get_object_vars($this), $options
  319. ));
  320. $out = "class {$name}Schema extends CakeSchema {\n\n";
  321. if ($path !== $this->path) {
  322. $out .= "\tpublic \$path = '{$path}';\n\n";
  323. }
  324. if ($file !== $this->file) {
  325. $out .= "\tpublic \$file = '{$file}';\n\n";
  326. }
  327. if ($connection !== 'default') {
  328. $out .= "\tpublic \$connection = '{$connection}';\n\n";
  329. }
  330. $out .= "\tpublic function before(\$event = array()) {\n\t\treturn true;\n\t}\n\n\tpublic function after(\$event = array()) {\n\t}\n\n";
  331. if (empty($tables)) {
  332. $this->read();
  333. }
  334. foreach ($tables as $table => $fields) {
  335. if (!is_numeric($table) && $table !== 'missing') {
  336. $out .= $this->generateTable($table, $fields);
  337. }
  338. }
  339. $out .= "}\n";
  340. $file = new File($path . DS . $file, true);
  341. $content = "<?php \n{$out}";
  342. if ($file->write($content)) {
  343. return $content;
  344. }
  345. return false;
  346. }
  347. /**
  348. * Generate the code for a table. Takes a table name and $fields array
  349. * Returns a completed variable declaration to be used in schema classes
  350. *
  351. * @param string $table Table name you want returned.
  352. * @param array $fields Array of field information to generate the table with.
  353. * @return string Variable declaration for a schema class
  354. */
  355. public function generateTable($table, $fields) {
  356. $out = "\tpublic \${$table} = array(\n";
  357. if (is_array($fields)) {
  358. $cols = array();
  359. foreach ($fields as $field => $value) {
  360. if ($field !== 'indexes' && $field !== 'tableParameters') {
  361. if (is_string($value)) {
  362. $type = $value;
  363. $value = array('type' => $type);
  364. }
  365. $col = "\t\t'{$field}' => array('type' => '" . $value['type'] . "', ";
  366. unset($value['type']);
  367. $col .= implode(', ', $this->_values($value));
  368. } elseif ($field === 'indexes') {
  369. $col = "\t\t'indexes' => array(\n\t\t\t";
  370. $props = array();
  371. foreach ((array)$value as $key => $index) {
  372. $props[] = "'{$key}' => array(" . implode(', ', $this->_values($index)) . ")";
  373. }
  374. $col .= implode(",\n\t\t\t", $props) . "\n\t\t";
  375. } elseif ($field === 'tableParameters') {
  376. $col = "\t\t'tableParameters' => array(";
  377. $props = array();
  378. foreach ((array)$value as $key => $param) {
  379. $props[] = "'{$key}' => '$param'";
  380. }
  381. $col .= implode(', ', $props);
  382. }
  383. $col .= ")";
  384. $cols[] = $col;
  385. }
  386. $out .= implode(",\n", $cols);
  387. }
  388. $out .= "\n\t);\n\n";
  389. return $out;
  390. }
  391. /**
  392. * Compares two sets of schemas
  393. *
  394. * @param array|object $old Schema object or array
  395. * @param array|object $new Schema object or array
  396. * @return array Tables (that are added, dropped, or changed)
  397. */
  398. public function compare($old, $new = null) {
  399. if (empty($new)) {
  400. $new = $this;
  401. }
  402. if (is_array($new)) {
  403. if (isset($new['tables'])) {
  404. $new = $new['tables'];
  405. }
  406. } else {
  407. $new = $new->tables;
  408. }
  409. if (is_array($old)) {
  410. if (isset($old['tables'])) {
  411. $old = $old['tables'];
  412. }
  413. } else {
  414. $old = $old->tables;
  415. }
  416. $tables = array();
  417. foreach ($new as $table => $fields) {
  418. if ($table === 'missing') {
  419. continue;
  420. }
  421. if (!array_key_exists($table, $old)) {
  422. $tables[$table]['create'] = $fields;
  423. } else {
  424. $diff = $this->_arrayDiffAssoc($fields, $old[$table]);
  425. if (!empty($diff)) {
  426. $tables[$table]['add'] = $diff;
  427. }
  428. $diff = $this->_arrayDiffAssoc($old[$table], $fields);
  429. if (!empty($diff)) {
  430. $tables[$table]['drop'] = $diff;
  431. }
  432. }
  433. foreach ($fields as $field => $value) {
  434. if (!empty($old[$table][$field])) {
  435. $diff = $this->_arrayDiffAssoc($value, $old[$table][$field]);
  436. if (!empty($diff) && $field !== 'indexes' && $field !== 'tableParameters') {
  437. $tables[$table]['change'][$field] = $value;
  438. }
  439. }
  440. if (isset($tables[$table]['add'][$field]) && $field !== 'indexes' && $field !== 'tableParameters') {
  441. $wrapper = array_keys($fields);
  442. if ($column = array_search($field, $wrapper)) {
  443. if (isset($wrapper[$column - 1])) {
  444. $tables[$table]['add'][$field]['after'] = $wrapper[$column - 1];
  445. }
  446. }
  447. }
  448. }
  449. if (isset($old[$table]['indexes']) && isset($new[$table]['indexes'])) {
  450. $diff = $this->_compareIndexes($new[$table]['indexes'], $old[$table]['indexes']);
  451. if ($diff) {
  452. if (!isset($tables[$table])) {
  453. $tables[$table] = array();
  454. }
  455. if (isset($diff['drop'])) {
  456. $tables[$table]['drop']['indexes'] = $diff['drop'];
  457. }
  458. if ($diff && isset($diff['add'])) {
  459. $tables[$table]['add']['indexes'] = $diff['add'];
  460. }
  461. }
  462. }
  463. if (isset($old[$table]['tableParameters']) && isset($new[$table]['tableParameters'])) {
  464. $diff = $this->_compareTableParameters($new[$table]['tableParameters'], $old[$table]['tableParameters']);
  465. if ($diff) {
  466. $tables[$table]['change']['tableParameters'] = $diff;
  467. }
  468. }
  469. }
  470. return $tables;
  471. }
  472. /**
  473. * Extended array_diff_assoc noticing change from/to NULL values
  474. *
  475. * It behaves almost the same way as array_diff_assoc except for NULL values: if
  476. * one of the values is not NULL - change is detected. It is useful in situation
  477. * where one value is strval('') ant other is strval(null) - in string comparing
  478. * methods this results as EQUAL, while it is not.
  479. *
  480. * @param array $array1 Base array
  481. * @param array $array2 Corresponding array checked for equality
  482. * @return array Difference as array with array(keys => values) from input array
  483. * where match was not found.
  484. */
  485. protected function _arrayDiffAssoc($array1, $array2) {
  486. $difference = array();
  487. foreach ($array1 as $key => $value) {
  488. if (!array_key_exists($key, $array2)) {
  489. $difference[$key] = $value;
  490. continue;
  491. }
  492. $correspondingValue = $array2[$key];
  493. if (($value === null) !== ($correspondingValue === null)) {
  494. $difference[$key] = $value;
  495. continue;
  496. }
  497. if (is_bool($value) !== is_bool($correspondingValue)) {
  498. $difference[$key] = $value;
  499. continue;
  500. }
  501. if (is_array($value) && is_array($correspondingValue)) {
  502. continue;
  503. }
  504. if ($value === $correspondingValue) {
  505. continue;
  506. }
  507. $difference[$key] = $value;
  508. }
  509. return $difference;
  510. }
  511. /**
  512. * Formats Schema columns from Model Object
  513. *
  514. * @param array $values options keys(type, null, default, key, length, extra)
  515. * @return array Formatted values
  516. */
  517. protected function _values($values) {
  518. $vals = array();
  519. if (is_array($values)) {
  520. foreach ($values as $key => $val) {
  521. if (is_array($val)) {
  522. $vals[] = "'{$key}' => array(" . implode(", ", $this->_values($val)) . ")";
  523. } else {
  524. $val = var_export($val, true);
  525. if ($val === 'NULL') {
  526. $val = 'null';
  527. }
  528. if (!is_numeric($key)) {
  529. $vals[] = "'{$key}' => {$val}";
  530. } else {
  531. $vals[] = "{$val}";
  532. }
  533. }
  534. }
  535. }
  536. return $vals;
  537. }
  538. /**
  539. * Formats Schema columns from Model Object
  540. *
  541. * @param array $Obj model object
  542. * @return array Formatted columns
  543. */
  544. protected function _columns(&$Obj) {
  545. $db = $Obj->getDataSource();
  546. $fields = $Obj->schema(true);
  547. $columns = array();
  548. foreach ($fields as $name => $value) {
  549. if ($Obj->primaryKey == $name) {
  550. $value['key'] = 'primary';
  551. }
  552. if (!isset($db->columns[$value['type']])) {
  553. trigger_error(__d('cake_dev', 'Schema generation error: invalid column type %s for %s.%s does not exist in DBO', $value['type'], $Obj->name, $name), E_USER_NOTICE);
  554. continue;
  555. } else {
  556. $defaultCol = $db->columns[$value['type']];
  557. if (isset($defaultCol['limit']) && $defaultCol['limit'] == $value['length']) {
  558. unset($value['length']);
  559. } elseif (isset($defaultCol['length']) && $defaultCol['length'] == $value['length']) {
  560. unset($value['length']);
  561. }
  562. unset($value['limit']);
  563. }
  564. if (isset($value['default']) && ($value['default'] === '' || ($value['default'] === false && $value['type'] !== 'boolean'))) {
  565. unset($value['default']);
  566. }
  567. if (empty($value['length'])) {
  568. unset($value['length']);
  569. }
  570. if (empty($value['key'])) {
  571. unset($value['key']);
  572. }
  573. $columns[$name] = $value;
  574. }
  575. return $columns;
  576. }
  577. /**
  578. * Compare two schema files table Parameters
  579. *
  580. * @param array $new New indexes
  581. * @param array $old Old indexes
  582. * @return mixed False on failure, or an array of parameters to add & drop.
  583. */
  584. protected function _compareTableParameters($new, $old) {
  585. if (!is_array($new) || !is_array($old)) {
  586. return false;
  587. }
  588. $change = $this->_arrayDiffAssoc($new, $old);
  589. return $change;
  590. }
  591. /**
  592. * Compare two schema indexes
  593. *
  594. * @param array $new New indexes
  595. * @param array $old Old indexes
  596. * @return mixed false on failure or array of indexes to add and drop
  597. */
  598. protected function _compareIndexes($new, $old) {
  599. if (!is_array($new) || !is_array($old)) {
  600. return false;
  601. }
  602. $add = $drop = array();
  603. $diff = $this->_arrayDiffAssoc($new, $old);
  604. if (!empty($diff)) {
  605. $add = $diff;
  606. }
  607. $diff = $this->_arrayDiffAssoc($old, $new);
  608. if (!empty($diff)) {
  609. $drop = $diff;
  610. }
  611. foreach ($new as $name => $value) {
  612. if (isset($old[$name])) {
  613. $newUnique = isset($value['unique']) ? $value['unique'] : 0;
  614. $oldUnique = isset($old[$name]['unique']) ? $old[$name]['unique'] : 0;
  615. $newColumn = $value['column'];
  616. $oldColumn = $old[$name]['column'];
  617. $diff = false;
  618. if ($newUnique != $oldUnique) {
  619. $diff = true;
  620. } elseif (is_array($newColumn) && is_array($oldColumn)) {
  621. $diff = ($newColumn !== $oldColumn);
  622. } elseif (is_string($newColumn) && is_string($oldColumn)) {
  623. $diff = ($newColumn != $oldColumn);
  624. } else {
  625. $diff = true;
  626. }
  627. if ($diff) {
  628. $drop[$name] = null;
  629. $add[$name] = $value;
  630. }
  631. }
  632. }
  633. return array_filter(compact('add', 'drop'));
  634. }
  635. /**
  636. * Trim the table prefix from the full table name, and return the prefix-less table
  637. *
  638. * @param string $prefix Table prefix
  639. * @param string $table Full table name
  640. * @return string Prefix-less table name
  641. */
  642. protected function _noPrefixTable($prefix, $table) {
  643. return preg_replace('/^' . preg_quote($prefix) . '/', '', $table);
  644. }
  645. }