BaseTestCaseORM.php 8.2KB

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