Completed
Pull Request — master (#406)
by Robert
02:52
created

File::setMetadata()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 10
rs 9.4285
cc 3
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Gaufrette;
4
5
use Gaufrette\Adapter\MetadataSupporter;
6
use Gaufrette\Exception\FileNotFound;
7
8
/**
9
 * Points to a file in a filesystem.
10
 *
11
 * @author Antoine Hérault <[email protected]>
12
 */
13
class File
14
{
15
    protected $key;
16
    protected $filesystem;
17
18
    /**
19
     * Content variable is lazy. It will not be read from filesystem until it's requested first time.
20
     *
21
     * @var mixed content
22
     */
23
    protected $content = null;
24
25
    /**
26
     * @var array metadata in associative array. Only for adapters that support metadata
27
     */
28
    protected $metadata = null;
29
30
    /**
31
     * Human readable filename (usually the end of the key).
32
     *
33
     * @var string name
34
     */
35
    protected $name = null;
36
37
    /**
38
     * File size in bytes.
39
     *
40
     * @var int size
41
     */
42
    protected $size = 0;
43
44
    /**
45
     * File date modified.
46
     *
47
     * @var int mtime
48
     */
49
    protected $mtime = null;
50
51
    /**
52
     * @param string     $key
53
     * @param Filesystem $filesystem
54
     */
55
    public function __construct($key, Filesystem $filesystem)
56
    {
57
        $this->key = $key;
58
        $this->name = $key;
59
        $this->filesystem = $filesystem;
60
    }
61
62
    /**
63
     * Returns the key.
64
     *
65
     * @return string
66
     */
67
    public function getKey()
68
    {
69
        return $this->key;
70
    }
71
72
    /**
73
     * Returns the content.
74
     *
75
     * @throws FileNotFound
76
     *
77
     * @param array $metadata optional metadata which should be send when read
78
     *
79
     * @return string
80
     */
81 View Code Duplication
    public function getContent($metadata = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
    {
83
        if (isset($this->content)) {
84
            return $this->content;
85
        }
86
        $this->setMetadata($metadata);
87
88
        return $this->content = $this->filesystem->read($this->key);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->content = $this->...stem->read($this->key); of type string|boolean adds the type boolean to the return on line 88 which is incompatible with the return type documented by Gaufrette\File::getContent of type string.
Loading history...
89
    }
90
91
    /**
92
     * Returns Filesystem instance.
93
     *
94
     * @return Filesystem filesystem instance
95
     */
96
    public function getFilesystem()
97
    {
98
        return $this->filesystem;
99
    }
100
101
    /**
102
     * @return string name of the file
103
     */
104
    public function getName()
105
    {
106
        return $this->name;
107
    }
108
109
    /**
110
     * @return int size of the file
111
     */
112
    public function getSize()
113
    {
114
        if ($this->size) {
115
            return $this->size;
116
        }
117
118
        try {
119
            return $this->size = $this->filesystem->size($this->getKey());
120
        } catch (FileNotFound $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
121
        }
122
123
        return 0;
124
    }
125
126
    /**
127
     * Returns the file modified time.
128
     *
129
     * @return int
130
     */
131
    public function getMtime()
132
    {
133
        return $this->mtime = $this->filesystem->mtime($this->key);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->filesystem->mtime($this->key) can also be of type boolean. However, the property $mtime is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
134
    }
135
136
    /**
137
     * @param int $size size of the file
138
     */
139
    public function setSize($size)
140
    {
141
        $this->size = $size;
142
    }
143
144
    /**
145
     * Sets the content.
146
     *
147
     * @param string $content
148
     * @param array  $metadata optional metadata which should be send when write
149
     *
150
     * @return int The number of bytes that were written into the file, or
151
     *             FALSE on failure
152
     */
153 View Code Duplication
    public function setContent($content, $metadata = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
    {
155
        $this->content = $content;
156
        $this->setMetadata($metadata);
157
158
        return $this->size = $this->filesystem->write($this->key, $this->content, true);
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->filesystem->write..., $this->content, true) can also be of type boolean. However, the property $size is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
159
    }
160
161
    /**
162
     * @param string $name name of the file
163
     */
164
    public function setName($name)
165
    {
166
        $this->name = $name;
167
    }
168
169
    /**
170
     * Indicates whether the file exists in the filesystem.
171
     *
172
     * @return bool
173
     */
174
    public function exists()
175
    {
176
        return $this->filesystem->has($this->key);
177
    }
178
179
    /**
180
     * Deletes the file from the filesystem.
181
     *
182
     * @throws FileNotFound
183
     * @throws \RuntimeException when cannot delete file
184
     *
185
     * @param array $metadata optional metadata which should be send when write
186
     *
187
     * @return bool TRUE on success
188
     */
189
    public function delete($metadata = array())
190
    {
191
        $this->setMetadata($metadata);
192
193
        return $this->filesystem->delete($this->key);
194
    }
195
196
    /**
197
     * Creates a new file stream instance of the file.
198
     *
199
     * @return Stream
200
     */
201
    public function createStream()
202
    {
203
        return $this->filesystem->createStream($this->key);
204
    }
205
206
    /**
207
     * Sets the metadata array to be stored in adapters that can support it.
208
     *
209
     * @param array $metadata
210
     *
211
     * @return bool
212
     */
213
    protected function setMetadata(array $metadata)
214
    {
215
        if ($metadata && $this->supportsMetadata()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $metadata of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
216
            $this->filesystem->getAdapter()->setMetadata($this->key, $metadata);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Gaufrette\Adapter as the method setMetadata() does only exist in the following implementations of said interface: Gaufrette\Adapter\AclAwareAmazonS3, Gaufrette\Adapter\AmazonS3, Gaufrette\Adapter\AwsS3, Gaufrette\Adapter\AzureBlobStorage, Gaufrette\Adapter\Cache, Gaufrette\Adapter\GoogleCloudStorage, Gaufrette\Adapter\GridFS.

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...
217
218
            return true;
219
        }
220
221
        return false;
222
    }
223
224
    /**
225
     * @return bool
226
     */
227
    private function supportsMetadata()
228
    {
229
        return $this->filesystem->getAdapter() instanceof MetadataSupporter;
230
    }
231
}
232