Completed
Push — master ( 10fc03...618a69 )
by Freek
02:30
created

LocalUrlGenerator::getUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace Spatie\MediaLibrary\UrlGenerator;
4
5
use Spatie\MediaLibrary\Exceptions\UrlCannotBeDetermined;
6
use Spatie\String\Str;
7
8
class LocalUrlGenerator extends BaseUrlGenerator
9
{
10
    /**
11
     * Get the url for the profile of a media item.
12
     *
13
     * @return string
14
     *
15
     * @throws \Spatie\MediaLibrary\Exceptions\UrlCannotBeDetermined
16
     */
17
    public function getUrl() : string
18
    {
19
        if (! string($this->getStoragePath())->startsWith(public_path())) {
20
            throw UrlCannotBeDetermined::mediaNotPubliclyAvailable($this->getStoragePath(), public_path());
21
        }
22
23
        $url = $this->getBaseMediaDirectory().'/'.$this->getPathRelativeToRoot();
24
25
        $url = $this->makeCompatibleForNonUnixHosts($url);
26
27
        $url = $this->rawUrlEncodeFilename($url);
28
29
        return $url;
30
    }
31
32
    /*
33
     * Get the path for the profile of a media item.
34
     */
35
    public function getPath() : string
36
    {
37
        return $this->getStoragePath().'/'.$this->getPathRelativeToRoot();
38
    }
39
40
    /*
41
     * Get the directory where all files of the media item are stored.
42
     */
43
    protected function getBaseMediaDirectory() : Str
44
    {
45
        $baseDirectory = string($this->getStoragePath())->replace(public_path(), '');
46
47
        return $baseDirectory;
48
    }
49
50
    /*
51
     * Get the path where the whole medialibrary is stored.
52
     */
53
    protected function getStoragePath() : string
54
    {
55
        $diskRootPath = $this->config->get('filesystems.disks.'.$this->media->disk.'.root');
56
57
        return realpath($diskRootPath);
58
    }
59
60
    protected function makeCompatibleForNonUnixHosts(string $url) : string
61
    {
62
        if (DIRECTORY_SEPARATOR != '/') {
63
            $url = str_replace(DIRECTORY_SEPARATOR, '/', $url);
64
        }
65
66
        return $url;
67
    }
68
69
    public function rawUrlEncodeFilename(string $path = ''): string
70
    {
71
        return pathinfo($path, PATHINFO_DIRNAME).'/'.rawurlencode(pathinfo($path, PATHINFO_BASENAME));
72
    }
73
}
74