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