Completed
Push — master ( 4d50ae...84674b )
by Tobias
06:42
created

FileStorage   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 116
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 3
dl 0
loc 116
ccs 0
cts 53
cp 0
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A delete() 0 9 1
A writeCatalogue() 0 10 3
A getCatalogue() 0 8 2
A loadCatalogue() 0 11 3
A get() 0 8 1
A update() 0 6 1
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);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Translation\...$locale, $translation); (Translation\Common\Model\Message) is incompatible with the return type declared by the interface Translation\Common\Storage::get of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function update(Message $message)
75
    {
76
        $catalogue = $this->getCatalogue($message->getLocale());
77
        $catalogue->set($message->getKey(), $message->getTranslation(), $message->getDomain());
78
        $this->writeCatalogue($catalogue, $message->getLocale(), $message->getDomain());
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function delete($locale, $domain, $key)
85
    {
86
        $catalogue = $this->getCatalogue($locale);
87
        $messages = $catalogue->all($domain);
88
        unset($messages[$key]);
89
90
        $catalogue->replace($messages, $domain);
91
        $this->writeCatalogue($catalogue, $locale, $domain);
92
    }
93
94
    /**
95
     * Save catalogue back to file.
96
     *
97
     * @param MessageCatalogue $catalogue
98
     * @param string           $domain
99
     */
100
    private function writeCatalogue(MessageCatalogue $catalogue, $locale, $domain)
101
    {
102
        $resources = $catalogue->getResources();
103
        foreach ($resources as $resource) {
104
            $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...
105
            if (preg_match('|/'.$domain.'\.'.$locale.'\.([a-z]+)$|', $path, $matches)) {
106
                $this->writer->writeTranslations($catalogue, $matches[1], ['path' => str_replace($matches[0], '', $path)]);
107
            }
108
        }
109
    }
110
111
    /**
112
     * @param $locale
113
     */
114
    private function getCatalogue($locale)
115
    {
116
        if (empty($this->catalogues[$locale])) {
117
            $this->loadCatalogue($locale, [$this->dir]);
118
        }
119
120
        return $this->catalogues[$locale];
121
    }
122
123
    /**
124
     * Load catalogue from files.
125
     *
126
     * @param $locale
127
     * @param array $dirs
128
     */
129
    private function loadCatalogue($locale, array $dirs)
130
    {
131
        $currentCatalogue = new MessageCatalogue($locale);
132
        foreach ($dirs as $path) {
133
            if (is_dir($path)) {
134
                $this->loader->loadMessages($path, $currentCatalogue);
135
            }
136
        }
137
138
        $this->catalogues[$locale] = $currentCatalogue;
139
    }
140
}
141