DefaultFormatter::formatMessage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 2
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Shared
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Shared\Message\Formatter;
16
17
use Phossa2\Shared\Base\ObjectAbstract;
18
19
/**
20
 * The default formatter
21
 *
22
 * @package Phossa2\Shared
23
 * @author  Hong Zhang <[email protected]>
24
 * @see     ObjectAbstract
25
 * @see     FormatterInterface
26
 * @version 2.0.28
27
 * @since   2.0.0 added
28
 * @since   2.0.28 update stringize()
29
 */
30
class DefaultFormatter extends ObjectAbstract implements FormatterInterface
31
{
32
    /**
33
     * {@inheritDoc}
34
     */
35
    public function formatMessage(
36
        /*# string */ $template,
37
        array $arguments = []
38
    )/*# : string */ {
39
        $this->stringize($arguments)->matchTemplate($template, $arguments);
40
        return vsprintf($template, $arguments);
41
    }
42
43
    /**
44
     * Convert any non-string item in the arguments to string
45
     *
46
     * @param array &$arguments
47
     * @return $this
48
     * @access protected
49
     * @since  2.0.10 modified to use json_encode
50
     */
51
    protected function stringize(array &$arguments)
52
    {
53
        array_walk($arguments, function (&$value) {
54
            if (is_object($value)) {
55
                $value = get_class($value);
56
            } elseif (is_scalar($value)) {
57
                $value = (string) $value;
58
            } else {
59
                $value = json_encode($value, 0);
60
            }
61
        });
62
        return $this;
63
    }
64
65
    /**
66
     * Match "%s" in template with the provided arguments.
67
     *
68
     * @param  string &$template
69
     * @param  array &$arguments
70
     * @return $this
71
     * @access protected
72
     */
73
    protected function matchTemplate(
74
        /*# string */ &$template,
75
        array &$arguments
76
    )/*# : string */ {
77
        $count = substr_count($template, '%s');
78
        $size  = sizeof($arguments);
79
        if ($count > $size) {
80
            $arguments = $arguments + array_fill($size, $count - $size, '');
81
        } else {
82
            $template .= str_repeat(' %s', $size - $count);
83
        }
84
        return $this;
85
    }
86
}
87