-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOption.php
More file actions
83 lines (71 loc) · 2.07 KB
/
Copy pathOption.php
File metadata and controls
83 lines (71 loc) · 2.07 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
/**
* Option class file
*
* @package mantle-framework
*/
namespace Mantle\Support;
use ArrayAccess;
use InvalidArgumentException;
use Mantle\Contracts\Support\Jsonable;
/**
* Fluent class for retrieving options as type-safe objects.
*
* When retrieving options from the database, get_option() has a return value of
* mixed. This class allows you to retrieve options with a specific type.
*/
class Option implements ArrayAccess, Jsonable, \JsonSerializable, \Stringable {
use Interacts_With_Data;
/**
* Retrieve an option from the database.
*
* @param string $option Option name.
* @param mixed $default Default value. Default is null.
*/
public static function of( string $option, mixed $default = null ): static {
return new static( $option, get_option( $option, $default ) );
}
/**
* Create a new instance of the class.
*
* @param mixed $value Value.
*/
public static function create( mixed $value ): static {
return new static( null, $value );
}
/**
* Constructor
*
* @param string|null $option Option name.
* @param mixed $value Option value.
* @param bool $throw Whether to throw an exception if the option is not a compatible type.
*/
public function __construct( protected readonly ?string $option, mixed $value, bool $throw = false ) {
$this->value = $value;
$this->throw = $throw;
}
/**
* Save the option.
*
* @throws InvalidArgumentException If the option is a sub-property of an option and the option name is not passed.
*/
public function save(): static {
if ( ! $this->option ) {
throw new InvalidArgumentException( 'Unable to save sub-property of an option.' );
}
update_option( $this->option, $this->value );
$this->value = get_option( $this->option );
return $this;
}
/**
* Delete the option.
*
* @throws InvalidArgumentException If the option is a sub-property of an option.
*/
public function delete(): void {
if ( ! $this->option ) {
throw new InvalidArgumentException( 'Unable to delete option on a sub-property of an option.' );
}
delete_option( $this->option );
}
}