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\Search\Filter;
12
13use FreeDSx\Asn1\Asn1;
14use FreeDSx\Asn1\Type\AbstractType;
15use FreeDSx\Asn1\Type\IncompleteType;
16use FreeDSx\Asn1\Type\OctetStringType;
17use FreeDSx\Asn1\Type\SequenceType;
18use FreeDSx\Ldap\Entry\Attribute;
19use FreeDSx\Ldap\Exception\ProtocolException;
20use FreeDSx\Ldap\Protocol\LdapEncoder;
21
22/**
23 * Common methods for filters using attribute value assertions.
24 *
25 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
26 */
27trait AttributeValueAssertionTrait
28{
29    use FilterAttributeTrait;
30
31    /**
32     * @var string
33     */
34    protected $value;
35
36    /**
37     * @param string $attribute
38     * @param string $value
39     */
40    public function __construct(string $attribute, string $value)
41    {
42        $this->attribute = $attribute;
43        $this->value = $value;
44    }
45
46    /**
47     * @param string $value
48     * @return $this
49     */
50    public function setValue(string $value)
51    {
52        $this->value = $value;
53
54        return $this;
55    }
56
57    /**
58     * @return string
59     */
60    public function getValue(): string
61    {
62        return $this->value;
63    }
64
65    /**
66     * {@inheritdoc}
67     */
68    public function toAsn1(): AbstractType
69    {
70        return Asn1::context(self::CHOICE_TAG, Asn1::sequence(
71            Asn1::octetString($this->attribute),
72            Asn1::octetString($this->value)
73        ));
74    }
75
76    /**
77     * {@inheritdoc}
78     */
79    public function toString(): string
80    {
81        return self::PAREN_LEFT
82            . $this->attribute
83            . self::FILTER_TYPE
84            . Attribute::escape($this->value)
85            . self::PAREN_RIGHT;
86    }
87
88    /**
89     * {@inheritdoc}
90     */
91    public static function fromAsn1(AbstractType $type)
92    {
93        $type = $type instanceof IncompleteType ? (new LdapEncoder())->complete($type, AbstractType::TAG_TYPE_SEQUENCE) : $type;
94        if (!($type instanceof SequenceType && count($type) === 2)) {
95            throw new ProtocolException('The attribute value assertion is malformed.');
96        }
97
98        $attribute = $type->getChild(0);
99        $value = $type->getChild(1);
100        if (!($attribute instanceof OctetStringType && $value instanceof OctetStringType)) {
101            throw new ProtocolException('The attribute value assertion is malformed.');
102        }
103
104        return new static($attribute->getValue(), $value->getValue());
105    }
106}
107