Publisher::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
ccs 0
cts 0
cp 0
crap 12
1
<?php
2
declare(strict_types=1);
3
4
/*
5
 * This file is part of the php-gelf package.
6
 *
7
 * (c) Benjamin Zikarsky <http://benjamin-zikarsky.de>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Gelf;
14
15
use Gelf\Transport\TransportInterface;
16
use Gelf\MessageValidator as DefaultMessageValidator;
17
use RuntimeException;
18
19
/**
20
 * A GELF publisher functions as a hub for pushing out a GELF message
21
 * to a least one GELF endpoint
22
 *
23
 * @author Benjamin Zikarsky <[email protected]>
24
 */
25
class Publisher implements PublisherInterface
26
{
27
    private array $transports = [];
28
    private MessageValidatorInterface $messageValidator;
29
30
    /**
31
     * Creates a Publisher for GELF-messages.
32
     */
33
    public function __construct(
34
        ?TransportInterface $transport = null,
35
        ?MessageValidatorInterface $messageValidator = null
36
    ) {
37
        $this->messageValidator = $messageValidator
38
            ?: new DefaultMessageValidator();
39
40
        if (null !== $transport) {
41
            $this->addTransport($transport);
42
        }
43 6
    }
44
45
    /**
46
     * @inheritDoc
47 6
     */
48 6
    public function publish(MessageInterface $message): void
49 1
    {
50
        if (count($this->transports) == 0) {
51 6
            throw new RuntimeException(
52 6
                "Publisher requires at least one transport"
53
            );
54 6
        }
55
56
        $reason = '';
57
        if (!$this->messageValidator->validate($message, $reason)) {
58
            throw new RuntimeException("Message is invalid: $reason");
59
        }
60
61 4
        foreach ($this->transports as $transport) {
62
            /* @var $transport TransportInterface */
63 4
            $transport->send($message);
64 1
        }
65 1
    }
66
67
    /**
68
     * Adds a transport object to the publisher.
69 3
     */
70 3
    public function addTransport(TransportInterface $transport): void
71 1
    {
72
        $this->transports[spl_object_hash($transport)] = $transport;
73
    }
74 2
75
    /**
76 2
     * Returns all defined transports.
77
     *
78 2
     * @return TransportInterface[]
79
     */
80
    public function getTransports(): array
81
    {
82
        return array_values($this->transports);
83
    }
84
85 6
    /**
86
     * Returns the current message validator.
87 6
     */
88 6
    public function getMessageValidator(): MessageValidatorInterface
89
    {
90
        return $this->messageValidator;
91
    }
92
}
93