class-attachment-id-list.php
2.38 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
113
114
<?php
namespace Smush\Core;
use Smush\Core\Modules\Background\Mutex;
class Attachment_Id_List {
private $option_id;
private $ids;
/**
* @var Array_Utils
*/
private $array_utils;
public function __construct( $option_id ) {
$this->option_id = $option_id;
$this->array_utils = new Array_Utils();
}
private function set_ids( $ids ) {
$this->ids = $ids;
}
public function get_ids() {
if ( is_null( $this->ids ) ) {
$this->ids = $this->fetch_ids();
}
return $this->ids;
}
private function fetch_ids() {
wp_cache_delete( $this->option_id, 'options' );
return $this->string_to_array( (string) get_option( $this->option_id ) );
}
public function has_id( $id ) {
return in_array( $id, $this->get_ids() );
}
public function add_id( $attachment_id ) {
$this->mutex( function () use ( $attachment_id ) {
$ids = $this->fetch_ids();
if ( ! in_array( $attachment_id, $ids ) ) {
$ids[] = $attachment_id;
}
$this->_update_ids( $ids );
} );
}
public function add_ids( $attachment_ids ) {
$this->mutex( function () use ( $attachment_ids ) {
$new_ids = array_merge( $this->fetch_ids(), $attachment_ids );
$new_ids = $this->array_utils->fast_array_unique( $new_ids );
$this->_update_ids( $new_ids );
} );
}
public function remove_id( $attachment_id ) {
$this->mutex( function () use ( $attachment_id ) {
$ids = $this->fetch_ids();
$index = array_search( $attachment_id, $ids );
if ( $index !== false ) {
unset( $ids[ $index ] );
}
$this->_update_ids( $ids );
} );
}
public function update_ids( $ids ) {
$this->mutex( function () use ( $ids ) {
$this->_update_ids( $ids );
} );
}
public function delete_ids() {
delete_option( $this->option_id );
$this->set_ids( array() );
}
private function string_to_array( $string ) {
return empty( $string )
? array()
: explode( ',', $string );
}
private function array_to_string( $array ) {
$array = empty( $array ) || ! is_array( $array )
? array()
: $array;
return join( ',', $array );
}
private function mutex( $operation ) {
$option_id = $this->option_id;
( new Mutex( "{$option_id}_mutex" ) )->execute( $operation );
}
private function _update_ids( $ids ) {
update_option(
$this->option_id,
$this->array_to_string( $ids ),
false
);
$this->set_ids( $ids );
}
public function get_count() {
return count( $this->get_ids() );
}
}