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