Completed
Branch develop (2a5993)
by Evan
02:52
created

ClassNameAsPostType   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A postTypeId() 0 8 2
A getPostTypeFromName() 0 22 3
1
<?php
2
3
namespace Silk\Post;
4
5
trait ClassNameAsPostType
6
{
7
    /**
8
     * Class name derived post type identifiers
9
     * @var array  className => post_type
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) {
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 (isset(static::$classNamePostType[static::class])) {
39
            return static::$classNamePostType[static::class];
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[static::class] = $name;
57
    }
58
}
59