Create a generic method for generating slugs that are unique to the table.

Ticket #20
This commit is contained in:
Tim Schumacher 2014-09-23 18:54:27 +02:00
parent 33b63429ef
commit e2618b06af

View file

@ -9,7 +9,9 @@
namespace Hackspace\Bundle\CalciferBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Acl\Exception\Exception;
/**
* A baseclass for all other entities
@ -60,4 +62,31 @@ abstract class BaseEntity {
throw new \Exception("Property {$name} does not Exists");
}
}
public function generateSlug($name,EntityManager $em) {
$slug = \URLify::filter($name, 255, 'de');
/** @var EntityRepository $repo */
$repo = $em->getRepository(get_class($this));
$entity = $repo->findOneBy(['slug' => $slug]);
if (is_null($entity)) {
return $slug;
} else {
$counter = 1;
while (true) {
$new_slug = $slug . '-' . $counter;
$entity = $repo->findOneBy(['slug' => $new_slug]);
if (is_null($entity)) {
return $new_slug;
}
if ($counter === 100) {
throw new \Exception('There are 100 events with the same name, pick a fresh one!');
}
$counter++;
}
}
return null;
}
}