Skip to content

Repository files navigation

rasuvaeff/specification

Latest Stable VersionTotal DownloadsBuildStatic analysisPsalm levelPHPLicenseРусская версия

Specification pattern for building Yiisoft DB queries.

useRasuvaeff\Specification\SpecificationBuilder;
useRasuvaeff\Specification\QueryApplier;
$spec = SpecificationBuilder::create()
->whereEqual('status', 'active')
->whereGreaterThan('age', 18)
->whereIn('role', ['admin', 'moderator'])
->orderBy(['created_at' => 'DESC'])
->limit(20)
->build();
$query = (new \Yiisoft\Db\Query\Query($db))->from('users');
QueryApplier::apply($spec, $query);
$rows = $query->all();

Using an AI coding assistant?llms.txt is a compact, self-contained reference of the whole public API plus copy-paste recipes — drop it into the model's context. Contributors: see AGENTS.md. Projects using the llm/skills Composer plugin also get this package's agent skill synced into .agents/skills/ automatically on install.

Requirements

  • PHP 8.3+
  • yiisoft/db ^2.0.1

Installation

composer require rasuvaeff/specification

Usage

SpecificationBuilder

Fluent builder for composing query conditions:

useRasuvaeff\Specification\SpecificationBuilder;
useRasuvaeff\Specification\QueryApplier;
$spec = SpecificationBuilder::create()
->whereEqual('status', 'active')
->whereGreaterThan('age', 18)
->whereNull('deleted_at')
->build();
$query = (newYiisoft\Db\Query\Query($db))->from('users');
QueryApplier::apply($spec, $query);
$rows = $query->all();

Available methods:

MethodSQL equivalent
where($col, $val, $op)col op val (any operator)
whereEqual($col, $val)col = val
whereNotEqual($col, $val)col != val
whereGreaterThan($col, $val)col > val
whereGreaterThanOrEqual($col, $val)col >= val
whereLessThan($col, $val)col < val
whereLessThanOrEqual($col, $val)col <= val
whereIn($col, $values)col IN (values)
whereNotIn($col, $values)col NOT IN (values)
whereLike($col, $pattern)col LIKE pattern
whereNotLike($col, $pattern)col NOT LIKE pattern
whereBetween($col, $from, $to)col BETWEEN from AND to
whereNotBetween($col, $from, $to)col NOT BETWEEN from AND to
whereIlike($col, $pattern)col ILIKE pattern
whereNotIlike($col, $pattern)col NOT ILIKE pattern
whereStartsWith($col, $prefix)col LIKE prefix%
whereEndsWith($col, $suffix)col LIKE %suffix
whereContains($col, $substring)col LIKE %substring%
whereNull($col)col IS NULL
whereNotNull($col)col IS NOT NULL
orWhere(callable)OR (nested conditions)
notWhere(callable)NOT (nested conditions)
orderBy($columns)ORDER BY col [ASC|DESC]
limit($n)LIMIT n
offset($n)OFFSET n

Specifications

Building blocks for composing complex conditions:

useRasuvaeff\Specification\ComparisonSpecification;
useRasuvaeff\Specification\CompositeSpecification;
useRasuvaeff\Specification\NotSpecification;
useRasuvaeff\Specification\OffsetSpecification;
useRasuvaeff\Specification\OrConditionSpecification;
useRasuvaeff\Specification\OrSpecification;
useRasuvaeff\Specification\RawSpecification;
// AND conditions$spec = CompositeSpecification::create()
->withComparison('status', 'active')
->withComparison('age', 18, '>')
->withOrderBy(['created_at' => 'DESC'])
->withLimit(20)
->withOffset(40);
// OR condition arrays via OrConditionSpecification.$orConditionSpec = CompositeSpecification::create()
->withOrCondition(['status' => 'active', 'type' => 'pending']);
// OR conditions$orSpec = OrSpecification::create(
ComparisonSpecification::equal('type', 'admin'),
ComparisonSpecification::equal('type', 'moderator'),
);
// NOT condition$notSpec = newNotSpecification(
newComparisonSpecification('status', 'banned'),
);
// Raw SQL — see the Security note below$rawSpec = newRawSpecification('age > :age', ['age' => 18]);
// Offset for pagination$offset = CompositeSpecification::create()
->withLimit(10)
->withOffset(20);
// Raw SQL — see the Security note below$rawComposite = CompositeSpecification::create()
->withRaw('price > :min AND price < :max', ['min' => 10, 'max' => 100]);

ComparisonSpecification factory methods

ComparisonSpecification::equal('col', $val)
ComparisonSpecification::notEqual('col', $val)
ComparisonSpecification::greaterThan('col', $val)
ComparisonSpecification::greaterThanOrEqual('col', $val)
ComparisonSpecification::lessThan('col', $val)
ComparisonSpecification::lessThanOrEqual('col', $val)
ComparisonSpecification::like('col', 'pattern')
ComparisonSpecification::notLike('col', 'pattern')
ComparisonSpecification::ilike('col', 'pattern')
ComparisonSpecification::notIlike('col', 'pattern')
ComparisonSpecification::startsWith('col', 'prefix')
ComparisonSpecification::endsWith('col', 'suffix')
ComparisonSpecification::contains('col', 'substring')
ComparisonSpecification::in('col', [1, 2, 3])
ComparisonSpecification::notIn('col', [4, 5, 6])
ComparisonSpecification::between('col', $from, $to)
ComparisonSpecification::notBetween('col', $from, $to)
ComparisonSpecification::isNull('col')
ComparisonSpecification::isNotNull('col')

Custom visitor

Implement SpecificationVisitor<T> to traverse the specification tree:

useRasuvaeff\Specification\SpecificationVisitor;
useRasuvaeff\Specification\ComparisonSpecification;
// ... other specification imports/** @implements SpecificationVisitor<int> */finalclass CountingVisitor implements SpecificationVisitor
{
privateint$count = 0;
#[\Override]
publicfunctionvisitComparison(ComparisonSpecification$specification): int
{
return ++$this->count;
}
// ... implement all visit* methods (visitComparison, visitComposite, visitNot,// visitOr, visitOrCondition, visitRaw, visitOrderBy, visitLimit, visitOffset)
}

Examples

Runnable, offline examples (in-memory SQLite) live in examples/: builder.php (AND/IN/BETWEEN) and or-not-raw.php (OR/NOT/raw/order+limit).

composer install && php examples/builder.php

Security

  • Values are parameterized. All comparison/IN/BETWEEN/LIKE values are bound as parameters by yiisoft/db, so they are safe against SQL injection.
  • Column names are not validated — they are passed to yiisoft/db and quoted as identifiers, but there is no allow-list. Pass only trusted column names (typically hard-coded), never raw user input.
  • RawSpecification is a raw escape hatch. The condition string is not escaped — never build it from untrusted input. Pass user values only through the $params map (placeholders): new RawSpecification('age > :age', ['age' => $value]).

Performance

SpecificationBuilder is immutable — each where*(), limit(), and offset() call clones the builder before returning. This is safe and predictable but carries a small overhead (~3.3µs for a 7-step chain, vs ~2.4µs for direct CompositeSpecification composition). orWhere() additionally allocates a temporary builder and invokes a closure (~2.8µs vs ~1.4µs for direct OrSpecification::create()).

For most web request workloads (1–5 specs per request, DB queries taking 1–100ms) this overhead is negligible. For high-throughput batch processing where specs are built in a tight loop, prefer the direct CompositeSpecification API:

// ~26% faster than SpecificationBuilder for a 7-condition chain$spec = CompositeSpecification::create()
->withComparison('status', 'active')
->withComparison('age', 18, '>')
->withComparison('role', ['admin', 'editor'], 'in')
->withLimit(100);
// ~48% faster than orWhere() for OR composition$spec = CompositeSpecification::create()
->withSpecification(OrSpecification::create(
CompositeSpecification::create()->withComparison('status', 'active'),
CompositeSpecification::create()->withComparison('status', 'pending'),
));

Benchmarks live in benchmarks/ and run via composer bench (requires testo/bench).

Notes

  • ilike / not ilike are PostgreSQL-specific; other drivers (e.g. MySQL) do not support them. Use like for case-insensitive needs on those drivers.
  • For OR conditions use OrSpecification or SpecificationBuilder::orWhere(). CompositeSpecification composes with AND semantics.
  • withOrCondition() value formats: a scalar is plain equality ('status' => 'active'); an array whose first element is a known operator is a shorthand ('age' => ['>', 18], 'type' => ['in', ['a', 'b']]); any other array is treated as a value, so a plain list ('name' => ['a', 'b']) becomes an IN condition. The operator is matched case-insensitively.

License

BSD-3-Clause.

About

Type-safe specification pattern for Yiisoft DB - composite AND/OR/NOT conditions, ORDER BY, LIMIT with sql injection protection

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages