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\Exception\EncoderException;
16use FreeDSx\Asn1\Exception\PartialPduException;
17use FreeDSx\Asn1\Type\AbstractType;
18use FreeDSx\Asn1\Type\SequenceType;
19use FreeDSx\Ldap\Exception\ProtocolException;
20use FreeDSx\Ldap\Operation\LdapResult;
21
22/**
23 * RFC 3062. A Modify Password Response.
24 *
25 * PasswdModifyResponseValue ::= SEQUENCE {
26 *     genPasswd       [0]     OCTET STRING OPTIONAL }
27 *
28 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
29 */
30class PasswordModifyResponse extends ExtendedResponse
31{
32    /**
33     * @var null|string
34     */
35    protected $generatedPassword;
36
37    /**
38     * @param LdapResult $result
39     * @param null|string $generatedPassword
40     */
41    public function __construct(LdapResult $result, ?string $generatedPassword = null)
42    {
43        $this->generatedPassword = $generatedPassword;
44        parent::__construct($result);
45    }
46
47    /**
48     * @return null|string
49     */
50    public function getGeneratedPassword(): ?string
51    {
52        return $this->generatedPassword;
53    }
54
55    /**
56     * {@inheritdoc}
57     */
58    public function toAsn1(): AbstractType
59    {
60        if ($this->generatedPassword !== null) {
61            $this->responseValue = Asn1::sequence(Asn1::context(0, Asn1::octetString($this->generatedPassword)));
62        }
63
64        return parent::toAsn1();
65    }
66
67    /**
68     * @param AbstractType $type
69     * @return PasswordModifyResponse
70     * @throws EncoderException
71     * @throws PartialPduException
72     * @throws ProtocolException
73     */
74    public static function fromAsn1(AbstractType $type)
75    {
76        $result = self::createLdapResult($type);
77        $generatedPassword = null;
78
79        $pwdResponse = self::decodeEncodedValue($type);
80        if ($pwdResponse !== null && $pwdResponse instanceof SequenceType) {
81            foreach ($pwdResponse->getChildren() as $child) {
82                if ($child->getTagNumber() === 0) {
83                    $generatedPassword = $child->getValue();
84                }
85            }
86        }
87
88        return new self($result, $generatedPassword);
89    }
90}
91