class-media-item-optimization-global-stats-persistable.php
2.53 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
<?php
namespace Smush\Core\Stats;
use Smush\Core\Media\Media_Item_Optimization_Global_Stats;
use Smush\Core\Modules\Background\Mutex;
class Media_Item_Optimization_Global_Stats_Persistable {
/**
* @var Media_Item_Optimization_Global_Stats
*/
private $stats;
private $option_id;
public function __construct( $option_id, $stats = null ) {
$this->option_id = $option_id;
$this->stats = is_a( $stats, '\Smush\Core\Media\Media_Item_Optimization_Global_Stats' )
? $stats
: new Media_Item_Optimization_Global_Stats();
$this->fetch_from_option( $option_id );
}
public function save() {
update_option( $this->option_id, $this->stats->to_array(), false );
}
public function has_attachment_id( $attachment_id ) {
return $this->stats->has_attachment_id( $attachment_id );
}
public function add_item_stats( $attachment_id, $addend ) {
$this->mutex( function () use ( $attachment_id, $addend ) {
$this->fetch_from_option( $this->option_id );
$this->stats->add_item_stats( $attachment_id, $addend );
$this->save();
} );
}
public function subtract_item_stats( $attachment_id, $subtrahend ) {
$this->mutex( function () use ( $attachment_id, $subtrahend ) {
$this->fetch_from_option( $this->option_id );
$this->stats->subtract_item_stats( $attachment_id, $subtrahend );
$this->save();
} );
}
public function add( $addend ) {
$this->mutex( function () use ( $addend ) {
$this->fetch_from_option( $this->option_id );
$this->stats->add( $addend );
$this->save();
} );
}
public function subtract( $subtrahend ) {
$this->mutex( function () use ( $subtrahend ) {
$this->fetch_from_option( $this->option_id );
$this->stats->subtract( $subtrahend );
$this->save();
} );
}
public function reset() {
$this->initialize();
}
public function initialize() {
$this->mutex( function () {
$this->stats->from_array( array() );
$this->save();
} );
}
/**
* @param $option_id
*
* @return void
*/
protected function fetch_from_option( $option_id ) {
// Two threads may access this at the same time, so cached values can cause reader-writer problem
wp_cache_delete( $this->option_id, 'options' );
$this->stats->from_array( get_option( $option_id, array() ) );
}
protected function mutex( $operation ) {
( new Mutex( $this->mutex_key() ) )->execute( $operation );
}
private function mutex_key() {
return 'update_global_stats_mutex_' . $this->option_id;
}
public function get_option_id() {
return $this->option_id;
}
public function get_stats() {
return $this->stats;
}
}