ComputedNumber.php
1.67 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
<?php
namespace ACP\Editing\Service;
use ACP;
use ACP\Editing;
use ACP\Editing\Storage;
use ACP\Editing\View;
use RuntimeException;
class ComputedNumber implements Editing\Service {
const ARG_COMPUTATION_TYPE = 'computation_type';
const ARG_ALLOW_NEGATIVE = 'allow_negative';
protected $storage;
public function __construct( Storage $storage ) {
$this->storage = $storage;
}
public function get_value( int $id ) {
return $this->storage->get( $id );
}
public function get_view( string $context ): ?View {
return $context === Editing\Service::CONTEXT_BULK
? new View\ComputedNumber()
: new View\Number();
}
private function compute( float $current_value, float $compute_value, string $computation = null ) {
switch ( $computation ) {
case 'add':
return $current_value + $compute_value;
case 'subtract':
return $current_value - $compute_value;
case 'multiply':
return $current_value * $compute_value;
case 'divide':
if ( 0 == $compute_value ) {
throw new RuntimeException( __( 'Cannot divide by zero', 'codepress-admin-columns' ) );
}
return $current_value / $compute_value;
case 'replace':
default:
return $compute_value;
}
}
public function update( int $id, $data ): void {
$computation = $data[ self::ARG_COMPUTATION_TYPE ] ?? null;
if ( null === $computation ) {
$this->storage->update( $id, $data ?: null );
return;
}
$value = $this->compute(
(float) $this->get_value( $id ),
(float) $data['value'],
$computation
);
$allow_negative = $data[ self::ARG_ALLOW_NEGATIVE ] ?? null;
if ( ! $allow_negative && $value < 0 ) {
$value = 0;
}
$this->storage->update( $id, $value );
}
}