Completed
Push — master ( f18b9d...e02934 )
by Tobias
08:27
created

FileStorage::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 3
crap 2
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Bundle\Storage;
13
14
use Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader;
15
use Symfony\Component\Translation\MessageCatalogue;
16
use Symfony\Component\Translation\Writer\TranslationWriter;
17
use Translation\Common\Model\Message;
18
use Translation\Common\Storage;
19
20
/**
21
 * This storage uses Symfony's writer and loader.
22
 *
23
 * @author Tobias Nyholm <[email protected]>
24
 */
25
class FileStorage implements Storage
26
{
27
    /**
28
     * @var TranslationWriter
29
     */
30
    private $writer;
31
32
    /**
33
     * @var TranslationLoader
34
     */
35
    private $loader;
36
37
    /**
38
     * @var string directory path
39
     */
40
    private $dir;
41
42
    /**
43
     * @var MessageCatalogue[] Fetched catalogies
44
     */
45
    private $catalogues;
46
47
    /**
48
     * @param TranslationWriter $writer
49
     * @param TranslationLoader $loader
50
     * @param array             $dir
51
     */
52
    public function __construct(TranslationWriter $writer, TranslationLoader $loader, $dir)
53
    {
54
        $this->writer = $writer;
55
        $this->loader = $loader;
56
        $this->dir = $dir;
0 ignored issues
show
Documentation Bug introduced by
It seems like $dir of type array is incompatible with the declared type string of property $dir.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function get($locale, $domain, $key)
63
    {
64
        $catalogue = $this->getCatalogue($locale);
65
66
        $translation = $catalogue->get($key, $domain);
67
68
        return new Message($key, $domain, $locale, $translation);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function create(Message $m)
75
    {
76
        $catalogue = $this->getCatalogue($m->getLocale());
77
        if (!$catalogue->defines($m->getKey(), $m->getDomain())) {
78
            $catalogue->set($m->getKey(), $m->getTranslation(), $m->getDomain());
79
            $this->writeCatalogue($catalogue, $m->getLocale(), $m->getDomain());
80
        }
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function update(Message $m)
87
    {
88
        $catalogue = $this->getCatalogue($m->getLocale());
89
        $catalogue->set($m->getKey(), $m->getTranslation(), $m->getDomain());
90
        $this->writeCatalogue($catalogue, $m->getLocale(), $m->getDomain());
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    public function delete($locale, $domain, $key)
97
    {
98
        $catalogue = $this->getCatalogue($locale);
99
        $messages = $catalogue->all($domain);
100
        unset($messages[$key]);
101
102
        $catalogue->replace($messages, $domain);
103
        $this->writeCatalogue($catalogue, $locale, $domain);
104
    }
105
106
    /**
107
     * Save catalogue back to file.
108
     *
109
     * @param MessageCatalogue $catalogue
110
     * @param string           $domain
111
     */
112
    private function writeCatalogue(MessageCatalogue $catalogue, $locale, $domain)
113
    {
114
        $resources = $catalogue->getResources();
115
        foreach ($resources as $resource) {
116
            $path = $resource->getResource();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Config...ource\ResourceInterface as the method getResource() does only exist in the following implementations of said interface: Symfony\Component\Config...\ClassExistenceResource, Symfony\Component\Config...ource\DirectoryResource, Symfony\Component\Config...e\FileExistenceResource, Symfony\Component\Config\Resource\FileResource, Symfony\Component\Depend...AutowireServiceResource, Symfony\Component\HttpKe...g\EnvParametersResource, Symfony\Component\Translation\Tests\StaleResource.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
117
            if (preg_match('|/'.$domain.'\.'.$locale.'\.([a-z]+)$|', $path, $matches)) {
118
                $this->writer->writeTranslations($catalogue, $matches[1], ['path' => str_replace($matches[0], '', $path)]);
119
            }
120
        }
121
    }
122
123
    /**
124
     * @param string $locale
125
     *
126
     * @return MessageCatalogue
127
     */
128
    private function getCatalogue($locale)
129
    {
130
        if (empty($this->catalogues[$locale])) {
131
            $this->loadCatalogue($locale, [$this->dir]);
132
        }
133
134
        return $this->catalogues[$locale];
135
    }
136
137
    /**
138
     * Load catalogue from files.
139
     *
140
     * @param string $locale
141
     * @param array  $dirs
142
     */
143
    private function loadCatalogue($locale, array $dirs)
144
    {
145
        $currentCatalogue = new MessageCatalogue($locale);
146
        foreach ($dirs as $path) {
147
            if (is_dir($path)) {
148
                $this->loader->loadMessages($path, $currentCatalogue);
149
            }
150
        }
151
152
        $this->catalogues[$locale] = $currentCatalogue;
153
    }
154
}
155