Completed
Push — master ( 805ee2...fead52 )
by Ibrahim
02:52
created

MetadataBuilder::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
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