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\Request;
13
14use FreeDSx\Asn1\Asn1;
15use FreeDSx\Asn1\Type\AbstractType;
16use FreeDSx\Asn1\Type\OctetStringType;
17use FreeDSx\Ldap\Entry\Dn;
18use FreeDSx\Ldap\Exception\ProtocolException;
19
20/**
21 * RFC 4511, 4.8
22 *
23 * DelRequest ::= [APPLICATION 10] LDAPDN
24 *
25 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
26 */
27class DeleteRequest implements RequestInterface, DnRequestInterface
28{
29    protected const APP_TAG = 10;
30
31    /**
32     * @var Dn
33     */
34    protected $dn;
35
36    /**
37     * @param string|Dn $dn
38     */
39    public function __construct($dn)
40    {
41        $this->setDn($dn);
42    }
43
44    /**
45     * @param string|Dn $dn
46     * @return $this
47     */
48    public function setDn($dn)
49    {
50        $this->dn = $dn instanceof Dn ? $dn : new Dn($dn);
51
52        return $this;
53    }
54
55    /**
56     * @return Dn
57     */
58    public function getDn(): Dn
59    {
60        return $this->dn;
61    }
62
63    /**
64     * {@inheritdoc}
65     */
66    public function toAsn1(): AbstractType
67    {
68        return Asn1::application(self::APP_TAG, Asn1::octetString($this->dn->toString()));
69    }
70
71    /**
72     * {@inheritDoc}
73     * @return self
74     */
75    public static function fromAsn1(AbstractType $type)
76    {
77        self::validate($type);
78
79        return new self($type->getValue());
80    }
81
82    /**
83     * @param AbstractType $type
84     * @throws ProtocolException
85     */
86    protected static function validate(AbstractType $type): void
87    {
88        if (!$type instanceof OctetStringType || $type->getTagClass() !== AbstractType::TAG_CLASS_APPLICATION) {
89            throw new ProtocolException('The delete request must be an octet string with an application tag class.');
90        }
91        if ($type->getTagNumber() !== self::APP_TAG) {
92            throw new ProtocolException(sprintf(
93                'The delete request must have an app tag of %s, received: %s',
94                self::APP_TAG,
95                $type->getTagNumber()
96            ));
97        }
98    }
99}
100