summaryrefslogtreecommitdiffstats
path: root/library/Director/Db/Cache/CustomVariableCache.php
blob: 243ecae94b0e73ada2fa8c356e879c71c9e681e9 (plain)
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
84
<?php

namespace Icinga\Module\Director\Db\Cache;

use Icinga\Application\Benchmark;
use Icinga\Module\Director\CustomVariable\CustomVariables;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\IcingaObject;

class CustomVariableCache
{
    protected $type;

    protected $rowsById = array();

    protected $varsById = array();

    public function __construct(IcingaObject $object)
    {
        Benchmark::measure('Initializing CustomVariableCache');
        $connection = $object->getConnection();
        $db = $connection->getDbAdapter();

        $columns = array(
            'id'       => sprintf('v.%s', $object->getVarsIdColumn()),
            'varname'  => 'v.varname',
            'varvalue' => 'v.varvalue',
            'format'   => 'v.format',
            'checksum' => '(NULL)',
        );

        if ($connection->isPgsql()) {
            if ($connection->hasPgExtension('pgcrypto')) {
                $columns['checksum'] = "DIGEST(v.varvalue || ';' || v.format, 'sha1')";
            }
        } else {
            $columns['checksum'] = "UNHEX(SHA1(v.varvalue || ';' || v.format))";
        }

        $query = $db->select()->from(
            array('v' => $object->getVarsTableName()),
            $columns
        );

        foreach ($db->fetchAll($query) as $row) {
            $id = $row->id;
            unset($row->id);

            if (is_resource($row->checksum)) {
                $row->checksum = stream_get_contents($row->checksum);
            }

            if (array_key_exists($id, $this->rowsById)) {
                $this->rowsById[$id][] = $row;
            } else {
                $this->rowsById[$id] = array($row);
            }
        }

        Benchmark::measure('Filled CustomVariableCache');
    }

    public function getVarsForObject(IcingaObject $object)
    {
        $id = $object->id;

        if (array_key_exists($id, $this->rowsById)) {
            if (! array_key_exists($id, $this->varsById)) {
                $this->varsById[$id] = CustomVariables::forStoredRows(
                    $this->rowsById[$id]
                );
            }

            return $this->varsById[$id];
        } else {
            return new CustomVariables();
        }
    }

    public function __destruct()
    {
        unset($this->db);
    }
}