AjaxNewItem.php
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);
namespace ACP\QuickAdd\Controller;
use AC\ListScreen;
use AC\ListScreenRepository\Storage;
use AC\Registerable;
use AC\Request;
use AC\Type\ListScreenId;
use ACP\QuickAdd\Model;
use RuntimeException;
class AjaxNewItem implements Registerable
{
private $storage;
protected $request;
public function __construct(Storage $storage, Request $request)
{
$this->storage = $storage;
$this->request = $request;
}
public function register(): void
{
if ($this->is_request()) {
add_action('ac/table/list_screen', [$this, 'register_hooks']);
}
}
public function register_hooks(ListScreen $list_screen)
{
switch (true) {
case $list_screen instanceof ListScreen\Post:
add_action('edit_posts_per_page', [$this, 'handle_request']);
break;
}
}
private function is_request(): bool
{
return $this->request->get('ac_action') === 'acp_add_new_inline';
}
public function handle_request(): void
{
if ( ! wp_verify_nonce($this->request->get('_ajax_nonce'), 'ac-ajax')) {
return;
}
$response = new JsonResponse();
$list_screen = $this->storage->find(new ListScreenId($this->request->get('layout')));
if ( ! $list_screen || ! $list_screen->is_user_allowed(wp_get_current_user())) {
$response->error();
}
$model = Model\Factory::create($list_screen);
if ( ! $model || ! $model->has_permission(wp_get_current_user())) {
$response->error();
}
try {
$id = $model->create();
} catch (RuntimeException $e) {
$response->set_message($e->getMessage())
->error();
}
do_action('acp/quick_add/saved', $id, $list_screen);
$response->create_from_list_screen($list_screen, $id)
->success();
}
}