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