Completed
Push — master ( 2df5ef...42de6e )
by Freek
31:55 queued 25:36
created

LocalUrlGenerator::getBaseMediaDirectoryUrl()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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