Completed
Push — master ( ec8354...8f0854 )
by Mārtiņš
02:29
created

MessageRevisions::saveRevision()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 3
crap 2.0116
1
<?php
2
3
namespace Printful\GettextCms;
4
5
use Gettext\Translation;
6
use Gettext\Translations;
7
use Printful\GettextCms\Exceptions\InvalidPathException;
8
use Printful\GettextCms\Interfaces\MessageConfigInterface;
9
use Printful\GettextCms\Structures\RevisionItem;
10
11
class MessageRevisions
12
{
13
    /** @var MessageConfigInterface */
14
    private $config;
15
16
    /**
17
     * Cached instance so we don't read the file each time
18
     * @var RevisionItem
19
     */
20
    private $revisionCache = null;
21
22 8
    public function __construct(MessageConfigInterface $config)
23
    {
24 8
        $this->config = $config;
25 8
    }
26
27
    /**
28
     * Get revisioned domain or the original domain name if revision does not exist for this domain
29
     *
30
     * @param string $locale
31
     * @param string $domain
32
     * @return string
33
     */
34 1
    public function getRevisionedDomain(string $locale, string $domain): string
35
    {
36 1
        if (!$this->revisionCache) {
37 1
            $this->revisionCache = $this->readFromFile();
38
        }
39
40 1
        $revisionedDomain = $this->revisionCache->getRevisionedDomain($locale, $domain);
41
42 1
        return $revisionedDomain ?: $domain;
43
    }
44
45
    /**
46
     * From given translations, create a versioned domain name "domain_XXXXXX"
47
     *
48
     * @param string $domain
49
     * @param Translations $translations
50
     * @return string
51
     */
52 1
    public function generateRevisionedDomain(string $domain, Translations $translations): string
53
    {
54 1
        return $domain . '-' . $this->generateHash($translations);
55
    }
56
57
    private function generateHash(Translations $translations): string
58
    {
59 1
        $array = array_map(function (Translation $t) {
60
            return [
61 1
                $t->getOriginal(),
62 1
                $t->getPlural(),
63 1
                $t->getTranslation(),
64 1
                $t->getPluralTranslations(),
65 1
                $t->getContext(),
66
            ];
67 1
        }, (array)$translations);
68
69 1
        return substr(md5(serialize($array)), 0, 6); // Take only 6, and pray for no collisions
70
    }
71
72
    /**
73
     * Store in revision file that a new revision was created
74
     *
75
     * @param string $locale
76
     * @param string $originalDomain
77
     * @param string $revisionedDomain
78
     * @return bool
79
     * @throws InvalidPathException
80
     */
81 2
    public function saveRevision(string $locale, string $originalDomain, string $revisionedDomain): bool
82
    {
83 2
        $revisions = $this->readFromFile();
84
85 2
        $previousRevision = $revisions->getRevisionedDomain($locale, $originalDomain);
86
87 2
        if ($previousRevision === $revisionedDomain) {
88
            // No need to save, because it's the same revision
89
            return true;
90
        }
91
92 2
        $revisions->setRevisionedDomain($locale, $originalDomain, $revisionedDomain);
93
94
        // TODO delete old generated domain revision
95
96 2
        return $this->writeToFile($revisions);
97
    }
98
99
    /**
100
     * Read revision data from file
101
     *
102
     * @return RevisionItem
103
     */
104 2
    private function readFromFile(): RevisionItem
105
    {
106 2
        $pathname = $this->getPathname();
107
108 2
        if (is_file($pathname)) {
109 1
            return RevisionItem::fromArray(json_decode(file_get_contents($pathname), true));
110
        }
111
112 2
        return new RevisionItem;
113
    }
114
115
    /**
116
     * Write revision data to json file
117
     *
118
     * @param Structures\RevisionItem $revisions
119
     * @return bool
120
     * @throws InvalidPathException
121
     */
122 2
    private function writeToFile(RevisionItem $revisions): bool
123
    {
124
        // Update the cached version
125 2
        $this->revisionCache = $revisions;
126
127 2
        $pathname = $this->getPathname();
128
129 2
        if (!is_dir(dirname($pathname))) {
130 1
            throw new InvalidPathException('Directory does not exist (' . $this->config->getMoDirectory() . ')');
131
        }
132
133 1
        return file_put_contents($pathname, json_encode($revisions->toArray(), JSON_PRETTY_PRINT));
0 ignored issues
show
Bug Best Practice introduced by
The expression return file_put_contents...Cms\JSON_PRETTY_PRINT)) returns the type integer which is incompatible with the type-hinted return boolean.
Loading history...
134
    }
135
136
    /**
137
     * Full path to revision file
138
     *
139
     * @return string
140
     */
141 2
    private function getPathname(): string
142
    {
143 2
        return rtrim($this->config->getMoDirectory(), '/') . '/' . 'revisions.json';
144
    }
145
}