PostMeta   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 20
c 2
b 0
f 1
dl 0
loc 48
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A buildMetaKey() 0 5 3
A normalize() 0 9 1
A get() 0 16 5
1
<?php
2
3
namespace GeminiLabs\Castor\Helpers;
4
5
/**
6
 * PostMeta::get('media');
7
 * PostMeta::get('media',[
8
 *    'fallback' => [],
9
 * ]);.
10
 */
11
class PostMeta
12
{
13
    /**
14
     * @param string $metaKey
15
     * @return mixed
16
     */
17
    public function get($metaKey, array $args = [])
18
    {
19
        if (empty($metaKey)) {
20
            return;
21
        }
22
23
        $args = $this->normalize($args);
24
        $metaKey = $this->buildMetaKey($metaKey, $args['prefix']);
25
        $metaValue = get_post_meta($args['id'], $metaKey, $args['single']);
26
27
        if (is_string($metaValue)) {
28
            $metaValue = trim($metaValue);
29
        }
30
        return empty($metaValue) && !in_array($metaValue, [0,'0'])
31
            ? $args['fallback']
32
            : $metaValue;
33
    }
34
35
    /**
36
     * @param string $metaKey
37
     * @param string $prefix
38
     * @return string
39
     */
40
    protected function buildMetaKey($metaKey, $prefix)
41
    {
42
        return ('_' == substr($metaKey, 0, 1) && !empty($prefix))
43
            ? sprintf('_%s%s', rtrim($prefix, '_'), $metaKey)
44
            : $prefix.$metaKey;
45
    }
46
47
    /**
48
     * @return array
49
     */
50
    protected function normalize(array $args)
51
    {
52
        $defaults = [
53
            'id' => get_the_ID(),
54
            'fallback' => '',
55
            'single' => true,
56
            'prefix' => apply_filters('pollux/prefix', 'pollux_'),
57
        ];
58
        return shortcode_atts($defaults, array_change_key_case($args));
59
    }
60
}
61