ClassNameAsPostType::postTypeId()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Silk\Post;
4
5
trait ClassNameAsPostType
6
{
7
    /**
8
     * Class name derived post type identifier
9
     * @var string
10
     */
11
    protected static $classNamePostType;
12
13
    /**
14
     * Get the post type identifier for this model
15
     *
16
     * This method overloads the constant-based default, allowing for
17
     * a convenient alternative to hard-coding the post type.
18
     * The POST_TYPE constant must take precedence over the derived name, if set.
19
     *
20
     * @return string post type identifier (slug)
21
     */
22
    public static function postTypeId()
23
    {
24
        if (static::POST_TYPE) {
0 ignored issues
show
Bug introduced by
The constant Silk\Post\ClassNameAsPostType::POST_TYPE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
25
            return static::POST_TYPE;
26
        }
27
28
        return static::getPostTypeFromName();
29
    }
30
31
    /**
32
     * Get the post type id from the class name
33
     *
34
     * @return string
35
     */
36
    protected static function getPostTypeFromName()
37
    {
38
        if (static::$classNamePostType) {
39
            return static::$classNamePostType;
40
        }
41
42
        /**
43
         * Convert the class name to snake_case and cache on a static property
44
         * to prevent evaluating more than once.
45
         */
46
        $name = (new \ReflectionClass(static::class))->getShortName();
47
48
        /**
49
         * Adapted from Str::snake()
50
         * @link https://github.com/laravel/framework/blob/5.2/src/Illuminate/Support/Str.php
51
         */
52
        if (! ctype_lower($name)) {
53
            $name = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1_', $name));
54
        }
55
56
        return static::$classNamePostType = $name;
57
    }
58
}
59