TreeSlugHandler.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. <?php
  2. namespace Gedmo\Sluggable\Handler;
  3. use Doctrine\Common\Persistence\ObjectManager;
  4. use Doctrine\Common\Persistence\Mapping\ClassMetadata;
  5. use Gedmo\Sluggable\SluggableListener;
  6. use Gedmo\Sluggable\Mapping\Event\SluggableAdapter;
  7. use Gedmo\Tool\Wrapper\AbstractWrapper;
  8. use Gedmo\Exception\InvalidMappingException;
  9. /**
  10. * Sluggable handler which slugs all parent nodes
  11. * recursively and synchronizes on updates. For instance
  12. * category tree slug could look like "food/fruits/apples"
  13. *
  14. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  15. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  16. */
  17. class TreeSlugHandler implements SlugHandlerWithUniqueCallbackInterface
  18. {
  19. const SEPARATOR = '/';
  20. /**
  21. * @var ObjectManager
  22. */
  23. protected $om;
  24. /**
  25. * @var SluggableListener
  26. */
  27. protected $sluggable;
  28. /**
  29. * @var string
  30. */
  31. private $prefix;
  32. /**
  33. * @var string
  34. */
  35. private $suffix;
  36. /**
  37. * True if node is being inserted
  38. *
  39. * @var boolean
  40. */
  41. private $isInsert = false;
  42. /**
  43. * Transliterated parent slug
  44. *
  45. * @var string
  46. */
  47. private $parentSlug;
  48. /**
  49. * Used path separator
  50. *
  51. * @var string
  52. */
  53. private $usedPathSeparator;
  54. /**
  55. * {@inheritDoc}
  56. */
  57. public function __construct(SluggableListener $sluggable)
  58. {
  59. $this->sluggable = $sluggable;
  60. }
  61. /**
  62. * {@inheritDoc}
  63. */
  64. public function onChangeDecision(SluggableAdapter $ea, array &$config, $object, &$slug, &$needToChangeSlug)
  65. {
  66. $this->om = $ea->getObjectManager();
  67. $this->isInsert = $this->om->getUnitOfWork()->isScheduledForInsert($object);
  68. $options = $config['handlers'][get_called_class()];
  69. $this->usedPathSeparator = isset($options['separator']) ? $options['separator'] : self::SEPARATOR;
  70. $this->prefix = isset($options['prefix']) ? $options['prefix'] : '';
  71. $this->suffix = isset($options['suffix']) ? $options['suffix'] : '';
  72. if (!$this->isInsert && !$needToChangeSlug) {
  73. $changeSet = $ea->getObjectChangeSet($this->om->getUnitOfWork(), $object);
  74. if (isset($changeSet[$options['parentRelationField']])) {
  75. $needToChangeSlug = true;
  76. }
  77. }
  78. }
  79. /**
  80. * {@inheritDoc}
  81. */
  82. public function postSlugBuild(SluggableAdapter $ea, array &$config, $object, &$slug)
  83. {
  84. $options = $config['handlers'][get_called_class()];
  85. $this->parentSlug = '';
  86. $wrapped = AbstractWrapper::wrap($object, $this->om);
  87. if ($parent = $wrapped->getPropertyValue($options['parentRelationField'])) {
  88. $parent = AbstractWrapper::wrap($parent, $this->om);
  89. $this->parentSlug = $parent->getPropertyValue($config['slug']);
  90. // if needed, remove suffix from parentSlug, so we can use it to prepend it to our slug
  91. if (isset($options['suffix'])) {
  92. $suffix = $options['suffix'];
  93. if (substr($this->parentSlug, -strlen($suffix)) === $suffix) { //endsWith
  94. $this->parentSlug = substr_replace($this->parentSlug, '', -1 * strlen($suffix));
  95. }
  96. }
  97. }
  98. }
  99. /**
  100. * {@inheritDoc}
  101. */
  102. public static function validate(array $options, ClassMetadata $meta)
  103. {
  104. if (!$meta->isSingleValuedAssociation($options['parentRelationField'])) {
  105. throw new InvalidMappingException("Unable to find tree parent slug relation through field - [{$options['parentRelationField']}] in class - {$meta->name}");
  106. }
  107. }
  108. /**
  109. * {@inheritDoc}
  110. */
  111. public function beforeMakingUnique(SluggableAdapter $ea, array &$config, $object, &$slug)
  112. {
  113. $slug = $this->transliterate($slug, $config['separator'], $object);
  114. }
  115. /**
  116. * {@inheritDoc}
  117. */
  118. public function onSlugCompletion(SluggableAdapter $ea, array &$config, $object, &$slug)
  119. {
  120. if (!$this->isInsert) {
  121. $wrapped = AbstractWrapper::wrap($object, $this->om);
  122. $meta = $wrapped->getMetadata();
  123. $target = $wrapped->getPropertyValue($config['slug']);
  124. $config['pathSeparator'] = $this->usedPathSeparator;
  125. $ea->replaceRelative($object, $config, $target.$config['pathSeparator'], $slug);
  126. $uow = $this->om->getUnitOfWork();
  127. // update in memory objects
  128. foreach ($uow->getIdentityMap() as $className => $objects) {
  129. // for inheritance mapped classes, only root is always in the identity map
  130. if ($className !== $wrapped->getRootObjectName()) {
  131. continue;
  132. }
  133. foreach ($objects as $object) {
  134. if (property_exists($object, '__isInitialized__') && !$object->__isInitialized__) {
  135. continue;
  136. }
  137. $oid = spl_object_hash($object);
  138. $objectSlug = $meta->getReflectionProperty($config['slug'])->getValue($object);
  139. if (preg_match("@^{$target}{$config['pathSeparator']}@smi", $objectSlug)) {
  140. $objectSlug = str_replace($target, $slug, $objectSlug);
  141. $meta->getReflectionProperty($config['slug'])->setValue($object, $objectSlug);
  142. $ea->setOriginalObjectProperty($uow, $oid, $config['slug'], $objectSlug);
  143. }
  144. }
  145. }
  146. }
  147. }
  148. /**
  149. * Transliterates the slug and prefixes the slug
  150. * by collection of parent slugs
  151. *
  152. * @param string $text
  153. * @param string $separator
  154. * @param object $object
  155. *
  156. * @return string
  157. */
  158. public function transliterate($text, $separator, $object)
  159. {
  160. $slug = $text . $this->suffix;
  161. if (strlen($this->parentSlug)) {
  162. $slug = $this->parentSlug.$this->usedPathSeparator.$slug;
  163. } else {
  164. // if no parentSlug, apply our prefix
  165. $slug = $this->prefix.$slug;
  166. }
  167. return $slug;
  168. }
  169. /**
  170. * {@inheritDoc}
  171. */
  172. public function handlesUrlization()
  173. {
  174. return false;
  175. }
  176. }