CacheInterface_Trait::ttl_to_seconds()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 18
rs 9.7998
cc 3
nc 3
nop 1
1
<?php declare(strict_types=1);
2
/**
3
 * The WordPress transient driver for the PinkCrab Peristant Cache interface.
4
 *
5
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16
 *
17
 * @author Glynn Quelch <[email protected]>
18
 * @license http://www.opensource.org/licenses/mit-license.html  MIT License
19
 * @package PinkCrab\WP_PSR16_Cache
20
 */
21
22
namespace PinkCrab\WP_PSR16_Cache;
23
24
use DateInterval;
25
use InvalidArgumentException;
26
27
trait CacheInterface_Trait {
28
29
	/**
30
	 * Checks if the passed key is a valid key value.
31
	 *
32
	 * @param mixed $key
33
	 * @return bool
34
	 * @throws InvalidArgumentException
35
	 */
36
	protected function is_valid_key_value( $key ) : bool {
37
		if ( ! \is_string( $key ) || empty( $key ) ) {
38
			throw new \InvalidArgumentException( 'Key must be a valid string' );
39
		}
40
		return ! (bool) \preg_match( '|[\{\}\(\)/\\\@\:]|', $key );
41
	}
42
43
	/**
44
	 * Converts a ttl ( DateInterval, int )
45
	 *
46
	 * @param mixed $ttl
47
	 * @return int
48
	 */
49
	public function ttl_to_seconds( $ttl ):int {
50
		switch ( true ) {
51
			case is_a( $ttl, DateInterval::class ):
52
				$days  = (int) $ttl->format( '%a' );
53
				$hours = (int) $ttl->format( '%h' );
54
				$mins  = (int) $ttl->format( '%i' );
55
				$secs  = (int) $ttl->format( '%s' );
56
57
				return ( $days * 24 * 60 * 60 )
58
					+ ( $hours * 60 * 60 )
59
					+ ( $mins * 60 )
60
					+ $secs;
61
62
			case is_numeric( $ttl ):
63
				return (int) $ttl;
64
65
			default:
66
				return 0;
67
		}
68
	}
69
70
	/**
71
	 * Checks if all values in an array are true and boosl
72
	 *
73
	 * @param array<mixed> $array
74
	 * @return bool
75
	 */
76
	protected function all_true( array $array ): bool {
77
		foreach ( $array as $value ) {
78
			if ( ! is_bool( $value ) ) {
79
				return false;
80
			}
81
82
			if ( $value === false ) {
83
				return false;
84
			}
85
		}
86
		return true;
87
	}
88
}
89