run.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. use Doctrine\ORM\Query;
  3. use Gedmo\Translatable\TranslatableListener;
  4. $executionStart = microtime(true);
  5. $memoryStart = memory_get_usage(true);
  6. $em = include 'em.php';
  7. /**
  8. * initialized in em.php
  9. *
  10. * Gedmo\Translatable\TranslationListener
  11. */
  12. $translatable;
  13. $repository = $em->getRepository('Entity\Category');
  14. $food = $repository->findOneByTitle('Food');
  15. if (!$food) {
  16. // lets create some categories
  17. $food = new Entity\Category;
  18. $food->setTitle('Food');
  19. $food->addTranslation(new Entity\CategoryTranslation('lt', 'title', 'Maistas'));
  20. $fruits = new Entity\Category;
  21. $fruits->setParent($food);
  22. $fruits->setTitle('Fruits');
  23. $fruits->addTranslation(new Entity\CategoryTranslation('lt', 'title', 'Vaisiai'));
  24. $apple = new Entity\Category;
  25. $apple->setParent($fruits);
  26. $apple->setTitle('Apple');
  27. $apple->addTranslation(new Entity\CategoryTranslation('lt', 'title', 'Obuolys'));
  28. $milk = new Entity\Category;
  29. $milk->setParent($food);
  30. $milk->setTitle('Milk');
  31. $milk->addTranslation(new Entity\CategoryTranslation('lt', 'title', 'Pienas'));
  32. $em->persist($food);
  33. $em->persist($milk);
  34. $em->persist($fruits);
  35. $em->persist($apple);
  36. $em->flush();
  37. }
  38. // create query to fetch tree nodes
  39. $query = $em
  40. ->createQueryBuilder()
  41. ->select('node')
  42. ->from('Entity\Category', 'node')
  43. ->orderBy('node.root, node.lft', 'ASC')
  44. ->getQuery()
  45. ;
  46. // set hint to translate nodes
  47. $query->setHint(
  48. Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
  49. 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
  50. );
  51. $treeDecorationOptions = array(
  52. 'decorate' => true,
  53. 'rootOpen' => '',
  54. 'rootClose' => '',
  55. 'childOpen' => '',
  56. 'childClose' => '',
  57. 'nodeDecorator' => function($node) {
  58. return str_repeat('-', $node['level']).$node['title'].PHP_EOL;
  59. }
  60. );
  61. // build tree in english
  62. echo $repository->buildTree($query->getArrayResult(), $treeDecorationOptions).PHP_EOL.PHP_EOL;
  63. // change locale
  64. $query->setHint(TranslatableListener::HINT_TRANSLATABLE_LOCALE, 'lt');
  65. // build tree in lithuanian
  66. echo $repository->buildTree($query->getArrayResult(), $treeDecorationOptions).PHP_EOL.PHP_EOL;
  67. $ms = round(microtime(true) - $executionStart, 4) * 1000;
  68. $mem = round((memory_get_usage(true) - $memoryStart) / 1000000, 2);
  69. echo "Execution took: {$ms} ms, memory consumed: {$mem} Mb";