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\ServerProtocolHandler;
12
13use FreeDSx\Ldap\Exception\RuntimeException;
14use FreeDSx\Ldap\Operation\Request\SearchRequest;
15use FreeDSx\Ldap\Operation\Response\SearchResultDone;
16use FreeDSx\Ldap\Operation\Response\SearchResultEntry;
17use FreeDSx\Ldap\Operation\ResultCode;
18use FreeDSx\Ldap\Protocol\LdapMessageRequest;
19use FreeDSx\Ldap\Protocol\LdapMessageResponse;
20use FreeDSx\Ldap\Protocol\Queue\ServerQueue;
21use FreeDSx\Ldap\Server\RequestContext;
22use FreeDSx\Ldap\Server\RequestHandler\RequestHandlerInterface;
23use FreeDSx\Ldap\Server\Token\TokenInterface;
24
25/**
26 * Handles search request logic.
27 *
28 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
29 */
30class ServerSearchHandler implements ServerProtocolHandlerInterface
31{
32    /**
33     * {@inheritDoc}
34     */
35    public function handleRequest(LdapMessageRequest $message, TokenInterface $token, RequestHandlerInterface $dispatcher, ServerQueue $queue, array $options): void
36    {
37        $context = new RequestContext($message->controls(), $token);
38        $request = $message->getRequest();
39
40        if (!$request instanceof SearchRequest) {
41            throw new RuntimeException(sprintf(
42                'Expected a search request, but got %s.',
43                get_class($request)
44            ));
45        }
46        $entries = $dispatcher->search($context, $request);
47
48        $messages = [];
49        foreach ($entries->toArray() as $entry) {
50            $messages[] = new LdapMessageResponse(
51                $message->getMessageId(),
52                new SearchResultEntry($entry)
53            );
54        }
55        $messages[] = new LdapMessageResponse(
56            $message->getMessageId(),
57            new SearchResultDone(ResultCode::SUCCESS)
58        );
59
60        $queue->sendMessage(...$messages);
61    }
62}
63