Create a generic method for generating slugs that are unique to the table.
Ticket #20
This commit is contained in:
parent
33b63429ef
commit
e2618b06af
1 changed files with 30 additions and 1 deletions
|
@ -9,7 +9,9 @@
|
||||||
namespace Hackspace\Bundle\CalciferBundle\Entity;
|
namespace Hackspace\Bundle\CalciferBundle\Entity;
|
||||||
|
|
||||||
use Doctrine\ORM\Mapping as ORM;
|
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
|
* A baseclass for all other entities
|
||||||
|
@ -60,4 +62,31 @@ abstract class BaseEntity {
|
||||||
throw new \Exception("Property {$name} does not Exists");
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
Reference in a new issue