PostMetaManager   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 46
ccs 0
cts 28
cp 0
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A buildMetaKey() 0 5 3
A normalize() 0 9 1
A get() 0 14 4
1
<?php
2
3
namespace GeminiLabs\Pollux\MetaBox;
4
5
use GeminiLabs\Pollux\Application;
6
7
/**
8
 * PostMeta::get('media');
9
 * PostMeta::get('media',[
10
 *    'fallback' => [],
11
 * ]);
12
 */
13
class PostMetaManager
14
{
15
	/**
16
	 * @param string $metaKey
17
	 * @return mixed
18
	 */
19
	public function get( $metaKey, array $args = [] )
20
	{
21
		if( empty( $metaKey ))return;
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 )
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'   => Application::prefix(),
57
		];
58
		return shortcode_atts( $defaults, array_change_key_case( $args ));
59
	}
60
}
61