Skip to content

Commit 6d1e896

Browse files
committed
Доработка.
1 parent 0b7c21c commit 6d1e896

File tree

5 files changed

+94
-6
lines changed

5 files changed

+94
-6
lines changed

Services/NativeAjax/AbstractWPAjaxController.php

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
66
use Symfony\Component\HttpFoundation\Request;
7+
use Symfony\Component\HttpFoundation\Response;
78

89
/**
910
* Class AbstractWPAjaxController
@@ -23,9 +24,44 @@ class AbstractWPAjaxController extends AbstractController
2324
*/
2425
public function __construct(?Request $request = null)
2526
{
26-
$this->request = $request;
2727
if ($request === null) {
2828
$this->request = Request::createFromGlobals();
2929
}
30+
31+
$action = (string)$this->request->query->get('action');
32+
$routeData = WpAjaxInitializer::route($action);
33+
34+
$this->request->attributes->set('methods', $routeData->getMethods());
35+
$this->request->attributes->set('requirements', $routeData->getRequirements());
36+
$this->request->attributes->set('defaults', $routeData->getDefaults());
37+
$this->request->attributes->set('options', $routeData->getOptions());
38+
}
39+
40+
/**
41+
* Валидный тип запроса?
42+
*
43+
* @param string $message Сообщение.
44+
* @param integer $statusCode HTTP status code.
45+
*
46+
* @return void
47+
*/
48+
protected function checkTypeRequest(string $message = '', int $statusCode = 400) : void
49+
{
50+
$methods = $this->request->attributes->get('methods');
51+
if (!$methods) {
52+
return;
53+
}
54+
55+
$requestMethod = $this->request->getMethod();
56+
if (!in_array($requestMethod, $methods, false)) {
57+
$response = new Response(
58+
$message,
59+
$statusCode
60+
);
61+
62+
$response->send();
63+
64+
wp_die();
65+
}
3066
}
31-
}
67+
}

Services/Router/InitRouter.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ public function __construct(
141141

142142
$this->dispatcher = $eventDispatcher;
143143
$this->routeListener = new RouterListener(
144-
$matcher, $this->requestStack
144+
$matcher,
145+
$this->requestStack
145146
);
146147

147148
$this->errorListener = new ErrorListener(

Tests/Cases/SampleAjaxControllerTest.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class SampleAjaxControllerTest extends WordpressableAjaxTestCase
1717
protected function setUp() : void
1818
{
1919
parent::setup();
20-
wp_set_current_user( 1 );
20+
wp_set_current_user(1);
2121

2222
$this->container = static::$testContainer = BuildContainer::getTestContainer(
2323
[
@@ -26,9 +26,21 @@ protected function setUp() : void
2626
'/../../../../Tests/Fixture'
2727
);
2828

29+
$_GET['action'] = 'examples_wp';
30+
2931
$this->container->get('wp_ajax.initializer');
3032
}
3133

34+
/**
35+
* @inheritDoc
36+
*/
37+
protected function tearDown(): void
38+
{
39+
parent::tearDown();
40+
41+
$_GET['action'] = null;
42+
}
43+
3244
/**
3345
* @return void
3446
*/

Tests/Fixture/Controller/SampleAjaxController.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,29 @@
33
namespace Prokl\WpSymfonyRouterBundle\Tests\Fixture\Controller;
44

55
use Prokl\WpSymfonyRouterBundle\Services\NativeAjax\AbstractWPAjaxController;
6+
use Symfony\Component\HttpFoundation\Response;
67

78
/**
89
* Class SampleAjaxController
910
* @package Prokl\WpSymfonyRouterBundle\Tests\Fixture\Controller
1011
*/
1112
class SampleAjaxController extends AbstractWPAjaxController
1213
{
13-
public function action()
14+
/**
15+
* @return void
16+
*/
17+
public function action() : void
1418
{
15-
echo 'OK';
19+
$this->checkTypeRequest('Invalid type request');
20+
21+
$response = new Response(
22+
'OK',
23+
Response::HTTP_OK
24+
);
25+
26+
$response->headers->set('Content-Type', 'application/html; charset=utf-8');
27+
$response->send();
28+
1629
wp_die();
1730
}
1831
}

readme.MD

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,29 @@ examples_wp: # Action роута
4040
Он представляет собой наследника от `AbstractController` с добавлением конструктора, принимающего одну зависимость -
4141
объект класса `Request`. Приходится так действовать, потому что в ajax обработчик Wordpress никак нелльзя передать
4242
параметры снаружи (за исключением супер-глобалов типа `$_POST` и `$_GET`).
43+
44+
Дополнительно в Request контроллера пробрасываются всякие параметры из свойств роута. Например `methods`.
45+
46+
Это делает возможным, например, отсекать неправильные типа запроса в `action` обработчика.
47+
48+
```php
49+
class SampleAjaxController extends AbstractWPAjaxController
50+
{
51+
public function action()
52+
{
53+
$this->checkTypeRequest('Invalid type request');
54+
55+
$response = new Response(
56+
'OK',
57+
Response::HTTP_OK
58+
);
59+
60+
$response->headers->set('Content-Type', 'application/html; charset=utf-8');
61+
$response->send();
62+
63+
wp_die();
64+
}
65+
}
66+
```
67+
68+
Или писать каку-нибудь логику для операций с `defaults`, `requirements` или `options` из параметров роута.

0 commit comments

Comments
 (0)