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\Ldap\Exception\ProtocolException;
18use FreeDSx\Ldap\Protocol\LdapEncoder;
19
20/**
21 * Checks for the presence of an attribute (ie. whether or not it contains a value). RFC 4511, 4.5.1.7.5
22 *
23 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
24 */
25class PresentFilter implements FilterInterface
26{
27    use FilterAttributeTrait;
28
29    protected const APP_TAG = 7;
30
31    /**
32     * @param string $attribute
33     */
34    public function __construct(string $attribute)
35    {
36        $this->attribute = $attribute;
37    }
38
39    /**
40     * {@inheritdoc}
41     */
42    public function toAsn1(): AbstractType
43    {
44        return Asn1::context(self::APP_TAG, Asn1::octetString($this->attribute));
45    }
46
47    /**
48     * {@inheritdoc}
49     */
50    public function toString(): string
51    {
52        return self::PAREN_LEFT . $this->attribute . self::FILTER_EQUAL . '*' . self::PAREN_RIGHT;
53    }
54
55    /**
56     * {@inheritdoc}
57     */
58    public static function fromAsn1(AbstractType $type)
59    {
60        $type = $type instanceof IncompleteType ? (new LdapEncoder())->complete($type, AbstractType::TAG_TYPE_OCTET_STRING) : $type;
61        if (!($type instanceof OctetStringType)) {
62            throw new ProtocolException('The present filter is malformed');
63        }
64
65        return new self($type->getValue());
66    }
67}
68