PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/system/application/plugins/doctrine/lib/Doctrine.php

https://github.com/cawago/ci_campusync_auth
PHP | 1039 lines | 465 code | 135 blank | 439 comment | 35 complexity | f078cd1d8d71a4fa6c380a190cbd408a MD5 | raw file
  1. <?php
  2. /*
  3. * $Id: Doctrine.php 6395 2009-09-22 03:47:00Z guilhermeblanco $
  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
  23. * the base class of Doctrine framework
  24. *
  25. * @package Doctrine
  26. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  27. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  28. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  29. * @link www.phpdoctrine.org
  30. * @since 1.0
  31. * @version $Revision: 6395 $
  32. */
  33. final class Doctrine
  34. {
  35. /**
  36. * VERSION
  37. */
  38. const VERSION = '1.1.4';
  39. /**
  40. * ERROR CONSTANTS
  41. */
  42. const ERR = -1;
  43. const ERR_SYNTAX = -2;
  44. const ERR_CONSTRAINT = -3;
  45. const ERR_NOT_FOUND = -4;
  46. const ERR_ALREADY_EXISTS = -5;
  47. const ERR_UNSUPPORTED = -6;
  48. const ERR_MISMATCH = -7;
  49. const ERR_INVALID = -8;
  50. const ERR_NOT_CAPABLE = -9;
  51. const ERR_TRUNCATED = -10;
  52. const ERR_INVALID_NUMBER = -11;
  53. const ERR_INVALID_DATE = -12;
  54. const ERR_DIVZERO = -13;
  55. const ERR_NODBSELECTED = -14;
  56. const ERR_CANNOT_CREATE = -15;
  57. const ERR_CANNOT_DELETE = -16;
  58. const ERR_CANNOT_DROP = -17;
  59. const ERR_NOSUCHTABLE = -18;
  60. const ERR_NOSUCHFIELD = -19;
  61. const ERR_NEED_MORE_DATA = -20;
  62. const ERR_NOT_LOCKED = -21;
  63. const ERR_VALUE_COUNT_ON_ROW = -22;
  64. const ERR_INVALID_DSN = -23;
  65. const ERR_CONNECT_FAILED = -24;
  66. const ERR_EXTENSION_NOT_FOUND = -25;
  67. const ERR_NOSUCHDB = -26;
  68. const ERR_ACCESS_VIOLATION = -27;
  69. const ERR_CANNOT_REPLACE = -28;
  70. const ERR_CONSTRAINT_NOT_NULL = -29;
  71. const ERR_DEADLOCK = -30;
  72. const ERR_CANNOT_ALTER = -31;
  73. const ERR_MANAGER = -32;
  74. const ERR_MANAGER_PARSE = -33;
  75. const ERR_LOADMODULE = -34;
  76. const ERR_INSUFFICIENT_DATA = -35;
  77. const ERR_CLASS_NAME = -36;
  78. /**
  79. * PDO derived constants
  80. */
  81. const CASE_LOWER = 2;
  82. const CASE_NATURAL = 0;
  83. const CASE_UPPER = 1;
  84. const CURSOR_FWDONLY = 0;
  85. const CURSOR_SCROLL = 1;
  86. const ERRMODE_EXCEPTION = 2;
  87. const ERRMODE_SILENT = 0;
  88. const ERRMODE_WARNING = 1;
  89. const FETCH_ASSOC = 2;
  90. const FETCH_BOTH = 4;
  91. const FETCH_BOUND = 6;
  92. const FETCH_CLASS = 8;
  93. const FETCH_CLASSTYPE = 262144;
  94. const FETCH_COLUMN = 7;
  95. const FETCH_FUNC = 10;
  96. const FETCH_GROUP = 65536;
  97. const FETCH_INTO = 9;
  98. const FETCH_LAZY = 1;
  99. const FETCH_NAMED = 11;
  100. const FETCH_NUM = 3;
  101. const FETCH_OBJ = 5;
  102. const FETCH_ORI_ABS = 4;
  103. const FETCH_ORI_FIRST = 2;
  104. const FETCH_ORI_LAST = 3;
  105. const FETCH_ORI_NEXT = 0;
  106. const FETCH_ORI_PRIOR = 1;
  107. const FETCH_ORI_REL = 5;
  108. const FETCH_SERIALIZE = 524288;
  109. const FETCH_UNIQUE = 196608;
  110. const NULL_EMPTY_STRING = 1;
  111. const NULL_NATURAL = 0;
  112. const NULL_TO_STRING = NULL;
  113. const PARAM_BOOL = 5;
  114. const PARAM_INPUT_OUTPUT = -2147483648;
  115. const PARAM_INT = 1;
  116. const PARAM_LOB = 3;
  117. const PARAM_NULL = 0;
  118. const PARAM_STMT = 4;
  119. const PARAM_STR = 2;
  120. /**
  121. * ATTRIBUTE CONSTANTS
  122. */
  123. /**
  124. * PDO derived attributes
  125. */
  126. const ATTR_AUTOCOMMIT = 0;
  127. const ATTR_PREFETCH = 1;
  128. const ATTR_TIMEOUT = 2;
  129. const ATTR_ERRMODE = 3;
  130. const ATTR_SERVER_VERSION = 4;
  131. const ATTR_CLIENT_VERSION = 5;
  132. const ATTR_SERVER_INFO = 6;
  133. const ATTR_CONNECTION_STATUS = 7;
  134. const ATTR_CASE = 8;
  135. const ATTR_CURSOR_NAME = 9;
  136. const ATTR_CURSOR = 10;
  137. const ATTR_ORACLE_NULLS = 11;
  138. const ATTR_PERSISTENT = 12;
  139. const ATTR_STATEMENT_CLASS = 13;
  140. const ATTR_FETCH_TABLE_NAMES = 14;
  141. const ATTR_FETCH_CATALOG_NAMES = 15;
  142. const ATTR_DRIVER_NAME = 16;
  143. const ATTR_STRINGIFY_FETCHES = 17;
  144. const ATTR_MAX_COLUMN_LEN = 18;
  145. /**
  146. * Doctrine constants
  147. */
  148. const ATTR_LISTENER = 100;
  149. const ATTR_QUOTE_IDENTIFIER = 101;
  150. const ATTR_FIELD_CASE = 102;
  151. const ATTR_IDXNAME_FORMAT = 103;
  152. const ATTR_SEQNAME_FORMAT = 104;
  153. const ATTR_SEQCOL_NAME = 105;
  154. const ATTR_CMPNAME_FORMAT = 118;
  155. const ATTR_DBNAME_FORMAT = 117;
  156. const ATTR_TBLCLASS_FORMAT = 119;
  157. const ATTR_TBLNAME_FORMAT = 120;
  158. const ATTR_FKNAME_FORMAT = 171;
  159. const ATTR_EXPORT = 140;
  160. const ATTR_DECIMAL_PLACES = 141;
  161. const ATTR_PORTABILITY = 106;
  162. const ATTR_VALIDATE = 107;
  163. const ATTR_COLL_KEY = 108;
  164. const ATTR_QUERY_LIMIT = 109;
  165. const ATTR_DEFAULT_TABLE_TYPE = 112;
  166. const ATTR_DEF_TEXT_LENGTH = 113;
  167. const ATTR_DEF_VARCHAR_LENGTH = 114;
  168. const ATTR_DEF_TABLESPACE = 115;
  169. const ATTR_EMULATE_DATABASE = 116;
  170. const ATTR_USE_NATIVE_ENUM = 117;
  171. const ATTR_DEFAULT_SEQUENCE = 133;
  172. const ATTR_FETCHMODE = 118;
  173. const ATTR_NAME_PREFIX = 121;
  174. const ATTR_CREATE_TABLES = 122;
  175. const ATTR_COLL_LIMIT = 123;
  176. const ATTR_CACHE = 150;
  177. const ATTR_RESULT_CACHE = 150;
  178. const ATTR_CACHE_LIFESPAN = 151;
  179. const ATTR_RESULT_CACHE_LIFESPAN = 151;
  180. const ATTR_LOAD_REFERENCES = 153;
  181. const ATTR_RECORD_LISTENER = 154;
  182. const ATTR_THROW_EXCEPTIONS = 155;
  183. const ATTR_DEFAULT_PARAM_NAMESPACE = 156;
  184. const ATTR_QUERY_CACHE = 157;
  185. const ATTR_QUERY_CACHE_LIFESPAN = 158;
  186. const ATTR_AUTOLOAD_TABLE_CLASSES = 160;
  187. const ATTR_MODEL_LOADING = 161;
  188. const ATTR_RECURSIVE_MERGE_FIXTURES = 162;
  189. const ATTR_USE_DQL_CALLBACKS = 164;
  190. const ATTR_AUTO_ACCESSOR_OVERRIDE = 165;
  191. const ATTR_AUTO_FREE_QUERY_OBJECTS = 166;
  192. const ATTR_DEFAULT_TABLE_CHARSET = 167;
  193. const ATTR_DEFAULT_TABLE_COLLATE = 168;
  194. const ATTR_DEFAULT_IDENTIFIER_OPTIONS = 169;
  195. const ATTR_DEFAULT_COLUMN_OPTIONS = 170;
  196. const ATTR_HYDRATE_OVERWRITE = 172;
  197. /**
  198. * LIMIT CONSTANTS
  199. */
  200. /**
  201. * constant for row limiting
  202. */
  203. const LIMIT_ROWS = 1;
  204. const QUERY_LIMIT_ROWS = 1;
  205. /**
  206. * constant for record limiting
  207. */
  208. const LIMIT_RECORDS = 2;
  209. const QUERY_LIMIT_RECORDS = 2;
  210. /**
  211. * FETCHMODE CONSTANTS
  212. */
  213. /**
  214. * PORTABILITY CONSTANTS
  215. */
  216. /**
  217. * Portability: turn off all portability features.
  218. * @see self::ATTR_PORTABILITY
  219. */
  220. const PORTABILITY_NONE = 0;
  221. /**
  222. * Portability: convert names of tables and fields to case defined in the
  223. * "field_case" option when using the query*(), fetch*() methods.
  224. * @see self::ATTR_PORTABILITY
  225. */
  226. const PORTABILITY_FIX_CASE = 1;
  227. /**
  228. * Portability: right trim the data output by query*() and fetch*().
  229. * @see self::ATTR_PORTABILITY
  230. */
  231. const PORTABILITY_RTRIM = 2;
  232. /**
  233. * Portability: force reporting the number of rows deleted.
  234. * @see self::ATTR_PORTABILITY
  235. */
  236. const PORTABILITY_DELETE_COUNT = 4;
  237. /**
  238. * Portability: convert empty values to null strings in data output by
  239. * query*() and fetch*().
  240. * @see self::ATTR_PORTABILITY
  241. */
  242. const PORTABILITY_EMPTY_TO_NULL = 8;
  243. /**
  244. * Portability: removes database/table qualifiers from associative indexes
  245. * @see self::ATTR_PORTABILITY
  246. */
  247. const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16;
  248. /**
  249. * Portability: makes Doctrine_Expression throw exception for unportable RDBMS expressions
  250. * @see self::ATTR_PORTABILITY
  251. */
  252. const PORTABILITY_EXPR = 32;
  253. /**
  254. * Portability: turn on all portability features.
  255. * @see self::ATTR_PORTABILITY
  256. */
  257. const PORTABILITY_ALL = 63;
  258. /**
  259. * LOCKMODE CONSTANTS
  260. */
  261. /**
  262. * mode for optimistic locking
  263. */
  264. const LOCK_OPTIMISTIC = 0;
  265. /**
  266. * mode for pessimistic locking
  267. */
  268. const LOCK_PESSIMISTIC = 1;
  269. /**
  270. * EXPORT CONSTANTS
  271. */
  272. /**
  273. * EXPORT_NONE
  274. */
  275. const EXPORT_NONE = 0;
  276. /**
  277. * EXPORT_TABLES
  278. */
  279. const EXPORT_TABLES = 1;
  280. /**
  281. * EXPORT_CONSTRAINTS
  282. */
  283. const EXPORT_CONSTRAINTS = 2;
  284. /**
  285. * EXPORT_PLUGINS
  286. */
  287. const EXPORT_PLUGINS = 4;
  288. /**
  289. * EXPORT_ALL
  290. */
  291. const EXPORT_ALL = 7;
  292. /**
  293. * HYDRATION CONSTANTS
  294. */
  295. const HYDRATE_RECORD = 2;
  296. /**
  297. * HYDRATE_ARRAY
  298. */
  299. const HYDRATE_ARRAY = 3;
  300. /**
  301. * HYDRATE_NONE
  302. */
  303. const HYDRATE_NONE = 4;
  304. /**
  305. * HYDRATE_SCALAR
  306. */
  307. const HYDRATE_SCALAR = 5;
  308. /**
  309. * HYDRATE_SINGLE_SCALAR
  310. */
  311. const HYDRATE_SINGLE_SCALAR = 6;
  312. /**
  313. * VALIDATION CONSTANTS
  314. */
  315. const VALIDATE_NONE = 0;
  316. /**
  317. * VALIDATE_LENGTHS
  318. */
  319. const VALIDATE_LENGTHS = 1;
  320. /**
  321. * VALIDATE_TYPES
  322. */
  323. const VALIDATE_TYPES = 2;
  324. /**
  325. * VALIDATE_CONSTRAINTS
  326. */
  327. const VALIDATE_CONSTRAINTS = 4;
  328. /**
  329. * VALIDATE_ALL
  330. */
  331. const VALIDATE_ALL = 7;
  332. /**
  333. * IDENTIFIER_AUTOINC
  334. *
  335. * constant for auto_increment identifier
  336. */
  337. const IDENTIFIER_AUTOINC = 1;
  338. /**
  339. * IDENTIFIER_SEQUENCE
  340. *
  341. * constant for sequence identifier
  342. */
  343. const IDENTIFIER_SEQUENCE = 2;
  344. /**
  345. * IDENTIFIER_NATURAL
  346. *
  347. * constant for normal identifier
  348. */
  349. const IDENTIFIER_NATURAL = 3;
  350. /**
  351. * IDENTIFIER_COMPOSITE
  352. *
  353. * constant for composite identifier
  354. */
  355. const IDENTIFIER_COMPOSITE = 4;
  356. /**
  357. * MODEL_LOADING_AGGRESSIVE
  358. *
  359. * Constant for agressive model loading
  360. * Will require_once() all found model files
  361. */
  362. const MODEL_LOADING_AGGRESSIVE = 1;
  363. /**
  364. * MODEL_LOADING_CONSERVATIVE
  365. *
  366. * Constant for conservative model loading
  367. * Will not require_once() found model files inititally instead it will build an array
  368. * and reference it in autoload() when a class is needed it will require_once() it
  369. */
  370. const MODEL_LOADING_CONSERVATIVE= 2;
  371. /**
  372. * Path to Doctrine root
  373. *
  374. * @var string $path doctrine root directory
  375. */
  376. private static $_path;
  377. /**
  378. * Debug bool true/false option
  379. *
  380. * @var boolean $_debug
  381. */
  382. private static $_debug = false;
  383. /**
  384. * Array of all the loaded models and the path to each one for autoloading
  385. *
  386. * @var array
  387. */
  388. private static $_loadedModelFiles = array();
  389. /**
  390. * Array of all the loaded validators
  391. *
  392. * @var array
  393. */
  394. private static $_validators = array();
  395. /**
  396. * __construct
  397. *
  398. * @return void
  399. * @throws Doctrine_Exception
  400. */
  401. public function __construct()
  402. {
  403. throw new Doctrine_Exception('Doctrine is static class. No instances can be created.');
  404. }
  405. /**
  406. * Returns an array of all the loaded models and the path where each of them exists
  407. *
  408. * @return array
  409. */
  410. public static function getLoadedModelFiles()
  411. {
  412. return self::$_loadedModelFiles;
  413. }
  414. /**
  415. * Turn on/off the debugging setting
  416. *
  417. * @param string $bool
  418. * @return void
  419. */
  420. public static function debug($bool = null)
  421. {
  422. if ($bool !== null) {
  423. self::$_debug = (bool) $bool;
  424. }
  425. return self::$_debug;
  426. }
  427. /**
  428. * Get the root path to Doctrine
  429. *
  430. * @return string
  431. */
  432. public static function getPath()
  433. {
  434. if ( ! self::$_path) {
  435. self::$_path = dirname(__FILE__);
  436. }
  437. return self::$_path;
  438. }
  439. /**
  440. * Load an individual model name and path in to the model loading registry
  441. *
  442. * @return null
  443. */
  444. public static function loadModel($className, $path = null)
  445. {
  446. self::$_loadedModelFiles[$className] = $path;
  447. }
  448. /**
  449. * Recursively load all models from a directory or array of directories
  450. *
  451. * @param string $directory Path to directory of models or array of directory paths
  452. * @param integer $modelLoading Pass value of Doctrine::ATTR_MODEL_LOADING to force a certain style of model loading
  453. * Allowed Doctrine::MODEL_LOADING_AGGRESSIVE(default) or Doctrine::MODEL_LOADING_CONSERVATIVE
  454. */
  455. public static function loadModels($directory, $modelLoading = null)
  456. {
  457. $manager = Doctrine_Manager::getInstance();
  458. $modelLoading = $modelLoading === null ? $manager->getAttribute(Doctrine::ATTR_MODEL_LOADING):$modelLoading;
  459. $loadedModels = array();
  460. if ($directory !== null) {
  461. foreach ((array) $directory as $dir) {
  462. if ( ! is_dir($dir)) {
  463. throw new Doctrine_Exception('You must pass a valid path to a directory containing Doctrine models');
  464. }
  465. $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
  466. RecursiveIteratorIterator::LEAVES_ONLY);
  467. foreach ($it as $file) {
  468. $e = explode('.', $file->getFileName());
  469. if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false) {
  470. $className = $e[0];
  471. if ( ! class_exists($className, false)) {
  472. if ($modelLoading == Doctrine::MODEL_LOADING_CONSERVATIVE) {
  473. self::loadModel($className, $file->getPathName());
  474. $loadedModels[$className] = $className;
  475. } else {
  476. $declaredBefore = get_declared_classes();
  477. require_once($file->getPathName());
  478. $declaredAfter = get_declared_classes();
  479. // Using array_slice because array_diff is broken is some PHP versions
  480. $foundClasses = array_slice($declaredAfter, count($declaredBefore));
  481. if ($foundClasses) {
  482. foreach ($foundClasses as $className) {
  483. if (self::isValidModelClass($className)) {
  484. $loadedModels[$className] = $className;
  485. self::loadModel($className, $file->getPathName());
  486. }
  487. }
  488. }
  489. $previouslyLoaded = array_keys(self::$_loadedModelFiles, $file->getPathName());
  490. if ( ! empty($previouslyLoaded)) {
  491. $previouslyLoaded = array_combine(array_values($previouslyLoaded), array_values($previouslyLoaded));
  492. $loadedModels = array_merge($loadedModels, $previouslyLoaded);
  493. }
  494. }
  495. } else {
  496. $loadedModels[$className] = $className;
  497. }
  498. }
  499. }
  500. }
  501. }
  502. asort($loadedModels);
  503. return $loadedModels;
  504. }
  505. /**
  506. * Get all the loaded models, you can provide an array of classes or it will use get_declared_classes()
  507. *
  508. * Will filter through an array of classes and return the Doctrine_Records out of them.
  509. * If you do not specify $classes it will return all of the currently loaded Doctrine_Records
  510. *
  511. * @param classes Array of classes to filter through, otherwise uses get_declared_classes()
  512. * @return array $loadedModels
  513. */
  514. public static function getLoadedModels($classes = null)
  515. {
  516. if ($classes === null) {
  517. $classes = get_declared_classes();
  518. $classes = array_merge($classes, array_keys(self::$_loadedModelFiles));
  519. }
  520. return self::filterInvalidModels($classes);
  521. }
  522. /**
  523. * Initialize all models so everything is present and loaded in to memory
  524. * This will also inheritently initialize any model behaviors and add
  525. * the models generated by Doctrine generators and add them to the $models
  526. * array
  527. *
  528. * @param string $models
  529. * @return array $models
  530. */
  531. public static function initializeModels($models)
  532. {
  533. $models = self::filterInvalidModels($models);
  534. foreach ($models as $model) {
  535. $declaredBefore = get_declared_classes();
  536. Doctrine::getTable($model);
  537. $declaredAfter = get_declared_classes();
  538. // Using array_slice because array_diff is broken is some PHP versions
  539. $foundClasses = array_slice($declaredAfter, count($declaredBefore) - 1);
  540. foreach ($foundClasses as $class) {
  541. if (self::isValidModelClass($class)) {
  542. $models[] = $class;
  543. }
  544. }
  545. }
  546. $models = self::filterInvalidModels($models);
  547. return $models;
  548. }
  549. /**
  550. * Filter through an array of classes and return all the classes that are valid models.
  551. * This will inflect the class, causing it to be loaded in to memory.
  552. *
  553. * @param classes Array of classes to filter through, otherwise uses get_declared_classes()
  554. * @return array $loadedModels
  555. */
  556. public static function filterInvalidModels($classes)
  557. {
  558. $validModels = array();
  559. foreach ((array) $classes as $name) {
  560. if (self::isValidModelClass($name) && ! in_array($name, $validModels)) {
  561. $validModels[] = $name;
  562. }
  563. }
  564. return $validModels;
  565. }
  566. /**
  567. * Checks if what is passed is a valid Doctrine_Record
  568. * Will load class in to memory in order to inflect it and find out information about the class
  569. *
  570. * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected
  571. * @return boolean
  572. */
  573. public static function isValidModelClass($class)
  574. {
  575. if ($class instanceof Doctrine_Record) {
  576. $class = get_class($class);
  577. }
  578. if (is_string($class) && class_exists($class)) {
  579. $class = new ReflectionClass($class);
  580. }
  581. if ($class instanceof ReflectionClass) {
  582. // Skip the following classes
  583. // - abstract classes
  584. // - not a subclass of Doctrine_Record
  585. if ( ! $class->isAbstract() && $class->isSubClassOf('Doctrine_Record')) {
  586. return true;
  587. }
  588. }
  589. return false;
  590. }
  591. /**
  592. * Get the connection object for a table by the actual table name
  593. * FIXME: I think this method is flawed because a individual connections could have the same table name
  594. *
  595. * @param string $tableName
  596. * @return Doctrine_Connection
  597. */
  598. public static function getConnectionByTableName($tableName)
  599. {
  600. $loadedModels = self::getLoadedModels();
  601. foreach ($loadedModels as $name) {
  602. $table = Doctrine::getTable($name);
  603. if ($table->getTableName() == $tableName) {
  604. return $table->getConnection();
  605. }
  606. }
  607. return Doctrine_Manager::connection();
  608. }
  609. /**
  610. * Method for importing existing schema to Doctrine_Record classes
  611. *
  612. * @param string $directory Directory to write your models to
  613. * @param array $databases Array of databases to generate models for
  614. * @param array $options Array of options
  615. * @return boolean
  616. * @throws Exception
  617. */
  618. public static function generateModelsFromDb($directory, array $databases = array(), array $options = array())
  619. {
  620. return Doctrine_Manager::connection()->import->importSchema($directory, $databases, $options);
  621. }
  622. /**
  623. * Generates models from database to temporary location then uses those models to generate a yaml schema file.
  624. * This should probably be fixed. We should write something to generate a yaml schema file directly from the database.
  625. *
  626. * @param string $yamlPath Path to write oyur yaml schema file to
  627. * @param array $options Array of options
  628. * @return void
  629. */
  630. public static function generateYamlFromDb($yamlPath, array $databases = array(), array $options = array())
  631. {
  632. $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models';
  633. $options['generateBaseClasses'] = isset($options['generateBaseClasses']) ? $options['generateBaseClasses']:false;
  634. $result = Doctrine::generateModelsFromDb($directory, $databases, $options);
  635. if ( empty($result) && ! is_dir($directory)) {
  636. throw new Doctrine_Exception('No models generated from your databases');
  637. }
  638. $export = new Doctrine_Export_Schema();
  639. $result = $export->exportSchema($yamlPath, 'yml', $directory);
  640. Doctrine_Lib::removeDirectories($directory);
  641. return $result;
  642. }
  643. /**
  644. * Generate a yaml schema file from an existing directory of models
  645. *
  646. * @param string $yamlPath Path to your yaml schema files
  647. * @param string $directory Directory to generate your models in
  648. * @param array $options Array of options to pass to the schema importer
  649. * @return void
  650. */
  651. public static function generateModelsFromYaml($yamlPath, $directory, $options = array())
  652. {
  653. $import = new Doctrine_Import_Schema();
  654. $import->setOptions($options);
  655. return $import->importSchema($yamlPath, 'yml', $directory);
  656. }
  657. /**
  658. * Creates database tables for the models in the specified directory
  659. *
  660. * @param string $directory Directory containing your models
  661. * @return void
  662. */
  663. public static function createTablesFromModels($directory = null)
  664. {
  665. return Doctrine_Manager::connection()->export->exportSchema($directory);
  666. }
  667. /**
  668. * Creates database tables for the models in the supplied array
  669. *
  670. * @param array $array An array of models to be exported
  671. * @return void
  672. */
  673. public static function createTablesFromArray($array)
  674. {
  675. return Doctrine_Manager::connection()->export->exportClasses($array);
  676. }
  677. /**
  678. * Generate a array of sql for the passed array of models
  679. *
  680. * @param array $array
  681. * @return array $sql
  682. */
  683. public static function generateSqlFromArray($array)
  684. {
  685. return Doctrine_Manager::connection()->export->exportClassesSql($array);
  686. }
  687. /**
  688. * Generate a sql string to create the tables from all loaded models
  689. * or the models found in the passed directory.
  690. *
  691. * @param string $directory
  692. * @return string $build String of sql queries. One query per line
  693. */
  694. public static function generateSqlFromModels($directory = null)
  695. {
  696. $conn = Doctrine_Manager::connection();
  697. $sql = $conn->export->exportSql($directory);
  698. $build = '';
  699. foreach ($sql as $query) {
  700. $build .= $query.$conn->sql_file_delimiter;
  701. }
  702. return $build;
  703. }
  704. /**
  705. * Generate yaml schema file for the models in the specified directory
  706. *
  707. * @param string $yamlPath Path to your yaml schema files
  708. * @param string $directory Directory to generate your models in
  709. * @return void
  710. */
  711. public static function generateYamlFromModels($yamlPath, $directory)
  712. {
  713. $export = new Doctrine_Export_Schema();
  714. return $export->exportSchema($yamlPath, 'yml', $directory);
  715. }
  716. /**
  717. * Creates databases for connections
  718. *
  719. * @param string $specifiedConnections Array of connections you wish to create the database for
  720. * @return void
  721. */
  722. public static function createDatabases($specifiedConnections = array())
  723. {
  724. return Doctrine_Manager::getInstance()->createDatabases($specifiedConnections);
  725. }
  726. /**
  727. * Drops databases for connections
  728. *
  729. * @param string $specifiedConnections Array of connections you wish to drop the database for
  730. * @return void
  731. */
  732. public static function dropDatabases($specifiedConnections = array())
  733. {
  734. return Doctrine_Manager::getInstance()->dropDatabases($specifiedConnections);
  735. }
  736. /**
  737. * Dump data to a yaml fixtures file
  738. *
  739. * @param string $yamlPath Path to write the yaml data fixtures to
  740. * @param string $individualFiles Whether or not to dump data to individual fixtures files
  741. * @return void
  742. */
  743. public static function dumpData($yamlPath, $individualFiles = false)
  744. {
  745. $data = new Doctrine_Data();
  746. return $data->exportData($yamlPath, 'yml', array(), $individualFiles);
  747. }
  748. /**
  749. * Load data from a yaml fixtures file.
  750. * The output of dumpData can be fed to loadData
  751. *
  752. * @param string $yamlPath Path to your yaml data fixtures
  753. * @param string $append Whether or not to append the data
  754. * @return void
  755. */
  756. public static function loadData($yamlPath, $append = false)
  757. {
  758. $data = new Doctrine_Data();
  759. return $data->importData($yamlPath, 'yml', array(), $append);
  760. }
  761. /**
  762. * Migrate database to specified $to version. Migrates from current to latest if you do not specify.
  763. *
  764. * @param string $migrationsPath Path to migrations directory which contains your migration classes
  765. * @param string $to Version you wish to migrate to.
  766. * @return bool true
  767. * @throws new Doctrine_Migration_Exception
  768. */
  769. public static function migrate($migrationsPath, $to = null)
  770. {
  771. $migration = new Doctrine_Migration($migrationsPath);
  772. return $migration->migrate($to);
  773. }
  774. /**
  775. * Generate new migration class skeleton
  776. *
  777. * @param string $className Name of the Migration class to generate
  778. * @param string $migrationsPath Path to directory which contains your migration classes
  779. */
  780. public static function generateMigrationClass($className, $migrationsPath)
  781. {
  782. $builder = new Doctrine_Migration_Builder($migrationsPath);
  783. return $builder->generateMigrationClass($className);
  784. }
  785. /**
  786. * Generate a set of migration classes from an existing database
  787. *
  788. * @param string $migrationsPath
  789. * @return void
  790. * @throws new Doctrine_Migration_Exception
  791. */
  792. public static function generateMigrationsFromDb($migrationsPath)
  793. {
  794. $builder = new Doctrine_Migration_Builder($migrationsPath);
  795. return $builder->generateMigrationsFromDb();
  796. }
  797. /**
  798. * Generate a set of migration classes from an existing set of models
  799. *
  800. * @param string $migrationsPath Path to your Doctrine migration classes
  801. * @param string $modelsPath Path to your Doctrine model classes
  802. * @param integer $modelLoading Style of model loading to use for loading the models in order to generate migrations
  803. * @return void
  804. */
  805. public static function generateMigrationsFromModels($migrationsPath, $modelsPath = null, $modelLoading = null)
  806. {
  807. $builder = new Doctrine_Migration_Builder($migrationsPath);
  808. return $builder->generateMigrationsFromModels($modelsPath, $modelLoading);
  809. }
  810. /**
  811. * Generate a set of migration classes by generating differences between two sets
  812. * of schema information
  813. *
  814. * @param string $migrationsPath Path to your Doctrine migration classes
  815. * @param string $from From schema information
  816. * @param string $to To schema information
  817. * @return array $changes
  818. */
  819. public static function generateMigrationsFromDiff($migrationsPath, $from, $to)
  820. {
  821. $diff = new Doctrine_Migration_Diff($from, $to, $migrationsPath);
  822. return $diff->generateMigrationClasses();
  823. }
  824. /**
  825. * Get the Doctrine_Table object for the passed model
  826. *
  827. * @param string $componentName
  828. * @return Doctrine_Table
  829. */
  830. public static function getTable($componentName)
  831. {
  832. return Doctrine_Manager::getInstance()->getConnectionForComponent($componentName)->getTable($componentName);
  833. }
  834. /**
  835. * Method for making a single file of most used doctrine runtime components
  836. * including the compiled file instead of multiple files (in worst
  837. * cases dozens of files) can improve performance by an order of magnitude
  838. *
  839. * @param string $target
  840. * @param array $includedDrivers
  841. * @throws Doctrine_Exception
  842. * @return void
  843. */
  844. public static function compile($target = null, $includedDrivers = array())
  845. {
  846. return Doctrine_Compiler::compile($target, $includedDrivers);
  847. }
  848. /**
  849. * simple autoload function
  850. * returns true if the class was loaded, otherwise false
  851. *
  852. * @param string $classname
  853. * @return boolean
  854. */
  855. public static function autoload($className)
  856. {
  857. if (class_exists($className, false) || interface_exists($className, false)) {
  858. return false;
  859. }
  860. $class = self::getPath() . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
  861. if (file_exists($class)) {
  862. require $class;
  863. return true;
  864. }
  865. $loadedModels = self::$_loadedModelFiles;
  866. if (isset($loadedModels[$className]) && file_exists($loadedModels[$className])) {
  867. require $loadedModels[$className];
  868. return true;
  869. }
  870. return false;
  871. }
  872. /**
  873. * dumps a given variable
  874. *
  875. * @param mixed $var a variable of any type
  876. * @param boolean $output whether to output the content
  877. * @param string $indent indention string
  878. * @return void|string
  879. */
  880. public static function dump($var, $output = true, $indent = "")
  881. {
  882. $ret = array();
  883. switch (gettype($var)) {
  884. case 'array':
  885. $ret[] = 'Array(';
  886. $indent .= " ";
  887. foreach ($var as $k => $v) {
  888. $ret[] = $indent . $k . ' : ' . self::dump($v, false, $indent);
  889. }
  890. $indent = substr($indent,0, -4);
  891. $ret[] = $indent . ")";
  892. break;
  893. case 'object':
  894. $ret[] = 'Object(' . get_class($var) . ')';
  895. break;
  896. default:
  897. $ret[] = var_export($var, true);
  898. }
  899. if ($output) {
  900. print implode("\n", $ret);
  901. }
  902. return implode("\n", $ret);
  903. }
  904. }