1<?php
2/**
3 * This file is part of the FreeDSx LDAP package.
4 *
5 * (c) Chad Sikorra <Chad.Sikorra@gmail.com>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11namespace FreeDSx\Ldap\Protocol\ClientProtocolHandler;
12
13use FreeDSx\Ldap\Exception\OperationException;
14use FreeDSx\Ldap\Operation\Request\ExtendedRequest;
15use FreeDSx\Ldap\Protocol\Factory\ExtendedResponseFactory;
16use FreeDSx\Ldap\Protocol\LdapMessageResponse;
17
18/**
19 * Logic for handling extended operations.
20 *
21 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
22 */
23class ClientExtendedOperationHandler extends ClientBasicHandler
24{
25    /**
26     * @var ExtendedResponseFactory
27     */
28    protected $extendedResponseFactory;
29
30    public function __construct(ExtendedResponseFactory $extendedResponseFactory = null)
31    {
32        $this->extendedResponseFactory = $extendedResponseFactory ?? new ExtendedResponseFactory();
33    }
34
35    /**
36     * {@inheritDoc}
37     */
38    public function handleRequest(ClientProtocolContext $context): ?LdapMessageResponse
39    {
40        $messageFrom = parent::handleRequest($context);
41
42        /** @var ExtendedRequest $request */
43        $request = $context->getRequest();
44        if (!$this->extendedResponseFactory->has($request->getName())) {
45            return $messageFrom;
46        }
47        if ($messageFrom === null) {
48            throw new OperationException('Expected an LDAP message response, but none was received.');
49        }
50
51        $response = $this->extendedResponseFactory->get(
52            $messageFrom->getResponse()->toAsn1(),
53            $request->getName()
54        );
55        $prop = (new \ReflectionClass(LdapMessageResponse::class))->getProperty('response');
56        $prop->setAccessible(true);
57        $prop->setValue($messageFrom, $response);
58
59        return $messageFrom;
60    }
61}
62