Completed
Push — master ( 1a22b8...361f69 )
by Ryan
07:46
created

ImagePaths::prefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php namespace Anomaly\Streams\Platform\Image;
2
3
use Anomaly\FilesModule\File\Contract\FileInterface;
4
use Anomaly\Streams\Platform\Application\Application;
5
use Illuminate\Config\Repository;
6
use Illuminate\Http\Request;
7
8
/**
9
 * Class ImagePaths
10
 *
11
 * @link          http://anomaly.is/streams-platform
12
 * @author        AnomalyLabs, Inc. <[email protected]>
13
 * @author        Ryan Thompson <[email protected]>
14
 * @package       Anomaly\Streams\Platform\Image
15
 */
16
class ImagePaths
17
{
18
19
    /**
20
     * Predefined paths.
21
     *
22
     * @var array
23
     */
24
    protected $paths = [];
25
26
    /**
27
     * The config repository.
28
     *
29
     * @var Repository
30
     */
31
    protected $config;
32
33
    /**
34
     * The request object.
35
     *
36
     * @var Request
37
     */
38
    protected $request;
39
40
    /**
41
     * The application object.
42
     *
43
     * @var Application
44
     */
45
    protected $application;
46
47
    /**
48
     * Create a new ImagePaths instance.
49
     *
50
     * @param Repository  $config
51
     * @param Request     $request
52
     * @param Application $application
53
     */
54 View Code Duplication
    public function __construct(Repository $config, Request $request, Application $application)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
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...
55
    {
56
        $this->config      = $config;
57
        $this->request     = $request;
58
        $this->application = $application;
59
60
        $this->paths = $config->get('streams::images.paths', []);
0 ignored issues
show
Documentation Bug introduced by
It seems like $config->get('streams::images.paths', array()) of type * is incompatible with the declared type array of property $paths.

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...
61
    }
62
63
    /**
64
     * Get the paths.
65
     *
66
     * @return array|mixed
67
     */
68
    public function getPaths()
69
    {
70
        return $this->paths;
71
    }
72
73
    /**
74
     * Set the paths.
75
     *
76
     * @param array $paths
77
     * @return $this
78
     */
79
    public function setPaths(array $paths)
80
    {
81
        $this->paths = $paths;
82
83
        return $this;
84
    }
85
86
    /**
87
     * Add an image path hint.
88
     *
89
     * @param $namespace
90
     * @param $path
91
     * @return $this
92
     */
93
    public function addPath($namespace, $path)
94
    {
95
        $this->paths[$namespace] = $path;
96
97
        return $this;
98
    }
99
100
    /**
101
     * Return the real path for a given path.
102
     *
103
     * @param $path
104
     * @return string
105
     * @throws \Exception
106
     */
107 View Code Duplication
    public function realPath($path)
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...
108
    {
109
        if (str_contains($path, '::')) {
110
111
            list($namespace, $path) = explode('::', $path);
112
113
            if (!isset($this->paths[$namespace])) {
114
                throw new \Exception("Path hint [{$namespace}::{$path}] does not exist!");
115
            }
116
117
            return rtrim($this->paths[$namespace], '/') . '/' . $path;
118
        }
119
120
        return $path;
121
    }
122
123
    /**
124
     * Return the output path for an image.
125
     *
126
     * @param $path
127
     * @return string
128
     */
129
    public function outputPath(Image $image)
130
    {
131
        $path = $image->getImage();
132
133
        if ($path instanceof FileInterface) {
0 ignored issues
show
Bug introduced by
The class Anomaly\FilesModule\File\Contract\FileInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
134
            $path = $path->path();
135
        }
136
137
        /**
138
         * If the path is already public
139
         * then just use it as it is.
140
         */
141
        if (str_contains($path, public_path())) {
142
            return str_replace(public_path(), '', $path);
143
        }
144
145
        /**
146
         * If the path is a file or file path then
147
         * put it in /app/{$application}/files/disk/folder/filename.ext
148
         */
149
        if (is_string($path) && str_is('*://*', $path)) {
150
151
            $application = $this->application->getReference();
152
153
            list($disk, $folder, $filename) = explode('/', str_replace('://', '/', $path));
154
155
            if ($rename = $image->getFilename()) {
156
157
                $filename = $rename;
158
159
                if (strpos($filename, DIRECTORY_SEPARATOR)) {
160
                    $directory = null;
0 ignored issues
show
Unused Code introduced by
$directory 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...
161
                }
162
            }
163
164
            return "/app/{$application}/files/{$disk}/{$folder}/{$filename}";
165
        }
166
167
        /**
168
         * Get the real path relative to our installation.
169
         */
170
        $path = str_replace(base_path(), '', $this->realPath($path));
171
172
        /**
173
         * Build out path parts.
174
         */
175
        $filename    = basename($path);
176
        $directory   = ltrim(dirname($path), '/\\') . '/';
177
        $application = $this->application->getReference();
178
179
        if ($image->getAlterations() || $image->getQuality()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $image->getQuality() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
180
            $filename = md5(
181
                    var_export([$path, $image->getAlterations()], true) . $image->getQuality()
182
                ) . '.' . $image->getExtension();
183
        }
184
185
        if ($rename = $image->getFilename()) {
186
187
            $directory = null;
188
            $filename  = ltrim($rename, '/\\');
189
        }
190
191
        return "/app/{$application}/assets/{$directory}{$filename}";
192
    }
193
194
    /**
195
     * Return the path prefix.
196
     *
197
     * @return string
198
     */
199
    public function prefix()
200
    {
201
        return rtrim(array_get(parse_url($this->request->root()), 'path'), '/');
0 ignored issues
show
Security Bug introduced by
It seems like parse_url($this->request->root()) targeting parse_url() can also be of type false; however, array_get() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
202
    }
203
}
204