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\Server\Paging;
13
14use FreeDSx\Ldap\Exception\ProtocolException;
15
16/**
17 * Represents a collection of paging requests from a client.
18 *
19 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
20 */
21final class PagingRequests
22{
23    /**
24     * @var PagingRequest[]
25     */
26    private $requests;
27
28    /**
29     * @param PagingRequest[] $pagingRequests
30     */
31    public function __construct(array $pagingRequests = [])
32    {
33        $this->requests = $pagingRequests;
34    }
35
36    public function add(PagingRequest $request): void
37    {
38        if ($this->has($request->getNextCookie())) {
39            throw new ProtocolException('A request with this cookie already exists.');
40        }
41
42        $this->requests[] = $request;
43    }
44
45    public function remove(PagingRequest $toRemove): void
46    {
47        foreach ($this->requests as $i => $pagingRequest) {
48            if ($pagingRequest === $toRemove) {
49                unset($this->requests[$i]);
50            }
51        }
52    }
53
54    public function findByNextCookie(string $cookie): PagingRequest
55    {
56        $request = $this->getByNextCookie($cookie);
57        if (!$request) {
58            throw new ProtocolException('The supplied cookie is invalid.');
59        }
60
61        return $request;
62    }
63
64    public function has(string $cookie): bool
65    {
66        return (bool)$this->getByNextCookie($cookie);
67    }
68
69    private function getByNextCookie(string $cookie): ?PagingRequest
70    {
71        foreach ($this->requests as $pagingRequest) {
72            if ($pagingRequest->getNextCookie() === $cookie) {
73                return $pagingRequest;
74            }
75        }
76
77        return null;
78    }
79}
80