Completed
Push — feature-output-formats ( a25fbf...c04345 )
by Arnaud
01:55
created

Prefix::subPrefix()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
/*
3
 * Copyright (c) Arnaud Ligny <[email protected]>
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Cecil\Page;
10
11
/**
12
 * Class Prefix.
13
 */
14
class Prefix
0 ignored issues
show
Coding Style introduced by
Prefix does not seem to conform to the naming convention (Utils?$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
15
{
16
    // https://regex101.com/r/tJWUrd/5
17
    // ie: "blog/2017-10-19-post-with-prefix.md" prefix is "2017-10-19"
18
    const PREFIX_PATTERN = '^(.*?)(([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])|[0-9]+)(-|_|\.)(.*)$';
19
20
    /**
21
     * Return true if the string contains a prefix.
22
     *
23
     * @param string $string
24
     *
25
     * @return bool
26
     */
27
    public static function hasPrefix(string $string): bool
28
    {
29
        if (preg_match('/'.self::PREFIX_PATTERN.'/', $string)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return (bool) preg_match...ATTERN . '/', $string);.
Loading history...
30
            return true;
31
        }
32
33
        return false;
34
    }
35
36
    /**
37
     * Return the prefix if exists.
38
     *
39
     * @param string $string
40
     *
41
     * @return string[]|null
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
42
     */
43
    public static function getPrefix(string $string): ?string
44
    {
45
        if (self::hasPrefix($string)) {
46
            preg_match('/'.self::PREFIX_PATTERN.'/', $string, $matches);
47
            return $matches[2];
48
        }
49
50
        return null;
51
    }
52
53
    /**
54
     * Return string without the prefix (if exists).
55
     *
56
     * @param string $string
57
     *
58
     * @return string
59
     */
60
    public static function subPrefix(string $string): string
61
    {
62
        if (self::hasPrefix($string)) {
63
            preg_match('/'.self::PREFIX_PATTERN.'/', $string, $matches);
64
            return $matches[1].$matches[7];
65
        }
66
67
        return $string;
68
    }
69
}
70