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\Protocol\ClientProtocolHandler;
13
14use FreeDSx\Ldap\Exception\ConnectionException;
15use FreeDSx\Ldap\Operation\Response\ExtendedResponse;
16use FreeDSx\Ldap\Operation\ResultCode;
17use FreeDSx\Ldap\Protocol\LdapMessageRequest;
18use FreeDSx\Ldap\Protocol\LdapMessageResponse;
19use FreeDSx\Ldap\Protocol\Queue\ClientQueue;
20
21/**
22 * Logic for handling a StartTLS operation.
23 *
24 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
25 */
26class ClientStartTlsHandler implements ResponseHandlerInterface
27{
28    /**
29     * @param LdapMessageRequest $messageTo
30     * @param LdapMessageResponse $messageFrom
31     * @param ClientQueue $queue
32     * @param array $options
33     * @return LdapMessageResponse
34     * @throws ConnectionException
35     * @throws \FreeDSx\Socket\Exception\ConnectionException
36     */
37    public function handleResponse(LdapMessageRequest $messageTo, LdapMessageResponse $messageFrom, ClientQueue $queue, array $options): ?LdapMessageResponse
38    {
39        /** @var ExtendedResponse $response */
40        $response = $messageFrom->getResponse();
41
42        if ($response->getResultCode() !== ResultCode::SUCCESS) {
43            throw new ConnectionException(sprintf(
44                'Unable to start TLS: %s',
45                $response->getDiagnosticMessage()
46            ));
47        }
48        $queue->encrypt();
49
50        return $messageFrom;
51    }
52}
53