Passed
Branch develop (612b6d)
by Steve
04:05
created

NamespaceFieldKey   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 13
c 0
b 0
f 0
lcom 0
cbo 2
dl 0
loc 60
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getBuilder() 0 4 1
A transformValue() 0 12 2
A shouldTransformValue() 0 4 3
A hasCustomKey() 0 4 3
A hasCustomCollapsedKey() 0 4 3
1
<?php
2
3
namespace StoutLogic\AcfBuilder\Transform;
4
5
/**
6
 * Namespace a field key by appending the namespace consisting of 'field'
7
 * and the Builder's name before the defined key.
8
 *
9
 * Ensure all lowercase.
10
 */
11
class NamespaceFieldKey extends RecursiveTransform
12
{
13
    protected $keys = ['key', 'field', 'collapsed'];
14
15
    /**
16
     * @param \StoutLogic\AcfBuilder\NamedBuilder $builder
17
     */
18
    public function __construct(\StoutLogic\AcfBuilder\NamedBuilder $builder)
19
    {
20
        parent::__construct($builder);
21
    }
22
23
    /**
24
     * @return \StoutLogic\AcfBuilder\NamedBuilder
25
     */
26
    public function getBuilder()
27
    {
28
        return parent::getBuilder();
29
    }
30
31
    /**
32
     * @param  string $value Key
33
     * @return string Namedspaced key
34
     */
35
    public function transformValue($value)
36
    {
37
        $namespace = 'field_';
38
        $groupName = $this->getBuilder()->getName();
39
40
        if ($groupName) {
41
            // remove field_ or group_ if already at the begining of the key
42
            $value = preg_replace('/^field_|^group_/', '', $value);
43
            $namespace .= str_replace(' ', '_', $groupName).'_';
44
        }
45
        return strtolower($namespace.$value);
46
    }
47
48
    public function shouldTransformValue($key, $config)
49
    {
50
        return parent::shouldTransformValue($key, $config) && !$this->hasCustomKey($key, $config) && !$this->hasCustomCollapsedKey($key, $config);
51
    }
52
53
    /**
54
     * @param $config
55
     * @return bool
56
     */
57
    private function hasCustomKey($key, $config)
58
    {
59
        return ($key !== 'collapsed' && array_key_exists('_has_custom_key', $config) && $config['_has_custom_key'] === true);
60
    }
61
62
    /**
63
     * @param $config
64
     * @return bool
65
     */
66
    private function hasCustomCollapsedKey($key, $config)
67
    {
68
        return ($key === 'collapsed' && array_key_exists('_has_custom_collapsed_key', $config) && $config['_has_custom_collapsed_key'] === true);
69
    }
70
}
71