1+ <?php
2+
3+ namespace Prokl \WpSymfonyRouterBundle \Services \NativeAjax ;
4+
5+ use ReflectionException ;
6+ use ReflectionMethod ;
7+ use RuntimeException ;
8+ use Symfony \Component \DependencyInjection \ContainerInterface ;
9+ use Symfony \Component \Routing \RouteCollection ;
10+
11+ /**
12+ * Class Prokl\WpSymfonyRouterBundle\Services\NativeAjax
13+ * @package Fedy\Services\Wordpress
14+ *
15+ * @since 12.06.2021
16+ */
17+ class WpAjaxInitializer
18+ {
19+ /**
20+ * @var RouteCollection $routes Роуты.
21+ */
22+ private $ routes ;
23+
24+ /**
25+ * @var ContainerInterface $container Контейнер.
26+ */
27+ private $ container ;
28+
29+ /**
30+ * WpAjaxInitializer constructor.
31+ *
32+ * @param RouteCollection $routes Роуты.
33+ * @param ContainerInterface $container Контейнер.
34+ */
35+ public function __construct (RouteCollection $ routes , ContainerInterface $ container )
36+ {
37+ $ this ->routes = $ routes ;
38+ $ this ->container = $ container ;
39+
40+ $ this ->init ();
41+ }
42+
43+ /**
44+ * Инициализация.
45+ *
46+ * @return void
47+ */
48+ private function init () : void
49+ {
50+ $ routes = $ this ->routes ->all ();
51+ foreach ($ routes as $ action => $ route ) {
52+ $ defaults = $ route ->getDefaults ();
53+ // Публичный роут или нет
54+ $ public = $ defaults ['_public ' ];
55+
56+ $ controller = $ this ->parseController ($ defaults ['_controller ' ]);
57+
58+ add_action ("wp_ajax_ {$ action }" , $ controller );
59+ if ($ public ) {
60+ add_action ("wp_ajax_nopriv_ {$ action }" , $ controller );
61+ }
62+ }
63+ }
64+
65+ /**
66+ * @param array|string|object $controller
67+ *
68+ * @return array|false|object|string|string[]|null
69+ * @throws RuntimeException Когда не получилось распарсить контроллер.
70+ */
71+ private function parseController ($ controller )
72+ {
73+ if (is_string ($ controller )) {
74+ if (strpos ($ controller , ':: ' ) !== false ) {
75+ $ controller = explode (':: ' , $ controller , 2 );
76+ } else {
77+ // Invoked controller.
78+ try {
79+ new ReflectionMethod ($ controller , '__invoke ' );
80+ $ controller = [$ controller , '__invoke ' ];
81+ } catch (ReflectionException $ e ) {
82+ return [];
83+ }
84+ }
85+ }
86+
87+ if (is_array ($ controller )) {
88+ if (is_string ($ controller [0 ]) && !$ this ->container ->has ($ controller [0 ])) {
89+ throw new RuntimeException (
90+ sprintf (
91+ 'Controller %s not found in container. Forgot mark him as service? ' ,
92+ $ controller [0 ]
93+ ),
94+ );
95+ }
96+
97+ $ controller [0 ] = $ this ->container ->get ($ controller [0 ]);
98+
99+ return $ controller ;
100+ }
101+
102+ if (is_object ($ controller )) {
103+ return [$ controller ];
104+ }
105+
106+ throw new RuntimeException (
107+ 'Error parsing controller '
108+ );
109+ }
110+ }
0 commit comments