Skip to content

Commit

Permalink
[Alias] Auto set alias when a node is created without.
Browse files Browse the repository at this point in the history
  • Loading branch information
NoUseFreak committed Apr 5, 2015
1 parent 10e999e commit 2bc720e
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Clastic/AliasBundle/EventListener/NodeListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Doctrine\ORM\Events;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\Proxy\ValueHolderInterface;
use Symfony\Component\Validator\Validator\RecursiveValidator;

/**
* NodeListener
Expand All @@ -34,6 +35,7 @@ class NodeListener implements EventSubscriber
public function getSubscribedEvents()
{
return array(
Events::prePersist,
Events::postLoad,
Events::postPersist,
Events::postRemove,
Expand Down Expand Up @@ -135,4 +137,40 @@ public function postRemove(LifecycleEventArgs $args)
->flush();
}
}

/**
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getObject();

if ($entity instanceof NodeReferenceInterface) {
$alias = $entity->getNode()->alias;
if (!$alias->getAlias()) {
$alias->setAlias($entity->getNode()->getTitle());

$i = 1;
while ($this->validateUnique($alias, $args)) {
$alias->setAlias($entity->getNode()->getTitle() . '_' . $i);
$i++;
}
}
}
}

/**
* @param Alias $alias
* @param LifecycleEventArgs $args
*
* @return bool
*/
private function validateUnique(Alias $alias, LifecycleEventArgs $args)
{
return (bool) $args->getObjectManager()
->getRepository('ClasticAliasBundle:Alias')
->findBy(array(
'alias' => $alias->getAlias(),
));
}
}

0 comments on commit 2bc720e

Please sign in to comment.