Completed
Pull Request — master (#10)
by Tomáš
03:17
created

generatePermalinkPathname()   C

Complexity

Conditions 14
Paths 44

Size

Total Lines 66
Code Lines 53

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 14.7893

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 37
cts 44
cp 0.8409
rs 5.8815
c 0
b 0
f 0
cc 14
eloc 53
nc 44
nop 1
crap 14.7893

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is a part of Sculpin.
5
 *
6
 * (c) Dragonfly Development Inc.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symplify\PHP7_Sculpin\Permalink;
13
14
use Symplify\PHP7_Sculpin\Source\SourceInterface;
15
use Symplify\PHP7_Sculpin\Util\PathNormalizer;
16
17
final class SourcePermalinkFactory
18
{
19
    /**
20
     * @var string
21
     */
22
    private $defaultPermalink;
23
24 4
    public function __construct(string $defaultPermalink)
25
    {
26 4
        $this->defaultPermalink = $defaultPermalink;
27 4
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 4
    public function create(SourceInterface $source) : Permalink
33
    {
34 4
        if ($source->canBeFormatted()) {
35 4
            $relativeFilePath = $this->generatePermalinkPathname($source);
36
            // TODO: Make this configurable... not all index files are named index.*
37 4
            if (strpos(basename($relativeFilePath), 'index.') === false) {
38 2
                $relativeUrlPath = $relativeFilePath;
39
            } else {
40 2
                $relativeUrlPath = dirname($relativeFilePath);
41
            }
42 4
            if ($relativeUrlPath == '/.') {
43 4
                $relativeUrlPath = '/';
44
            }
45
        } else {
46
            $relativeFilePath = $relativeUrlPath = $source->relativePathname();
47
        }
48
49 4
        if (0 !== strpos($relativeUrlPath, '/')) {
50 4
            $relativeUrlPath = '/'.$relativeUrlPath;
51
        }
52
53 4
        $relativeUrlPath = PathNormalizer::normalize($relativeUrlPath);
0 ignored issues
show
Bug introduced by
It seems like $relativeUrlPath can also be of type array<integer,string> or null; however, Symplify\PHP7_Sculpin\Ut...Normalizer::normalize() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
54
55 4
        return new Permalink($relativeFilePath, $relativeUrlPath);
0 ignored issues
show
Bug introduced by
It seems like $relativeFilePath defined by $this->generatePermalinkPathname($source) on line 35 can also be of type array<integer,string> or null; however, Symplify\PHP7_Sculpin\Pe...ermalink::__construct() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
56
    }
57
58 4
    private function generatePermalinkPathname(SourceInterface $source)
59
    {
60 4
        $pathname = $source->relativePathname();
61
        // Make sure that twig files end up as .html files.
62 4
        $pathname = preg_replace('/(html\.)?twig$|twig\.html$/', 'html', $pathname);
63 4
        $date = $source->data()->get('calculated_date');
64 4
        $title = $source->data()->get('title');
65 4
        $slug = $source->data()->get('slug');
66 4
        if (!$permalink = $source->data()->get('permalink')) {
67 4
            $permalink = $this->defaultPermalink;
68
        }
69
        switch ($permalink) {
70 4
            case 'none':
71 1
                return $pathname;
72
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
73 3
            case 'pretty':
74 2
                if ($response = $this->isDatePath($pathname)) {
75 1
                    return implode('/', array_merge($response, ['index.html']));
76
                } else {
77 1
                    $pretty = preg_replace('/(\.[^\.\/]+|\.[^\.\/]+\.[^\.\/]+)$/', '', $pathname);
78 1
                    if (basename($pretty) == 'index') {
79
                        return $pretty.'.html';
80
                    } else {
81 1
                        return $pretty.'/index.html';
82
                    }
83
                }
84
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
85 1
            case 'date':
86
                if ($response = $this->isDatePath($pathname)) {
87
                    return implode('/', $response).'.html';
88
                }
89
90
                return preg_replace('/(\.[^\.]+|\.[^\.]+\.[^\.]+)$/', '', $pathname).'.html';
91
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
92
            default:
93 1
                list($year, $yr, $month, $mo, $day, $dy) = explode('-', date('Y-y-m-n-d-j', (int) $date));
94 1
                $permalink = preg_replace('/:year/', $year, $permalink);
95 1
                $permalink = preg_replace('/:yr/', $yr, $permalink);
96 1
                $permalink = preg_replace('/:month/', $month, $permalink);
97 1
                $permalink = preg_replace('/:mo/', $mo, $permalink);
98 1
                $permalink = preg_replace('/:day/', $day, $permalink);
99 1
                $permalink = preg_replace('/:dy/', $dy, $permalink);
100 1
                $permalink = preg_replace('/:title/', $this->normalize($title), $permalink);
101 1
                $permalink = preg_replace('/:slug_title/', $this->normalize($slug ?: $title), $permalink);
102 1
                $filename = $pathname;
103 1
                if ($isDatePath = $this->isDatePath($pathname)) {
104
                    $filename = $isDatePath[3];
105
                }
106 1
                $permalink = preg_replace('/:filename/', $filename, $permalink);
107 1
                $permalink = preg_replace('/:slug_filename/', $this->normalize($slug ?: $filename), $permalink);
108 1
                if (strrpos($filename, DIRECTORY_SEPARATOR) !== false) {
109
                    $basename = substr($filename, strrpos($filename, DIRECTORY_SEPARATOR) + 1);
110
                } else {
111 1
                    $basename = $filename;
112
                }
113 1
                $prettyBasename = false !== strrpos($basename, '.') ? substr($basename, 0, strrpos($basename, '.')) : $basename;
114 1
                $permalink = preg_replace('/:basename_real/', $basename, $permalink);
115 1
                $permalink = preg_replace('/:basename/', $prettyBasename, $permalink);
116 1
                if (substr($permalink, -1, 1) == '/') {
117
                    $permalink .= 'index.html';
118
                }
119
120 1
                return $permalink;
121
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
122
        }
123
    }
124
125
    /**
126
     * @return mixed
127
     */
128 3
    private function isDatePath(string $path)
129
    {
130 3
        if (preg_match('/(\d{4})[\/\-]*(\d{2})[\/\-]*(\d{2})[\/\-]*(.+?)(\.[^\.]+|\.[^\.]+\.[^\.]+)$/', $path, $matches)) {
131 1
            return [$matches[1], $matches[2], $matches[3], $matches[4]];
132
        }
133
134 2
        return null;
135
    }
136
137
    /**
138
     * Normalize parameter to be used in human readable URL.
139
     *
140
     * "Inspired" by Phrozn's normalize implementation.
141
     */
142 1
    private function normalize(string $param, string $space = '-') : string
143
    {
144 1
        $param = trim($param);
145 1
        if (function_exists('iconv')) {
146 1
            $param = @iconv('utf-8', 'us-ascii//TRANSLIT', $param);
147
        }
148 1
        $param = preg_replace('/[^a-zA-Z0-9 -]/', '', $param);
149 1
        $param = strtolower($param);
150 1
        $param = preg_replace('/[\s-]+/', $space, $param);
151
152 1
        return $param;
153
    }
154
}
155