Skip to content

Core\Ldap\Filter::parse

Reads a filter written as LDAP filter text, such as (&(objectClass=user)(mail=*)), and returns it as a Core\Ldap\Filter.

Use it for a filter that you or an operator wrote, for example in a configuration file or a constant. The text cannot be tainted, so text from a request does not compile here. To search for a value from a user, build the filter with Core\Ldap\Filter::equals or one of the other functions of this class.

Text that is not a filter throws a LogicError. The message gives the position of the first wrong character, counted from 1.

Good to know: the result works the same as a filter you built step by step. Its toString returns text that parse reads back as the same filter.

Parameters

  • $textstringThe filter text, as RFC 4515 writes it. It cannot be tainted. Build a filter from user input with equals and the other functions of this class.

Return value

Returns Core\Ldap\Filter. A Core\Ldap\Filter. Its toString returns text that parse reads back as the same filter.

Errors

  • LogicErrorThe text is not a filter, it has a name that is not an attribute name, or it has more than 100 levels of filters inside each other. The message gives the position of the first wrong character.

Examples

A filter from the settings

<?nvs
// Shows how to read a filter that an operator wrote as text.
// The filter text is a constant that you wrote, so it is not `tainted`.
class Settings
{
public const string STAFF = '(&(objectClass=user)(memberOf=CN=Staff,OU=Groups,DC=example,DC=test))';
}
var $filter = Core\Ldap\Filter::parse(Settings::STAFF);
// `toString` returns the same text.
echo $filter->toString(), "\n";
Output
(&(objectClass=user)(memberOf=CN=Staff,OU=Groups,DC=example,DC=test))

Combine with a built filter

<?nvs
// Shows how to combine a filter read from text with a value from a user.
var $staff = Core\Ldap\Filter::parse('(&(objectClass=user)(department=Sales))');
// Think of this text as a name that somebody typed into a form.
string $typed = 'Lee';
var $filter = Core\Ldap\Filter::all($staff, Core\Ldap\Filter::startsWith('sn', $typed));
// This prints (&(&(objectClass=user)(department=Sales))(sn=Lee*)).
echo $filter->toString(), "\n";
Output
(&(&(objectClass=user)(department=Sales))(sn=Lee*))

Text that is not a filter

<?nvs
// Shows the error for text that is not a filter.
try {
// The last `)` is missing.
Core\Ldap\Filter::parse('(&(objectClass=user)(mail=*)');
} catch (LogicError $error) {
// The message names the position of the first wrong character, which is 29.
echo $error->message, "\n";
}
Output
Core\Ldap\Filter::parse: the text stops being a filter at character 29: a filter ends with `)`