66
77namespace Hostnet \Component \EntityMutation \Listener ;
88
9- use Hostnet \Component \EntityMutation \Mutation ;
9+ use Hostnet \Component \EntityMutation \Attributes \ Mutation ;
1010use Hostnet \Component \EntityMutation \MutationAwareInterface ;
1111use Hostnet \Component \EntityMutation \Resolver \MutationResolverInterface ;
1212use Hostnet \Component \EntityTracker \Event \EntityChangedEvent ;
13+ use Psr \Cache \CacheItemInterface ;
14+ use Psr \Cache \CacheItemPoolInterface ;
15+ use Symfony \Component \Cache \Adapter \ArrayAdapter ;
1316
1417class MutationListener
1518{
16- /**
17- * @var MutationResolverInterface
18- */
19- private $ resolver ;
20-
2119 /**
2220 * @param MutationResolverInterface $resolver
2321 */
24- public function __construct (MutationResolverInterface $ resolver )
25- {
26- $ this ->resolver = $ resolver ;
22+ public function __construct (
23+ private MutationResolverInterface $ resolver ,
24+ private CacheItemPoolInterface $ is_mutation_cache = new ArrayAdapter ()
25+ ) {
2726 }
2827
2928 /**
3029 * @param EntityChangedEvent $event
3130 */
32- public function entityChanged (EntityChangedEvent $ event )
31+ public function entityChanged (EntityChangedEvent $ event ): void
3332 {
3433 $ em = $ event ->getEntityManager ();
3534 $ entity = $ event ->getCurrentEntity ();
3635
37- if (null === ( $ annotation = $ this ->resolver -> getMutationAnnotation ($ em , $ entity) )) {
36+ if (false === $ strategy = $ this ->getMutationStrategy ($ em , $ entity )) {
3837 return ;
3938 }
4039
@@ -44,8 +43,6 @@ public function entityChanged(EntityChangedEvent $event)
4443 return ;
4544 }
4645
47- $ strategy = $ annotation ->getStrategy ();
48-
4946 if ($ strategy === Mutation::STRATEGY_COPY_PREVIOUS && null === $ event ->getOriginalEntity ()) {
5047 return ;
5148 }
@@ -72,4 +69,32 @@ public function entityChanged(EntityChangedEvent $event)
7269 $ entity ->addMutation ($ mutation );
7370 }
7471 }
72+
73+ private function getMutationStrategy ($ em , $ entity ): false |string
74+ {
75+ $ cache_key = base64_encode ('MUTATION- ' . get_class ($ entity ));
76+ $ cached_item = $ this ->is_mutation_cache ->getItem ($ cache_key );
77+
78+ if ($ cached_item ->isHit ()) {
79+ return $ cached_item ->get ();
80+ }
81+
82+ if (null !== $ attribute = $ this ->resolver ->getMutationAttribute ($ em , $ entity )) {
83+ return $ this ->save ($ cached_item , $ attribute ->getStrategy ());
84+ }
85+
86+ if (null !== $ annotation = $ this ->resolver ->getMutationAnnotation ($ em , $ entity )) {
87+ return $ this ->save ($ cached_item , $ annotation ->getStrategy ());
88+ }
89+
90+ return $ this ->save ($ cached_item , false );
91+ }
92+
93+ private function save (CacheItemInterface $ item , false |string $ value ): false |string
94+ {
95+ $ item ->set ($ value );
96+ $ this ->is_mutation_cache ->save ($ item );
97+
98+ return $ value ;
99+ }
75100}
0 commit comments