CacheFileHelper   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 23
dl 0
loc 79
rs 10
c 1
b 0
f 1
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A arrayIdentifier() 0 3 1
A validateCacheItem() 0 5 1
A ttl() 0 7 3
A convertExpirationToSeconds() 0 17 3
A mergeCacheData() 0 3 1
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\Helpers;
4
5
use Silviooosilva\CacheerPhp\Helpers\CacheerHelper;
6
use Silviooosilva\CacheerPhp\Exceptions\CacheFileException;
7
8
/**
9
 * Class CacheFileHelper
10
 * @author Sílvio Silva <https://github.com/silviooosilva>
11
 * @package Silviooosilva\CacheerPhp
12
 */
13
class CacheFileHelper
14
{
15
16
    /**
17
    * Converts a string expiration format to seconds.
18
    *
19
    * @param string $expiration
20
    * @return int
21
    */
22
    public static function convertExpirationToSeconds(string $expiration)
23
    {
24
        $units = [
25
            'second' => 1,
26
            'minute' => 60,
27
            'hour'   => 3600,
28
            'day'    => 86400,
29
            'week'   => 604800,
30
            'month'  => 2592000,
31
            'year'   => 31536000,
32
        ];
33
        foreach ($units as $unit => $value) {
34
            if (strpos($expiration, $unit) !== false) {
35
                return (int)$expiration * $value;
36
            }
37
        }
38
        throw CacheFileException::create("Invalid expiration format");
39
    }
40
41
    /**
42
    * Merges cache data with existing data.
43
    * 
44
    * @param array $options
45
    * @return array
46
    */
47
    public static function mergeCacheData($cacheData)
48
    {
49
        return CacheerHelper::mergeCacheData($cacheData);
50
    }
51
52
    /**
53
     * Validates a cache item.
54
     * 
55
     * @param array $item
56
     * @return void
57
     */
58
    public static function validateCacheItem(array $item)
59
    {
60
        CacheerHelper::validateCacheItem(
61
            $item,
62
            fn($msg) => CacheFileException::create($msg)
63
        );
64
    }
65
66
    /**
67
    * Calculates the TTL (Time To Live) for cache items.
68
    *
69
    * @param string|int $ttl
70
    * @param int $defaultTTL
71
    * @return mixed
72
    */
73
    public static function ttl($ttl = null, ?int $defaultTTL = null) {
74
        if ($ttl) {
75
            $ttl = is_string($ttl) ? self::convertExpirationToSeconds($ttl) : $ttl;
76
        } else {
77
            $ttl = $defaultTTL;
78
        }
79
        return $ttl;
80
    }
81
82
  /**
83
  * Generates an array identifier for cache data.
84
  * 
85
  * @param mixed $currentCacheData
86
  * @param mixed $cacheData
87
  * @return array
88
  */
89
  public static function arrayIdentifier(mixed $currentCacheData, mixed $cacheData)
90
  {
91
    return CacheerHelper::arrayIdentifier($currentCacheData, $cacheData);
92
  }
93
}
94