Posts.php
2.5 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace ACP\Editing\Service;
use ACP;
use ACP\Editing\PaginatedOptions;
use ACP\Editing\PaginatedOptionsFactory;
use ACP\Editing\Service;
use ACP\Editing\Storage;
use ACP\Editing\View;
use InvalidArgumentException;
class Posts implements Service, PaginatedOptions {
/**
* @var View\AjaxSelect
*/
protected $view;
/**
* @var Storage
*/
protected $storage;
/**
* @var PaginatedOptionsFactory
*/
protected $options_factory;
public function __construct( View\AjaxSelect $view, Storage $storage, PaginatedOptionsFactory $options_factory = null ) {
$this->view = $view;
$this->storage = $storage;
$this->options_factory = $options_factory ?: new PaginatedOptions\Posts();
}
public function get_view( string $context ): ?View {
$view = $this->view->set_multiple( true );
if ( $context === self::CONTEXT_BULK ) {
$view->has_methods( true )->set_revisioning( false );
}
return $view;
}
private function get_post_title( int $id ) {
return get_the_title( $id ) ?: sprintf( __( '#%d (no title)' ), $id );
}
public function get_value( int $id ) {
$ids = $this->get_current_post_ids( $id );
return $ids
? array_map( [ $this, 'get_post_title' ], array_combine( $ids, $ids ) )
: [];
}
/**
* @param int $id
*
* @return int[]
*/
private function get_current_post_ids( int $id ) {
$ids = $this->storage->get( $id );
return $ids && is_array( $ids )
? array_map( 'intval', array_filter( $ids, 'is_numeric' ) )
: [];
}
public function update( int $id, $data ): void {
$method = $data['method'] ?? null;
if ( null === $method ) {
$this->storage->update( $id, $data && is_array( $data ) ? $this->sanitize_ids( $data ) : null );
return;
}
$ids = $data['value'] ?? [];
if ( ! is_array( $ids ) ) {
throw new InvalidArgumentException( 'Invalid value' );
}
$ids = $this->sanitize_ids( $ids );
switch ( $method ) {
case 'add':
if ( $ids ) {
$this->storage->update( $id, array_merge( $this->get_current_post_ids( $id ), $ids ) ?: null );
}
break;
case 'remove':
if ( $ids ) {
$this->storage->update( $id, array_diff( $this->get_current_post_ids( $id ), $ids ) ?: null );
}
break;
default:
$this->storage->update( $id, $ids ?: null );
}
}
protected function sanitize_ids( array $ids ): array {
return array_map( 'intval', array_unique( array_filter( $ids ) ) );
}
public function get_paginated_options( $search, $page, $id = null ) {
return $this->options_factory->create( $search, $page, $id );
}
}