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\Exception;
13
14use Exception;
15use FreeDSx\Ldap\Operation\ResultCode;
16use Throwable;
17
18/**
19 * Used in client-side requests to indicate generic issues with non-success request responses for operations. Used to
20 * indicate an error during server-side operation processing. The resulting message and code is used in the
21 * LDAP result sent back to the client (when thrown from the request handler).
22 *
23 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
24 */
25class OperationException extends Exception
26{
27    public function __construct(
28        string $message = '',
29        int $code = ResultCode::OPERATIONS_ERROR,
30        Throwable $previous = null
31    ) {
32        $message = empty($message)
33            ? $this->generateMessage($code)
34            : $message;
35
36        parent::__construct(
37            $message,
38            $code,
39            $previous
40        );
41    }
42
43    /**
44     * Get the LDAP result code as a short string (as defined in the LDAP RFC).
45     *
46     * @return string|null
47     */
48    public function getCodeShort(): ?string
49    {
50        return ResultCode::MEANING_SHORT[$this->getCode()] ?? null;
51    }
52
53    /**
54     * Get the LDAP result code meaning description (as defined in the LDAP RFC).
55     *
56     * @return string|null
57     */
58    public function getCodeDescription(): ?string
59    {
60        return ResultCode::MEANING_DESCRIPTION[$this->getCode()] ?? null;
61    }
62
63    private function generateMessage(int $resultCode): string
64    {
65        $message = sprintf('The result code %d was thrown', $resultCode);
66
67        if (isset(ResultCode::MEANING_SHORT[$resultCode])) {
68            $message .= sprintf(' (%s)', ResultCode::MEANING_SHORT[$resultCode]);
69        }
70        if (isset(ResultCode::MEANING_DESCRIPTION[$resultCode])) {
71            $message .= '. ' . ResultCode::MEANING_DESCRIPTION[$resultCode];
72        }
73
74        return $message;
75    }
76}
77