MetadataBuilder   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 57
ccs 34
cts 34
cp 1
rs 10
wmc 13

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A build() 0 3 1
A with() 0 7 2
A __call() 0 10 4
A toSnakeCase() 0 8 3
A withCustomField() 0 11 2
1
<?php
2
namespace Yabacon\Paystack;
3
4
use Yabacon\Paystack\Exception\BadMetaNameException;
5
6
class MetadataBuilder
7
{
8
    private $meta;
9
    public static $auto_snake_case = true;
10
11 4
    public function __construct()
12
    {
13 4
        $this->meta = [];
14 4
    }
15
16 3
    private function with($name, $value)
17
    {
18 3
        if ($name === 'custom_fields') {
19 1
            throw new BadMetaNameException('Please use the withCustomField method to add custom fields');
20
        }
21 2
        $this->meta[$name] = $value;
22 2
        return $this;
23
    }
24
25 2
    private function toSnakeCase($input)
26
    {
27 2
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
28 2
        $ret = $matches[0];
29 2
        foreach ($ret as &$match) {
30 2
            $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
31 2
        }
32 2
        return implode('_', $ret);
33
    }
34
35 4
    public function __call($method, $args)
36
    {
37 4
        if ((strpos($method, 'with') === 0) && ($method !== 'with')) {
38 3
            $name = substr($method, 4);
39 3
            if (MetadataBuilder::$auto_snake_case) {
40 2
                $name = $this->toSnakeCase($name);
41 2
            }
42 3
            return $this->with($name, $args[0]);
43
        }
44 1
        throw new \BadMethodCallException('Call to undefined function: ' . get_class($this) . '::' . $method);
45
    }
46
47 3
    public function withCustomField($title, $value)
48
    {
49 3
        if (!array_key_exists('custom_fields', $this->meta)) {
50 3
            $this->meta['custom_fields'] = [];
51 3
        }
52 3
        $this->meta['custom_fields'][] = [
53 3
            'display_name' => strval($title),
54 3
            'variable_name' => strval($title),
55 3
            'value' => strval($value),
56
        ];
57 3
        return $this;
58
    }
59
60 2
    public function build()
61
    {
62 2
        return json_encode($this->meta);
63
    }
64
}
65