APC::set()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2026
6
 * @package Base
7
 * @subpackage Config
8
 */
9
10
11
namespace Aimeos\Base\Config\Decorator;
12
13
14
/**
15
 * APC caching decorator for config classes.
16
 *
17
 * @package Base
18
 * @subpackage Config
19
 */
20
class APC
21
	extends \Aimeos\Base\Config\Decorator\Base
22
	implements \Aimeos\Base\Config\Decorator\Iface
23
{
24
	private bool $enable;
25
	private string $prefix;
26
27
28
	/**
29
	 * Initializes the decorator.
30
	 *
31
	 * @param \Aimeos\Base\Config\Iface $object Config object or decorator
32
	 * @param string $prefix Prefix for keys to distinguish several instances
33
	 */
34
	public function __construct( \Aimeos\Base\Config\Iface $object, string $prefix = '' )
35
	{
36
		parent::__construct( $object );
37
38
		$this->enable = function_exists( 'apcu_store' );
39
		$this->prefix = $prefix;
40
	}
41
42
43
	/**
44
	 * Returns the value of the requested config key.
45
	 *
46
	 * @param string $path Path to the requested value like tree/node/classname
47
	 * @param mixed $default Value returned if requested key isn't found
48
	 * @return mixed Value associated to the requested key
49
	 */
50
	public function get( string $path, $default = null )
51
	{
52
		if( !$this->enable ) {
53
			return $this->object()->get( $path, $default );
54
		}
55
56
		$path = trim( $path, '/' );
57
58
		// negative cache
59
		$success = false;
60
		apcu_fetch( '-' . $this->prefix . $path, $success );
61
62
		if( $success === true ) {
63
			return $default;
64
		}
65
66
		// regular cache
67
		$success = false;
68
		$value = apcu_fetch( $this->prefix . $path, $success );
69
70
		if( $success === true ) {
71
			return $value;
72
		}
73
74
		// not cached
75
		if( ( $value = $this->object()->get( $path, null ) ) === null )
76
		{
77
			apcu_store( '-' . $this->prefix . $path, null );
78
			return $default;
79
		}
80
81
		apcu_store( $this->prefix . $path, $value );
82
83
		return $value;
84
	}
85
86
87
	/**
88
	 * Sets the value for the specified key.
89
	 *
90
	 * @param string $path Path to the requested value like tree/node/classname
91
	 * @param string $value Value that should be associated with the given path
92
	 * @return \Aimeos\Base\Config\Iface Config instance for method chaining
93
	 */
94
	public function set( string $path, $value ) : \Aimeos\Base\Config\Iface
95
	{
96
		if( !$this->enable ) {
97
			return $this->object()->set( $path, $value );
98
		}
99
100
		$path = trim( $path, '/' );
101
102
		$this->object()->set( $path, $value );
103
104
		apcu_store( $this->prefix . $path, $value );
105
		return $this;
106
	}
107
}
108