BaseTestCaseORM.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. namespace Tool;
  3. use Gedmo\Tool\Logging\DBAL\QueryAnalyzer;
  4. use Doctrine\Common\Annotations\AnnotationReader;
  5. use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
  6. use Doctrine\ORM\EntityManager;
  7. use Doctrine\Common\EventManager;
  8. use Doctrine\ORM\Tools\SchemaTool;
  9. use Doctrine\ORM\Configuration;
  10. use Gedmo\Translatable\TranslatableListener;
  11. use Gedmo\Sluggable\SluggableListener;
  12. use Gedmo\Tree\TreeListener;
  13. use Gedmo\Timestampable\TimestampableListener;
  14. use Gedmo\Loggable\LoggableListener;
  15. use Gedmo\SoftDeleteable\SoftDeleteableListener;
  16. use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
  17. use Doctrine\ORM\Mapping\DefaultNamingStrategy;
  18. use Doctrine\ORM\Repository\DefaultRepositoryFactory;
  19. /**
  20. * Base test case contains common mock objects
  21. * and functionality among all extensions using
  22. * ORM object manager
  23. *
  24. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  25. * @link http://www.gediminasm.org
  26. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  27. */
  28. abstract class BaseTestCaseORM extends \PHPUnit_Framework_TestCase
  29. {
  30. /**
  31. * @var EntityManager
  32. */
  33. protected $em;
  34. /**
  35. * @var QueryAnalyzer
  36. */
  37. protected $queryAnalyzer;
  38. /**
  39. * {@inheritdoc}
  40. */
  41. protected function setUp()
  42. {
  43. }
  44. /**
  45. * EntityManager mock object together with
  46. * annotation mapping driver and pdo_sqlite
  47. * database in memory
  48. *
  49. * @param EventManager $evm
  50. * @return EntityManager
  51. */
  52. protected function getMockSqliteEntityManager(EventManager $evm = null, Configuration $config = null)
  53. {
  54. $conn = array(
  55. 'driver' => 'pdo_sqlite',
  56. 'memory' => true,
  57. );
  58. $config = null === $config ? $this->getMockAnnotatedConfig() : $config;
  59. $em = EntityManager::create($conn, $config, $evm ?: $this->getEventManager());
  60. $schema = array_map(function($class) use ($em) {
  61. return $em->getClassMetadata($class);
  62. }, (array)$this->getUsedEntityFixtures());
  63. $schemaTool = new SchemaTool($em);
  64. $schemaTool->dropSchema(array());
  65. $schemaTool->createSchema($schema);
  66. return $this->em = $em;
  67. }
  68. /**
  69. * EntityManager mock object together with
  70. * annotation mapping driver and custom
  71. * connection
  72. *
  73. * @param array $conn
  74. * @param EventManager $evm
  75. * @return EntityManager
  76. */
  77. protected function getMockCustomEntityManager(array $conn, EventManager $evm = null)
  78. {
  79. $config = $this->getMockAnnotatedConfig();
  80. $em = EntityManager::create($conn, $config, $evm ?: $this->getEventManager());
  81. $schema = array_map(function($class) use ($em) {
  82. return $em->getClassMetadata($class);
  83. }, (array)$this->getUsedEntityFixtures());
  84. $schemaTool = new SchemaTool($em);
  85. $schemaTool->dropSchema(array());
  86. $schemaTool->createSchema($schema);
  87. return $this->em = $em;
  88. }
  89. /**
  90. * EntityManager mock object with
  91. * annotation mapping driver
  92. *
  93. * @param EventManager $evm
  94. * @return EntityManager
  95. */
  96. protected function getMockMappedEntityManager(EventManager $evm = null)
  97. {
  98. $driver = $this->getMock('Doctrine\DBAL\Driver');
  99. $driver->expects($this->once())
  100. ->method('getDatabasePlatform')
  101. ->will($this->returnValue($this->getMock('Doctrine\DBAL\Platforms\MySqlPlatform')));
  102. $conn = $this->getMock('Doctrine\DBAL\Connection', array(), array(array(), $driver));
  103. $conn->expects($this->once())
  104. ->method('getEventManager')
  105. ->will($this->returnValue($evm ?: $this->getEventManager()));
  106. $config = $this->getMockAnnotatedConfig();
  107. $this->em = EntityManager::create($conn, $config);
  108. return $this->em;
  109. }
  110. /**
  111. * Starts query statistic log
  112. *
  113. * @throws \RuntimeException
  114. */
  115. protected function startQueryLog()
  116. {
  117. if (!$this->em || !$this->em->getConnection()->getDatabasePlatform()) {
  118. throw new \RuntimeException('EntityManager and database platform must be initialized');
  119. }
  120. $this->queryAnalyzer = new QueryAnalyzer($this->em->getConnection()->getDatabasePlatform());
  121. $this->em
  122. ->getConfiguration()
  123. ->expects($this->any())
  124. ->method('getSQLLogger')
  125. ->will($this->returnValue($this->queryAnalyzer));
  126. }
  127. /**
  128. * Stops query statistic log and outputs
  129. * the data to screen or file
  130. *
  131. * @param boolean $dumpOnlySql
  132. * @param boolean $writeToLog
  133. * @throws \RuntimeException
  134. */
  135. protected function stopQueryLog($dumpOnlySql = false, $writeToLog = false)
  136. {
  137. if ($this->queryAnalyzer) {
  138. $output = $this->queryAnalyzer->getOutput($dumpOnlySql);
  139. if ($writeToLog) {
  140. $fileName = __DIR__.'/../../temp/query_debug_'.time().'.log';
  141. if (($file = fopen($fileName, 'w+')) !== false) {
  142. fwrite($file, $output);
  143. fclose($file);
  144. } else {
  145. throw new \RuntimeException('Unable to write to the log file');
  146. }
  147. } else {
  148. echo $output;
  149. }
  150. }
  151. }
  152. /**
  153. * Creates default mapping driver
  154. *
  155. * @return \Doctrine\ORM\Mapping\Driver\Driver
  156. */
  157. protected function getMetadataDriverImplementation()
  158. {
  159. return new AnnotationDriver($_ENV['annotation_reader']);
  160. }
  161. /**
  162. * Get a list of used fixture classes
  163. *
  164. * @return array
  165. */
  166. abstract protected function getUsedEntityFixtures();
  167. /**
  168. * Build event manager
  169. *
  170. * @return EventManager
  171. */
  172. private function getEventManager()
  173. {
  174. $evm = new EventManager;
  175. $evm->addEventSubscriber(new TreeListener);
  176. $evm->addEventSubscriber(new SluggableListener);
  177. $evm->addEventSubscriber(new LoggableListener);
  178. $evm->addEventSubscriber(new TranslatableListener);
  179. $evm->addEventSubscriber(new TimestampableListener);
  180. $evm->addEventSubscriber(new SoftDeleteableListener);
  181. return $evm;
  182. }
  183. /**
  184. * Get annotation mapping configuration
  185. *
  186. * @return \Doctrine\ORM\Configuration
  187. */
  188. protected function getMockAnnotatedConfig()
  189. {
  190. // We need to mock every method except the ones which
  191. // handle the filters
  192. $configurationClass = 'Doctrine\ORM\Configuration';
  193. $refl = new \ReflectionClass($configurationClass);
  194. $methods = $refl->getMethods();
  195. $mockMethods = array();
  196. foreach ($methods as $method) {
  197. if ($method->name !== 'addFilter' && $method->name !== 'getFilterClassName') {
  198. $mockMethods[] = $method->name;
  199. }
  200. }
  201. $config = $this->getMock($configurationClass, $mockMethods);
  202. $config
  203. ->expects($this->once())
  204. ->method('getProxyDir')
  205. ->will($this->returnValue(__DIR__.'/../../temp'))
  206. ;
  207. $config
  208. ->expects($this->once())
  209. ->method('getProxyNamespace')
  210. ->will($this->returnValue('Proxy'))
  211. ;
  212. $config
  213. ->expects($this->once())
  214. ->method('getAutoGenerateProxyClasses')
  215. ->will($this->returnValue(true))
  216. ;
  217. $config
  218. ->expects($this->once())
  219. ->method('getClassMetadataFactoryName')
  220. ->will($this->returnValue('Doctrine\\ORM\\Mapping\\ClassMetadataFactory'))
  221. ;
  222. $mappingDriver = $this->getMetadataDriverImplementation();
  223. $config
  224. ->expects($this->any())
  225. ->method('getMetadataDriverImpl')
  226. ->will($this->returnValue($mappingDriver))
  227. ;
  228. $config
  229. ->expects($this->any())
  230. ->method('getDefaultRepositoryClassName')
  231. ->will($this->returnValue('Doctrine\\ORM\\EntityRepository'))
  232. ;
  233. $config
  234. ->expects($this->any())
  235. ->method('getQuoteStrategy')
  236. ->will($this->returnValue(new DefaultQuoteStrategy))
  237. ;
  238. $config
  239. ->expects($this->any())
  240. ->method('getNamingStrategy')
  241. ->will($this->returnValue(new DefaultNamingStrategy))
  242. ;
  243. $config
  244. ->expects($this->once())
  245. ->method('getRepositoryFactory')
  246. ->will($this->returnValue(new DefaultRepositoryFactory))
  247. ;
  248. return $config;
  249. }
  250. }