ProductRelations.php
2.02 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
<?php
declare( strict_types=1 );
namespace ACA\WC\Editing;
use ACA\WC\Helper\Select;
use ACP;
use ACP\Editing\PaginatedOptions;
use ACP\Editing\Service;
use ACP\Editing\Storage;
use ACP\Editing\View;
use InvalidArgumentException;
abstract class ProductRelations implements Service, PaginatedOptions {
use PostTrait;
/**
* @var Storage
*/
private $storage;
public function __construct( Storage $storage ) {
$this->storage = $storage;
}
public function get_value( int $id ) {
return $this->get_editable_posts_values( $this->get_relation_ids( $id ) );
}
private function get_relation_ids( $id ) {
$ids = $this->storage->get( $id );
return $ids && is_array( $ids )
? $ids
: [];
}
/**
* @param array $ids
*
* @return int[]
*/
private function sanitize_ids( $ids ): array {
return $ids
? array_map( 'intval', array_filter( $ids, 'is_numeric' ) )
: [];
}
public function update( int $id, $data ): void {
$method = $data['method'] ?? null;
if ( ! $method ) {
$this->storage->update( $id, $this->sanitize_ids( $data ) );
return;
}
$relation_ids = $data['value'] ?? [];
if ( ! is_array( $relation_ids ) ) {
throw new InvalidArgumentException( 'Invalid value' );
}
$relation_ids = $this->sanitize_ids( $relation_ids );
switch ( $method ) {
case 'add':
$this->storage->update( $id, array_merge( $this->get_relation_ids( $id ), $relation_ids ) );
break;
case 'remove':
$this->storage->update( $id, array_diff( $this->get_relation_ids( $id ), $relation_ids ) );
break;
default:
$this->storage->update( $id, $relation_ids );
}
}
public function get_view( string $context ): ?View {
$view = ( new ACP\Editing\View\AjaxSelect() )
->set_multiple( true )
->set_clear_button( true );
if ( $context === self::CONTEXT_BULK ) {
$view->has_methods( true )->set_revisioning( false );
}
return $view;
}
public function get_paginated_options( $s, $paged, $id = null ) {
return new Select\Paginated\Products( (string) $s, (int) $paged );
}
}