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\Factory;
13
14use FreeDSx\Ldap\Operation;
15use FreeDSx\Ldap\Operation\Request;
16use FreeDSx\Ldap\Operation\Response;
17use FreeDSx\Ldap\Operation\ResultCode;
18use FreeDSx\Ldap\Protocol\ClientProtocolHandler;
19use FreeDSx\Ldap\Protocol\ClientProtocolHandler\RequestHandlerInterface;
20use FreeDSx\Ldap\Protocol\ClientProtocolHandler\ResponseHandlerInterface;
21
22/**
23 * Retrieves the correct handler for a specific client protocol request / response.
24 *
25 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
26 */
27class ClientProtocolHandlerFactory
28{
29    /**
30     * @param Request\RequestInterface $request
31     * @return ClientProtocolHandler\ClientBasicHandler|ClientProtocolHandler\ClientSaslBindHandler|ClientProtocolHandler\ClientUnbindHandler
32     */
33    public function forRequest(Request\RequestInterface $request): RequestHandlerInterface
34    {
35        if ($request instanceof Request\SearchRequest) {
36            return new ClientProtocolHandler\ClientSearchHandler();
37        } elseif ($request instanceof Request\UnbindRequest) {
38            return new ClientProtocolHandler\ClientUnbindHandler();
39        } elseif ($request instanceof Request\SaslBindRequest) {
40            return new ClientProtocolHandler\ClientSaslBindHandler();
41        } else {
42            return new ClientProtocolHandler\ClientBasicHandler();
43        }
44    }
45
46
47    /**
48     * @param Request\RequestInterface $request
49     * @param Response\ResponseInterface $response
50     * @return ClientProtocolHandler\ClientBasicHandler|ClientProtocolHandler\ClientReferralHandler|ClientProtocolHandler\ClientStartTlsHandler
51     */
52    public function forResponse(Request\RequestInterface $request, Response\ResponseInterface $response): ResponseHandlerInterface
53    {
54        if ($response instanceof Response\SearchResultDone || $response instanceof Response\SearchResultEntry || $response instanceof Response\SearchResultReference) {
55            return new ClientProtocolHandler\ClientSearchHandler();
56        } elseif ($response instanceof Operation\LdapResult && $response->getResultCode() === ResultCode::REFERRAL) {
57            return new ClientProtocolHandler\ClientReferralHandler();
58        } elseif ($request instanceof Request\ExtendedRequest && $request->getName() === Request\ExtendedRequest::OID_START_TLS) {
59            return new ClientProtocolHandler\ClientStartTlsHandler();
60        } elseif ($response instanceof Response\ExtendedResponse) {
61            return new ClientProtocolHandler\ClientExtendedOperationHandler();
62        } else {
63            return new ClientProtocolHandler\ClientBasicHandler();
64        }
65    }
66}
67