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\Operation\Response;
13
14use FreeDSx\Asn1\Asn1;
15use FreeDSx\Asn1\Type\AbstractType;
16use FreeDSx\Ldap\Exception\ProtocolException;
17use FreeDSx\Ldap\Exception\UrlParseException;
18use FreeDSx\Ldap\LdapUrl;
19use function array_map;
20
21/**
22 * A search result reference. RFC 4511, 4.5.3.
23 *
24 * SearchResultReference ::= [APPLICATION 19] SEQUENCE
25 *     SIZE (1..MAX) OF uri URI
26 *
27 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
28 */
29class SearchResultReference implements ResponseInterface
30{
31    protected const TAG_NUMBER = 19;
32
33    /**
34     * @var LdapUrl[]
35     */
36    protected $referrals = [];
37
38    /**
39     * @param LdapUrl ...$referrals
40     */
41    public function __construct(LdapUrl ...$referrals)
42    {
43        $this->referrals = $referrals;
44    }
45
46    /**
47     * @return LdapUrl[]
48     */
49    public function getReferrals(): array
50    {
51        return $this->referrals;
52    }
53
54    /**
55     * {@inheritDoc}
56     * @return self
57     */
58    public static function fromAsn1(AbstractType $type)
59    {
60        $referrals = [];
61
62        foreach ($type->getChildren() as $referral) {
63            try {
64                $referrals[] = LdapUrl::parse($referral->getValue());
65            } catch (UrlParseException $e) {
66                throw new ProtocolException($e->getMessage());
67            }
68        }
69
70        return new self(...$referrals);
71    }
72
73    /**
74     * {@inheritdoc}
75     */
76    public function toAsn1(): AbstractType
77    {
78        return Asn1::application(self::TAG_NUMBER, Asn1::sequence(...array_map(function ($ref) {
79            /** @var LdapUrl $ref */
80            return Asn1::octetString($ref->toString());
81        }, $this->referrals)));
82    }
83}
84