Skip to content

Commit

Permalink
Merge pull request #9 from formal-php/optimize-any-none
Browse files Browse the repository at this point in the history
Optimize `Repository::any()` and `Repository::none()`
  • Loading branch information
Baptouuuu authored Feb 10, 2024
2 parents d69cad1 + 8a90a55 commit e7f0bfd
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Added

- You can match aggregates on collections via `Formal\ORM\Specification\Child`
- `Formal\ORM\Adapter\Repository::any()`

### Changed

Expand Down
11 changes: 11 additions & 0 deletions src/Adapter/Filesystem/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,17 @@ public function size(Specification $specification = null): int
->size();
}

public function any(Specification $specification = null): bool
{
return $this
->fetch($specification, null, null, 1)
->first()
->match(
static fn() => true,
static fn() => false,
);
}

/**
* @return Sequence<Aggregate>
*/
Expand Down
2 changes: 2 additions & 0 deletions src/Adapter/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,6 @@ public function fetch(
* @return 0|positive-int
*/
public function size(Specification $specification = null): int;

public function any(Specification $specification = null): bool;
}
18 changes: 18 additions & 0 deletions src/Adapter/SQL/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,22 @@ public function size(Specification $specification = null): int
static fn() => 0,
);
}

public function any(Specification $specification = null): bool
{
$count = $this
->mainTable
->count($specification)
->limit(1);

return ($this->connection)($count)
->first()
->flatMap(static fn($row) => $row->column('count'))
->filter(\is_numeric(...))
->map(static fn($count) => (int) $count)
->match(
static fn($count) => $count !== 0,
static fn() => false,
);
}
}
7 changes: 5 additions & 2 deletions src/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,12 +190,15 @@ public function size(Specification $specification = null): int

public function any(Specification $specification = null): bool
{
return $this->size($specification) !== 0;
return $this->adapter->any(match ($specification) {
null => null,
default => ($this->normalizeSpecification)($specification),
});
}

public function none(Specification $specification = null): bool
{
return $this->size($specification) === 0;
return !$this->any($specification);
}

/**
Expand Down

0 comments on commit e7f0bfd

Please sign in to comment.