Completed
Pull Request — develop (#303)
by
unknown
08:23
created

Manager::store()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 7
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license    MIT
7
 * @copyright  2013 - 2016 Cross Solution <http://cross-solution.de>
8
 */
9
namespace Organizations\ImageFileCache;
10
11
use Organizations\Entity\OrganizationImage;
12
use Organizations\Options\ImageFileCacheOptions as Options;
13
use Zend\Stdlib\ErrorHandler;
14
use InvalidArgumentException;
15
use RuntimeException;
16
17
/**
18
 * Image file cache manager
19
 *
20
 * @author Miroslav Fedeleš <[email protected]>
21
 * @since 0.28
22
 */
23
class Manager
24
{
25
    
26
    /**
27
     * @var Options
28
     */
29
    protected $options;
30
    
31
    /**
32
     * @param Options $options
33
     */
34
    public function __construct(Options $options)
35
    {
36
        $this->options = $options;
37
    }
38
39
    /**
40
     * Returns image URI
41
     *
42
     * @param OrganizationImage $image
43
     * @return string
44
     */
45
    public function getUri(OrganizationImage $image)
46
    {
47
        if ($this->options->getEnabled()) {
48
            return sprintf('%s/%s', $this->options->getUriPath(), $this->getImageSubPath($image));
49
        }
50
        
51
        return $image->getUri();
52
    }
53
    
54
    /**
55
     * @return bool
56
     */
57
    public function isEnabled()
58
    {
59
        return $this->options->getEnabled();
60
    }
61
    
62
    /**
63
     * Store an image as a file in a file system
64
     *
65
     * @param OrganizationImage $image
66
     */
67
    public function store(OrganizationImage $image)
68
    {
69
        $resource = $image->getResource();
70
        $path = $this->getImagePath($image);
71
        $this->createDirectoryRecursively(dirname($path));
72
        file_put_contents($path, $resource);
73
    }
74
    
75
    /**
76
     * Delete an image file from file system
77
     *
78
     * @param OrganizationImage $image
79
     */
80
    public function delete(OrganizationImage $image)
81
    {
82
        @unlink($this->getImagePath($image));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
83
    }
84
85
    /**
86
     * Match the passed $uri and return an image ID on success
87
     *
88
     * @param string $uri
89
     * @return null|string Image ID
90
     */
91
    public function matchUri($uri)
92
    {
93
        $pattern = '#^' . preg_quote($this->options->getUriPath(), '#') . '/[0-9a-z]/[0-9a-z]/([0-9a-z]+)\.[a-zA-Z]{3,4}$#';
94
        $matches = [];
95
        preg_match($pattern, $uri, $matches);
96
        
97
        return isset($matches[1]) ? $matches[1] : null;
98
    }
99
    
100
    /**
101
     * @param OrganizationImage $image
102
     * @return string
103
     */
104
    protected function getImagePath(OrganizationImage $image)
105
    {
106
        return sprintf('%s/%s', $this->options->getFilePath(), $this->getImageSubPath($image));
107
    }
108
    
109
    /**
110
     * @param OrganizationImage $image
111
     * @return string
112
     */
113
    protected function getImageSubPath(OrganizationImage $image)
114
    {
115
        $id = $image->getId();
116
        
117
        if (!$id) {
118
            throw new InvalidArgumentException('image must have ID');
119
        }
120
        
121
        $extension = null;
0 ignored issues
show
Unused Code introduced by
$extension is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
122
        $filename = $image->getName();
123
        
124
        if ($filename) {
125
            // get an extension from the filename
126
            $extension = pathinfo($filename, PATHINFO_EXTENSION);
127
        } else {
128
            // try get an extension from MIME if any
129
            $extension = str_replace('image/', '', $image->getType());
130
        }
131
        
132
        if (!$extension) {
133
            throw new InvalidArgumentException('unable to get an image file extension');
134
        }
135
        
136
        $firstLevel = substr($id, -1) ?: '0';
137
        $secondLevel = substr($id, -2, 1) ?: '0';
138
        
139
        return sprintf('%s/%s/%s.%s', $firstLevel, $secondLevel, $id, $extension);
140
    }
141
142
    /**
143
     * @param string $dir
144
     */
145
    protected function createDirectoryRecursively($dir)
146
    {
147
        $dir = rtrim($dir, '/\\');
148
        
149
        if (! is_dir($dir)) {
150
            $this->createDirectoryRecursively(dirname($dir));
151
            
152
            $oldUmask = umask(0);
153
            
154
            ErrorHandler::start();
155
            $created = mkdir($dir, 0775);
156
            $error = ErrorHandler::stop();
157
            
158
            if (!$created) {
159
                throw new RuntimeException(sprintf('unable to create directory "%s"', $dir), 0, $error);
160
            }
161
            
162
            umask($oldUmask);
163
        }
164
    }
165
}
166