run.php 2.3 KB

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