-
Notifications
You must be signed in to change notification settings - Fork 0
/
Factory.php
60 lines (44 loc) · 1.44 KB
/
Factory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
namespace Expresser\PostType;
use InvalidArgumentException;
use WP_Post;
class Factory
{
protected static $classCache = [];
public static function resolve(WP_Post $post)
{
$postType = $post->post_type;
$classname = isset(static::$classCache[$postType]) ? static::$classCache[$postType] : null;
if (is_null($classname)) {
$classname = static::normalizeClassName($postType);
static::$classCache[$postType] = $classname;
}
return new $classname($post);
}
protected static function normalizeClassName($key)
{
$classname = static::convertToNamespace($key);
if (!class_exists($classname)) {
$classname = static::convertToAlias($key);
if (!class_exists($classname)) {
$classname = __NAMESPACE__.'\\'.$classname;
if (!class_exists($classname)) {
throw new InvalidArgumentException('Class type not found.');
}
}
}
return $classname;
}
protected static function convertToWords($value)
{
return ucwords(str_replace(['-', '_'], ' ', $value));
}
protected static function convertToAlias($value)
{
return str_replace(' ', '', static::convertToWords($value));
}
protected static function convertToNamespace($value)
{
return str_replace(' ', '\\', static::convertToWords($value));
}
}