1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Formatter;
13
14/**
15 * formats the record to be used in the FlowdockHandler
16 *
17 * @author Dominik Liebler <liebler.dominik@gmail.com>
18 */
19class FlowdockFormatter implements FormatterInterface
20{
21    /**
22     * @var string
23     */
24    private $source;
25
26    /**
27     * @var string
28     */
29    private $sourceEmail;
30
31    public function __construct(string $source, string $sourceEmail)
32    {
33        $this->source = $source;
34        $this->sourceEmail = $sourceEmail;
35    }
36
37    /**
38     * {@inheritDoc}
39     *
40     * @return mixed[]
41     */
42    public function format(array $record): array
43    {
44        $tags = [
45            '#logs',
46            '#' . strtolower($record['level_name']),
47            '#' . $record['channel'],
48        ];
49
50        foreach ($record['extra'] as $value) {
51            $tags[] = '#' . $value;
52        }
53
54        $subject = sprintf(
55            'in %s: %s - %s',
56            $this->source,
57            $record['level_name'],
58            $this->getShortMessage($record['message'])
59        );
60
61        $record['flowdock'] = [
62            'source' => $this->source,
63            'from_address' => $this->sourceEmail,
64            'subject' => $subject,
65            'content' => $record['message'],
66            'tags' => $tags,
67            'project' => $this->source,
68        ];
69
70        return $record;
71    }
72
73    /**
74     * {@inheritDoc}
75     *
76     * @return mixed[][]
77     */
78    public function formatBatch(array $records): array
79    {
80        $formatted = [];
81
82        foreach ($records as $record) {
83            $formatted[] = $this->format($record);
84        }
85
86        return $formatted;
87    }
88
89    public function getShortMessage(string $message): string
90    {
91        static $hasMbString;
92
93        if (null === $hasMbString) {
94            $hasMbString = function_exists('mb_strlen');
95        }
96
97        $maxLength = 45;
98
99        if ($hasMbString) {
100            if (mb_strlen($message, 'UTF-8') > $maxLength) {
101                $message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
102            }
103        } else {
104            if (strlen($message) > $maxLength) {
105                $message = substr($message, 0, $maxLength - 4) . ' ...';
106            }
107        }
108
109        return $message;
110    }
111}
112