1<?php
2
3/**
4 * This file is part of the FreeDSx LDAP package.
5 *
6 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
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 FreeDSx\Ldap;
13
14use FreeDSx\Ldap\Exception\RuntimeException;
15use Psr\Log\LoggerInterface;
16use Psr\Log\LogLevel;
17
18/**
19 * Some simple logging methods. Only logs if we have a logger in the options.
20 *
21 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
22 */
23trait LoggerTrait
24{
25    /**
26     * Logs a message and then throws a runtime exception.
27     *
28     * @throws RuntimeException
29     */
30    private function logAndThrow(
31        string $message,
32        array $context = []
33    ): void {
34        $this->log(
35            LogLevel::ERROR,
36            $message,
37            $context
38        );
39
40        throw new RuntimeException($message);
41    }
42
43    protected function logError(
44        string $message,
45        array $context = []
46    ): void {
47        $this->log(
48            LogLevel::ERROR,
49            $message,
50            $context
51        );
52    }
53
54    protected function logInfo(
55        string $message,
56        array $context = []
57    ): void {
58        $this->log(
59            LogLevel::INFO,
60            $message,
61            $context
62        );
63    }
64
65    /**
66     * Log a message with a level and context (if we have a logger).
67     *
68     * @param string $level
69     * @param string $message
70     * @param array $context
71     */
72    private function log(
73        string $level,
74        string $message,
75        array $context = []
76    ): void {
77        if (isset($this->options['logger']) && $this->options['logger'] instanceof LoggerInterface) {
78            $this->options['logger']->log(
79                $level,
80                $message,
81                $context
82            );
83        }
84    }
85}
86