Completed
Pull Request — master (#66)
by Greg
01:50
created

MetadataFormatterTrait::writeMetadata()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 16
rs 9.2
cc 4
eloc 11
nc 4
nop 3
1
<?php
2
namespace Consolidation\OutputFormatters\Formatters;
3
4
use Consolidation\OutputFormatters\Options\FormatterOptions;
5
use Symfony\Component\Console\Output\OutputInterface;
6
use Consolidation\OutputFormatters\StructuredData\MetadataInterface;
7
8
trait MetadataFormatterTrait
9
{
10
    /**
11
     * @inheritdoc
12
     */
13
    public function writeMetadata(OutputInterface $output, $structuredOutput, FormatterOptions $options)
14
    {
15
        $template = $options->get(FormatterOptions::METADATA_TEMPLATE);
16
        if (!$template) {
17
            return;
18
        }
19
        if (!$structuredOutput instanceof MetadataInterface) {
20
            return;
21
        }
22
        $metadata = $structuredOutput->getMetadata();
23
        if (empty($metadata)) {
24
            return;
25
        }
26
        $message = $this->interpolate($template, $metadata);
27
        return $output->writeln($message);
28
    }
29
30
    /**
31
     * Interpolates context values into the message placeholders.
32
     *
33
     * @author PHP Framework Interoperability Group
34
     *
35
     * @param string $message
36
     * @param array  $context
37
     *
38
     * @return string
39
     */
40
    private function interpolate($message, array $context)
41
    {
42
        // build a replacement array with braces around the context keys
43
        $replace = array();
44
        foreach ($context as $key => $val) {
45
            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
46
                $replace[sprintf('{%s}', $key)] = $val;
47
            }
48
        }
49
50
        // interpolate replacement values into the message and return
51
        return strtr($message, $replace);
52
    }
53
}
54