EntityManagerMockFactory.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Sonata Project package.
  4. *
  5. * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Sonata\CoreBundle\Test;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Doctrine\ORM\Version;
  13. class EntityManagerMockFactory
  14. {
  15. /**
  16. * @param \PHPUnit_Framework_TestCase $test
  17. * @param \Closure $qbCallback
  18. * @param $fields
  19. *
  20. * @return EntityManagerInterface
  21. */
  22. public static function create(\PHPUnit_Framework_TestCase $test, \Closure $qbCallback, $fields)
  23. {
  24. $query = $test->getMockBuilder('Doctrine\ORM\AbstractQuery')
  25. ->disableOriginalConstructor()->getMock();
  26. $query->expects($test->any())->method('execute')->will($test->returnValue(true));
  27. if (Version::compare('2.5.0') < 1) {
  28. $entityManager = $test->getMockBuilder('Doctrine\ORM\EntityManagerInterface')->getMock();
  29. $qb = $test->getMockBuilder('Doctrine\ORM\QueryBuilder')->setConstructorArgs(array($entityManager))->getMock();
  30. } else {
  31. $qb = $test->getMockBuilder('Doctrine\ORM\QueryBuilder')->disableOriginalConstructor()->getMock();
  32. }
  33. $qb->expects($test->any())->method('select')->will($test->returnValue($qb));
  34. $qb->expects($test->any())->method('getQuery')->will($test->returnValue($query));
  35. $qb->expects($test->any())->method('where')->will($test->returnValue($qb));
  36. $qb->expects($test->any())->method('orderBy')->will($test->returnValue($qb));
  37. $qb->expects($test->any())->method('andWhere')->will($test->returnValue($qb));
  38. $qb->expects($test->any())->method('leftJoin')->will($test->returnValue($qb));
  39. $qbCallback($qb);
  40. $repository = $test->getMockBuilder('Doctrine\ORM\EntityRepository')->disableOriginalConstructor()->getMock();
  41. $repository->expects($test->any())->method('createQueryBuilder')->will($test->returnValue($qb));
  42. $metadata = $test->getMockBuilder('Doctrine\Common\Persistence\Mapping\ClassMetadata')->getMock();
  43. $metadata->expects($test->any())->method('getFieldNames')->will($test->returnValue($fields));
  44. $metadata->expects($test->any())->method('getName')->will($test->returnValue('className'));
  45. $em = $test->getMockBuilder('Doctrine\ORM\EntityManager')->disableOriginalConstructor()->getMock();
  46. $em->expects($test->any())->method('getRepository')->will($test->returnValue($repository));
  47. $em->expects($test->any())->method('getClassMetadata')->will($test->returnValue($metadata));
  48. return $em;
  49. }
  50. }