Taxonomies.php
1.83 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
<?php
namespace ACA\ACF\Editing\Service;
use ACP\Editing\View;
use InvalidArgumentException;
use LogicException;
class Taxonomies extends Taxonomy {
public function get_view( string $context ): ?View {
$view = parent::get_view( $context );
if ( ! $view instanceof View\AjaxSelect ) {
throw new LogicException( 'Invalid view' );
}
if ( $context === self::CONTEXT_BULK ) {
$view->has_methods( true );
}
return $view->set_multiple( true );
}
public function update( int $id, $data ): void {
$method = $data['method'] ?? null;
if ( null === $method ) {
$this->storage->update( $id, is_array( $data ) ? $this->sanitize_term_ids( $data ) : null );
return;
}
$term_ids = $data['value'] ?? [];
if ( ! is_array( $term_ids ) ) {
throw new InvalidArgumentException( 'Invalid value' );
}
$term_ids = $this->sanitize_term_ids( $term_ids );
switch ( $method ) {
case 'add':
$this->add_term_ids( $id, $term_ids );
break;
case 'remove':
$this->remove_term_ids( $id, $term_ids );
break;
default:
$this->storage->update( $id, $term_ids );
}
}
private function add_term_ids( $id, array $add_term_ids ) {
if ( ! $add_term_ids ) {
return;
}
$this->storage->update( $id, array_merge( $this->get_current_term_ids( $id ), $add_term_ids ) );
}
private function remove_term_ids( $id, array $remove_term_ids ) {
$term_ids = $this->get_current_term_ids( $id );
if ( ! $term_ids || ! $remove_term_ids ) {
return;
}
$this->storage->update( $id, array_unique( array_diff( $term_ids, $remove_term_ids ) ) );
}
protected function sanitize_term_ids( array $term_ids ) {
// Cast term id to `string`
return array_map( 'strval', array_unique( array_filter( $term_ids ) ) );
}
private function get_current_term_ids( $id ): array {
return $this->storage->get( $id ) ?: [];
}
}