EMongoDbFixtureManager.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. /**
  3. * EMongoDbFixtureManager
  4. *
  5. * @author Philippe Gaultier <pgaultier@ibitux.com>
  6. * @copyright 2010-2011 Ibitux
  7. * @license http://www.yiiframework.com/license/ BSD license
  8. * @category tests
  9. * @package ext.YiiMongoDbSuite.tests
  10. * @since v1.3.6
  11. */
  12. /**
  13. * EMongoDbFixtureManager manages simple mongodb fixtures during tests
  14. *
  15. * A fixture represents a list of documents for a specific collection.
  16. * For a test method, using a fixture means that a the beginning of the method,
  17. * the collection has and only has the documents that are given in the fixture.
  18. * Therefore, the collection's state is predictable.
  19. *
  20. * A fixture is represented as a PHP script whose name (without suffix) is the
  21. * same as the collection name. The PHP script returns an array representing a list
  22. * of documents. Each row is an associative array of properties values indexed
  23. * by property names.
  24. *
  25. * A fixture can be associated with an init script which sits under the same fixture
  26. * directory and is named as "CollectionName.init.php". The init script is used to
  27. * initialize the collection before populating the fixture data into the collection.
  28. * If the init script does not exist, the collection will be emptied.
  29. *
  30. * Fixtures must be stored under the {@link basePath} directory. The directory
  31. * may contain a file named "init.php" which will be executed once to initialize
  32. * the database. If this file is not found, all available fixtures will be loaded
  33. * into the database.
  34. *
  35. * @author Philippe Gaultier <pgaultier@ibitux.com>
  36. * @copyright 2010-2011 Ibitux
  37. * @license http://www.yiiframework.com/license/ BSD license
  38. * @category tests
  39. * @package ext.YiiMongoDbSuite.tests
  40. * @since v1.3.6
  41. */
  42. class EMongoDbFixtureManager extends CApplicationComponent
  43. {
  44. /**
  45. * @var string the name of the initialization script that would be executed before the whole test set runs.
  46. * Defaults to 'init.php'. If the script does not exist, every collection with a fixture file will be reset.
  47. */
  48. public $initScript='init.php';
  49. /**
  50. * @var string the suffix for fixture initialization scripts.
  51. * If a collection is associated with such a script whose name is CollectionName suffixed this property value,
  52. * then the script will be executed each time before the table is reset.
  53. */
  54. public $initScriptSuffix='.init.php';
  55. /**
  56. * @var string the base path containing all fixtures. Defaults to null, meaning
  57. * the path 'protected/tests/fixtures'.
  58. */
  59. public $basePath;
  60. /**
  61. * @var string the ID of the mongodb connection. Defaults to 'mongodb'.
  62. * Note, data in this database may be deleted or modified during testing.
  63. * Make sure you have a backup database.
  64. */
  65. public $connectionID='mongodb';
  66. private $_mongoDb;
  67. private $_fixtures;
  68. private $_rows; // fixture name, row alias => row
  69. private $_records; // fixture name, row alias => record (or class name)
  70. private $_collectionList; // list of collections available in database
  71. /**
  72. * Initializes this application component.
  73. */
  74. public function init()
  75. {
  76. parent::init();
  77. if($this->basePath===null)
  78. $this->basePath=Yii::getPathOfAlias('application.tests.fixtures');
  79. $this->prepare();
  80. }
  81. /**
  82. * Returns the database connection used to load fixtures.
  83. * @return MongoDb the database connection
  84. */
  85. public function getDbConnection()
  86. {
  87. if($this->_mongoDb===null)
  88. {
  89. $this->_mongoDb=Yii::app()->getComponent($this->connectionID)->getDbInstance();
  90. if(!$this->_mongoDb instanceof MongoDB)
  91. throw new CException(Yii::t('yii','EMongoDbFixtureManager.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
  92. array('{id}'=>$this->connectionID)));
  93. }
  94. return $this->_mongoDb;
  95. }
  96. /**
  97. * Prepares the fixtures for the whole test.
  98. * This method is invoked in {@link init}. It executes the database init script
  99. * if it exists. Otherwise, it will load all available fixtures.
  100. */
  101. public function prepare()
  102. {
  103. $initFile=$this->basePath . DIRECTORY_SEPARATOR . $this->initScript;
  104. if(is_file($initFile))
  105. require($initFile);
  106. else
  107. {
  108. foreach($this->getFixtures() as $collectionName=>$fixturePath)
  109. {
  110. $this->resetCollection($collectionName);
  111. $this->loadFixture($collectionName);
  112. }
  113. }
  114. }
  115. /**
  116. * Resets the collection to the state that it contains no fixture data.
  117. * If there is an init script named "tests/fixtures/CollectionName.init.php",
  118. * the script will be executed.
  119. * Otherwise, {@link truncateCollection} will be invoked to delete all documents
  120. * in the collection.
  121. * @param string $collectionName the collection name
  122. */
  123. public function resetCollection($collectionName)
  124. {
  125. $initFile=$this->basePath . DIRECTORY_SEPARATOR . $collectionName . $this->initScriptSuffix;
  126. if(is_file($initFile))
  127. require($initFile);
  128. else
  129. $this->truncateCollection($collectionName);
  130. }
  131. /**
  132. * Loads the fixture for the specified collection.
  133. * This method will insert documents given in the fixture into the corresponding collection.
  134. * The loaded documents will be returned by this method.
  135. * If the fixture does not exist, this method will return false.
  136. * Note, you may want to call {@link resetCollection} before calling this method
  137. * so that the collection is emptied first.
  138. * @param string $collectionName collection name
  139. * @return array the loaded fixture rows indexed by row aliases (if any).
  140. * False is returned if the collection does not have a fixture.
  141. */
  142. public function loadFixture($collectionName)
  143. {
  144. $fileName=$this->basePath.DIRECTORY_SEPARATOR.$collectionName.'.php';
  145. if(!is_file($fileName))
  146. return false;
  147. $rows=array();
  148. foreach(require($fileName) as $alias=>$row)
  149. {
  150. $this->getDbConnection()->{$collectionName}->save($row);
  151. $rows[$alias]=$row;
  152. }
  153. return $rows;
  154. }
  155. /**
  156. * Check if requested collection exists
  157. * @param string $collectionName collection name
  158. * @return boolean
  159. */
  160. protected function isCollection($collectionName) {
  161. if ($this->_collectionList === null) {
  162. $this->_collectionList = array();
  163. foreach($this->getDbConnection()->listCollections() as $collection) {
  164. $this->_collectionList[] = $collection->getName();
  165. }
  166. }
  167. return in_array($collectionName, $this->_collectionList);
  168. }
  169. /**
  170. * Returns the information of the available fixtures.
  171. * This method will search for all PHP files under {@link basePath}.
  172. * If a file's name is the same as a collection name, it is considered to be the fixture data for that table.
  173. * @return array the information of the available fixtures (collection name => fixture file)
  174. */
  175. public function getFixtures()
  176. {
  177. if($this->_fixtures===null)
  178. {
  179. $this->_fixtures=array();
  180. $folder=opendir($this->basePath);
  181. $suffixLen=strlen($this->initScriptSuffix);
  182. while($file=readdir($folder))
  183. {
  184. if($file==='.' || $file==='..' || $file===$this->initScript)
  185. continue;
  186. $path=$this->basePath.DIRECTORY_SEPARATOR.$file;
  187. if(substr($file,-4)==='.php' && is_file($path) && substr($file,-$suffixLen)!==$this->initScriptSuffix)
  188. {
  189. $collectionName=substr($file,0,-4);
  190. if($this->isCollection($collectionName) === true)
  191. {
  192. $this->_fixtures[$collectionName]=$path;
  193. }
  194. }
  195. }
  196. closedir($folder);
  197. }
  198. return $this->_fixtures;
  199. }
  200. /**
  201. * Removes all documents from the specified collection.
  202. * @param string $collectionName the collection name
  203. */
  204. public function truncateCollection($collectionName)
  205. {
  206. $this->getDbConnection()->{$collectionName}->remove(array());
  207. }
  208. /**
  209. * Truncates all collections.
  210. * @see truncateCollection
  211. */
  212. public function truncateCollections()
  213. {
  214. foreach($this->getDbConnection()->listCollections() as $collection)
  215. $this->truncateCollection($collection->getName());
  216. }
  217. /**
  218. * Loads the specified fixtures.
  219. * For each fixture, the corresponding collection will be reset first by calling
  220. * {@link resetCollection} and then be populated with the fixture data.
  221. * The loaded fixture data may be later retrieved using {@link getRows}
  222. * and {@link getRecord}.
  223. * Note, if a collection does not have fixture data, {@link resetCollection} will still
  224. * be called to reset the table.
  225. * @param array $fixtures fixtures to be loaded. The array keys are fixture names,
  226. * and the array values are either EMongoDocument class names or collection names.
  227. * If collection names, they must begin with a colon character (e.g. 'Post'
  228. * means an EMongoDocument class, while ':Post' means a collection name).
  229. */
  230. public function load($fixtures)
  231. {
  232. $this->_rows=array();
  233. $this->_records=array();
  234. foreach($fixtures as $fixtureName=>$collectionName)
  235. {
  236. if($collectionName[0]===':')
  237. {
  238. $collectionName=substr($collectionName,1);
  239. unset($modelClass);
  240. }
  241. else
  242. {
  243. $modelClass=Yii::import($collectionName,true);
  244. $collectionName=EMongoDocument::model($modelClass)->getCollectionName();
  245. }
  246. $this->resetCollection($collectionName);
  247. $rows=$this->loadFixture($collectionName);
  248. if(is_array($rows) && is_string($fixtureName))
  249. {
  250. $this->_rows[$fixtureName]=$rows;
  251. if(isset($modelClass))
  252. {
  253. foreach(array_keys($rows) as $alias)
  254. $this->_records[$fixtureName][$alias]=$modelClass;
  255. }
  256. }
  257. }
  258. }
  259. /**
  260. * Returns the fixture data documents.
  261. * The documents will have updated primary key.
  262. * @param string $name the fixture name
  263. * @return array the fixture data documents. False is returned if there is no such fixture data.
  264. */
  265. public function getRows($name)
  266. {
  267. if(isset($this->_rows[$name]))
  268. return $this->_rows[$name];
  269. else
  270. return false;
  271. }
  272. /**
  273. * Returns the specified EMongoDocument instance in the fixture data.
  274. * @param string $name the fixture name
  275. * @param string $alias the alias for the fixture data document
  276. * @return EMongoDocument the MongoDocument instance. False is returned
  277. * if there is no such fixture document.
  278. */
  279. public function getRecord($name,$alias)
  280. {
  281. if(isset($this->_records[$name][$alias]))
  282. {
  283. if(is_string($this->_records[$name][$alias]))
  284. {
  285. $row=$this->_rows[$name][$alias];
  286. $model=EMongoDocument::model($this->_records[$name][$alias]);
  287. $pk = $row['_id'];
  288. $this->_records[$name][$alias]=$model->findByPk($pk);
  289. }
  290. return $this->_records[$name][$alias];
  291. }
  292. else
  293. return false;
  294. }
  295. }