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\Factory;
12
13use FreeDSx\Ldap\Operation\Request\ExtendedRequest;
14use FreeDSx\Ldap\Operation\Request\RequestInterface;
15use FreeDSx\Ldap\Operation\Request\SearchRequest;
16use FreeDSx\Ldap\Operation\Request\UnbindRequest;
17use FreeDSx\Ldap\Protocol\ServerProtocolHandler;
18use FreeDSx\Ldap\Protocol\ServerProtocolHandler\ServerProtocolHandlerInterface;
19
20/**
21 * Determines the correct handler for the request.
22 *
23 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
24 */
25class ServerProtocolHandlerFactory
26{
27    public function get(RequestInterface $request): ServerProtocolHandlerInterface
28    {
29        if ($request instanceof ExtendedRequest && $request->getName() === ExtendedRequest::OID_WHOAMI) {
30            return new ServerProtocolHandler\ServerWhoAmIHandler();
31        } elseif ($request instanceof ExtendedRequest && $request->getName() === ExtendedRequest::OID_START_TLS) {
32            return new ServerProtocolHandler\ServerStartTlsHandler();
33        } elseif ($this->isRootDseSearch($request)) {
34            return new ServerProtocolHandler\ServerRootDseHandler();
35        } elseif ($request instanceof SearchRequest) {
36            return new ServerProtocolHandler\ServerSearchHandler();
37        } elseif ($request instanceof UnbindRequest) {
38            return new ServerProtocolHandler\ServerUnbindHandler();
39        } else {
40            return new ServerProtocolHandler\ServerDispatchHandler();
41        }
42    }
43
44    /**
45     * @param RequestInterface $request
46     * @return bool
47     */
48    protected function isRootDseSearch(RequestInterface $request): bool
49    {
50        if (!$request instanceof SearchRequest) {
51            return false;
52        }
53
54        return $request->getScope() === SearchRequest::SCOPE_BASE_OBJECT
55                && ((string)$request->getBaseDn() === '');
56    }
57}
58