1+ <?php
2+
3+ namespace Vivait \StringGeneratorBundle \EventListener ;
4+
5+ use Doctrine \Common \Annotations \Reader ;
6+ use Doctrine \ORM \Event \LifecycleEventArgs ;
7+ use Vivait \StringGeneratorBundle \Annotation as Vivait ;
8+
9+ class IdGeneratorListener
10+ {
11+ private $ reader ;
12+ private $ repo ;
13+
14+ public function __construct (Reader $ reader )
15+ {
16+ $ this ->reader = $ reader ;
17+ }
18+
19+ /**
20+ * @param LifecycleEventArgs $args
21+ */
22+ public function prePersist (LifecycleEventArgs $ args )
23+ {
24+ $ entity = $ args ->getEntity ();
25+ $ em = $ args ->getEntityManager ();
26+ $ meta = $ em ->getClassMetadata (get_class ($ entity ));
27+ $ this ->repo = $ em ->getRepository ($ meta ->getName ());
28+
29+ $ obj = new \ReflectionObject ($ entity );
30+
31+ //Loop through each of entity's properties
32+ foreach ($ obj ->getProperties () as $ property ) {
33+ //Loop through the property's annotations
34+ foreach ($ this ->reader ->getPropertyAnnotations ($ property ) as $ annotation ) {
35+
36+ if ($ annotation instanceof Vivait \StringGenerator) {
37+ if (method_exists ($ entity , $ annotation ->prefix_callback ) && is_callable ([$ entity , $ annotation ->prefix_callback ])) {
38+ $ callback = $ annotation ->prefix_callback ;
39+ $ annotation ->prefix = $ entity ->$ callback ();
40+ }
41+
42+ $ id = $ this ->generateId (
43+ $ property ->name ,
44+ $ annotation
45+ );
46+ $ meta ->getReflectionProperty ($ property ->name )->setValue ($ entity , $ id );
47+ }
48+ }
49+ }
50+ }
51+
52+ /**
53+ * @param $property
54+ * @param $annotation
55+ * @return string
56+ */
57+ private function generateId ($ property , Vivait \StringGenerator $ annotation )
58+ {
59+ $ id = $ this ->createId ($ annotation ->alphabet , $ annotation ->length );
60+
61+ if ($ annotation ->prefix ) {
62+ $ id = sprintf ("%s%s%s " , $ annotation ->prefix , $ annotation ->separator , $ id );
63+ }
64+
65+ if ($ this ->repo ->findOneBy ([$ property => $ id ])) {
66+ $ this ->generateId ($ property , $ annotation );
67+ } else {
68+ return $ id ;
69+ }
70+ }
71+
72+ /**
73+ * @param $alphabet
74+ * @param $length
75+ * @return string
76+ */
77+ private function createId ($ alphabet , $ length )
78+ {
79+ $ id = [];
80+ $ alphaLength = strlen ($ alphabet ) - 1 ;
81+ for ($ i = 0 ; $ i < $ length ; $ i ++) {
82+ $ n = rand (0 , $ alphaLength );
83+ $ id [] = $ alphabet [$ n ];
84+ }
85+
86+ return implode ($ id );
87+ }
88+ }
0 commit comments