Completed
Pull Request — master (#290)
by Leny
08:38
created

ViewReferenceXmlCacheDriver   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 3
Bugs 1 Features 1
Metric Value
wmc 6
c 3
b 1
f 1
lcom 1
cbo 0
dl 0
loc 65
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A fileExists() 0 4 1
A readCache() 0 10 2
A writeFile() 0 15 2
1
<?php
2
3
namespace Victoire\Bundle\ViewReferenceBundle\Cache\Xml;
4
5
class ViewReferenceXmlCacheDriver
6
{
7
    protected $xmlFile;
8
    public static $baseRootNode = <<<'XML'
9
<?xml version='1.0' encoding='UTF-8' ?>
10
<viewReferences/>
11
XML;
12
13
    /**
14
     * @param string $filePath
15
     */
16
    public function __construct($filePath)
17
    {
18
        $this->xmlFile = $filePath;
19
    }
20
21
    /**
22
     * Does the cache file exists ?
23
     *
24
     * @return bool
25
     **/
26
    public function fileExists()
27
    {
28
        return file_exists($this->xmlFile);
29
    }
30
31
    /**
32
     * get the content of the view cache file.
33
     *
34
     * @return \SimpleXMLElement
35
     */
36
    public function readCache()
37
    {
38
        if ($this->fileExists()) {
39
            $xmlElement = new \SimpleXMLElement(file_get_contents($this->xmlFile));
40
        } else {
41
            $xmlElement = new \SimpleXMLElement(self::$baseRootNode);
42
        }
43
44
        return $xmlElement;
45
    }
46
47
    /**
48
     * write \SimpleXMLElement in the cache file.
49
     *
50
     * @param \SimpleXMLElement $rootNode
51
     *
52
     * @return int
53
     */
54
    public function writeFile(\SimpleXMLElement $rootNode)
55
    {
56
        if (!is_dir(dirname($this->xmlFile))) {
57
            mkdir(dirname($this->xmlFile), 0777, true);
58
        }
59
60
        //Used to format result and have a proper indentation
61
        $dom = new \DOMDocument('1.0');
62
        $dom->preserveWhiteSpace = false;
63
        $dom->formatOutput = true;
64
        $dom->loadXML($rootNode->asXML());
65
        $dom->saveXML();
66
67
        return $dom->save($this->xmlFile);
68
    }
69
}
70