Passed
Push — master ( 5379a4...a2888f )
by Joao
04:49
created

src/Repository/CachedDBDataset.php (1 issue)

Check that a foreach expression is traversable

Bug Major

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace ByJG\AnyDataset\Repository;
4
5
use ByJG\Cache\CacheEngineInterface;
6
use InvalidArgumentException;
7
8
class CachedDBDataset
9
{
10
11
    /**
12
     *
13
     * @var CacheEngineInterface
14
     */
15
    protected $_cacheEngine = null;
16
17
    /**
18
     *
19
     * @var DBDataset
20
     */
21
    protected $_dbdataset = null;
22
23
    /**
24
     *
25
     * @param DBDataset $dbdataset
26
     * @param CacheEngineInterface $cacheEngine
27
     * @throws InvalidArgumentException
28
     */
29
    public function __construct(DBDataset $dbdataset, CacheEngineInterface $cacheEngine)
30
    {
31
        $this->_cacheEngine = $cacheEngine;
32
        $this->_dbdataset = $dbdataset;
33
    }
34
35
    public function getIterator($sql, $array = null, $ttl = 600)
36
    {
37
        $key1 = md5($sql);
38
39
        // Check which parameter exists in the SQL
40
        $arKey2 = array();
41
        if (is_array($array)) {
42
            foreach ($array as $key => $value) {
43
                if (preg_match("/\[\[$key\]\]/", $sql)) {
44
                    $arKey2[$key] = $value;
45
                }
46
            }
47
        }
48
49
        // Define the query key
50
        if (is_array($arKey2) && count($arKey2) > 0) {
51
            $key2 = ":" . md5(json_encode($arKey2));
52
        } else {
53
            $key2 = "";
54
        }
55
        $key = "qry:" . $key1 . $key2;
56
57
        // Get the CACHE
58
        $cache = $this->_cacheEngine->get($key, $ttl);
59
        if ($cache === false) {
60
            $cache = array();
61
            $it = $this->_dbdataset->getIterator($sql, $array);
62
            foreach ($it as $value) {
0 ignored issues
show
The expression $it of type object<ByJG\AnyDataset\R...tory\IteratorInterface> is not traversable.
Loading history...
63
                $cache[] = $value->toArray();
64
            }
65
66
            $this->_cacheEngine->set($key, $cache, $ttl);
67
        }
68
69
        $arrayDS = new ArrayDataset($cache);
70
        return $arrayDS->getIterator();
71
    }
72
}
73