$class Not a field of the covariant template; kept for IDE inference. */ public function __construct( private readonly Connection $connection, private readonly string $class, private readonly Dialect $dialect = new MySqlDialect(), private readonly ?Persister $persister = null, ) { $this->builder = new QueryBuilder($this->dialect); $this->metadata(); } public function metadata(): ClassMetadata { return Model::metadataFor($this->class); } /** * @param array $criteria * @param list $order * @param true|array|false $with * @return list */ public function find( array $criteria = [], array $order = [], ?int $limit = null, ?int $offset = null, bool|array $with = false, ): array { $compiled = $this->builder->select($this->metadata(), $criteria, $order, $limit, $offset); $rows = $this->connection->select($compiled['sql'], $compiled['params']); return $this->hydrateRows($rows, null, $with === false ? false : $with); } /** * @param array $criteria * @param list $order * @param true|array|false $with * @return T|null */ public function findFirst( array $criteria = [], array $order = [], bool|array $with = false, ): ?Model { $rows = $this->find($criteria, $order, 1, null, $with); return $rows[0] ?? null; } /** * @param true|array|false $with * @return T|null */ public function findByPk(int|string $pk, bool|array $with = false): ?Model { return $this->findFirst([$this->metadata()->primaryKey() => $pk], [], $with); } /** * @param true|array|false $with * @return T */ public function findByPkOrFail(int|string $pk, bool|array $with = false): Model { $model = $this->findByPk($pk, $with); if ($model === null) { throw RecordNotFoundException::byPrimaryKey($this->class, $pk); } return $model; } /** * @param array $criteria * @param array $values * @return T */ public function findOrCreate(array $criteria, array $values = []): Model { $found = $this->findFirst($criteria); if ($found !== null) { return $found; } return $this->create($values + $criteria); } /** * @param array $criteria */ public function count(array $criteria = []): int { $compiled = $this->builder->count($this->metadata(), $criteria); return (int) $this->connection->scalar($compiled['sql'], $compiled['params']); } /** * @param array $criteria */ public function exists(array $criteria = []): bool { return $this->count($criteria) > 0; } /** * @param array $criteria */ public function sum(string $column, array $criteria = []): float { return (float) ($this->aggregate('SUM', $column, $criteria) ?? 0.0); } /** * @param array $criteria */ public function avg(string $column, array $criteria = []): float { return (float) ($this->aggregate('AVG', $column, $criteria) ?? 0.0); } /** * @param array $criteria */ public function max(string $column, array $criteria = []): ?float { return $this->aggregate('MAX', $column, $criteria); } /** * @param array $criteria */ public function min(string $column, array $criteria = []): ?float { return $this->aggregate('MIN', $column, $criteria); } /** * @param array $criteria * @param list $order */ public function page( array $criteria = [], array $order = [], int $page = 1, int $perPage = 20, ): Page { $query = $this->query(); foreach ($criteria as $column => $value) { $query = $query->where((string) $column, $value); } foreach ($order as [$column, $direction]) { $query = $query->orderBy($column, $direction); } return $query->page($page, $perPage); } public function query(): Query { return Query::start( $this, new QueryState($this->metadata()), $this->connection, $this->builder, ); } /** * @return int|string */ public function save(Model $model): int|string { return $this->persister()->save($model); } /** * Builds a new model from $values and inserts it. * * `hydrate()` deliberately skips #[Guarded] properties, which is right for request payloads but * wrong here: this method is called from trusted server code (a seeder, a service), and a guarded * column such as a password hash would otherwise be silently dropped. Guarded values are applied * after hydration, so `create()` can persist every column it is given. * * @param array $values * @return T */ public function create(array $values = []): Model { /** @var T $model */ $model = new $this->class(); $model->hydrate($values); $metadata = $this->metadata(); foreach ($values as $key => $value) { $property = $metadata->resolveProperty((string) $key); if ($property === null) { continue; } $definition = $metadata->propertyMetadata($property); if ($definition->guarded && !$definition->ignored && !$definition->primaryKey) { $model->set($property, $model->castFor($definition, $value)); } } $this->persister()->insert($model); return $model; } public function update(Model $model): void { $this->persister()->update($model); } public function delete(Model $model): void { $this->persister()->delete($model); } /** * @param array $values keyed by property or column */ public function patch(int|string $pk, array $values): void { $this->persister()->patch($this->instance(), $pk, $values); } public function remove(int|string $pk): bool { return $this->persister()->remove($this->instance(), $pk); } /** * Loads the declared relationships of an already hydrated model into the instance. * * @param list $only empty means every declared relationship */ public function refreshRelations(Model $model, array $only = []): void { $this->loadRelationsInto([$model], $only === [] ? true : $only, 0); } /** * Hydrates database rows into models and applies eager loading. * * @internal used by Query * @param list> $rows * @param list|null $columns properties actually selected * @param true|array|false $with * @return list */ public function hydrateRows(array $rows, ?array $columns, bool|array $with): array { $models = $this->hydrate($rows); if ($columns !== null && $columns !== []) { foreach ($models as $model) { $model->markPartial(); } } if ($with !== false && $with !== []) { $this->loadRelationsInto($models, $with, 0); } return $models; } /** * @internal * @param list> $rows * @return list */ public function hydrate(array $rows): array { $metadata = $this->metadata(); $models = []; foreach ($rows as $row) { /** @var T $model */ $model = new $this->class(); foreach ($row as $column => $value) { $property = $metadata->property((string) $column); if ($property === null) { continue; } $model->set($property, $this->castDatabaseValue( $metadata->properties()[$property], $value, )); } $models[] = $model; } return $models; } private function castDatabaseValue(PropertyMetadata $definition, mixed $value): mixed { if ($value === null) { return null; } if ($definition->enumClass !== null) { return TypeCaster::castEnum($value, $definition->enumClass, true, $definition->name); } return TypeCaster::cast($value, $definition->type, true, $definition->name); } /** * @param array $criteria */ private function aggregate(string $function, string $column, array $criteria): ?float { $compiled = $this->builder->aggregate($this->metadata(), $column, $function, $criteria); $value = $this->connection->scalar($compiled['sql'], $compiled['params']); return $value === null ? null : (float) $value; } private function persister(): Persister { if ($this->persister !== null) { return $this->persister; } return new Persister($this->connection, $this->builder); } private function instance(): Model { /** @var T $model */ $model = new $this->class(); return $model; } /** * @param list $models * @param true|array|false $with */ private function loadRelationsInto(array $models, bool|array $with, int $depth): void { if ($with === false) { return; } $metadata = $this->metadata(); $requested = $this->resolveRequestedRelations($metadata, $with); // Validate every requested path up front: a typo must fail even when no rows matched. foreach ($requested as $request) { $this->validateRelationPath( $metadata, $request['name'], $request['nested'], $depth + 1, ); } if ($models === []) { return; } if (($depth + 1) > self::MAX_RELATION_DEPTH) { throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH); } foreach ($requested as $requested) { $relation = $this->relationMetadata($requested['name']); $nested = $requested['nested']; $this->loadOneRelation($models, $relation, $metadata); if ($nested === []) { continue; } $loaded = []; foreach ($models as $model) { /** @var mixed $value */ $value = $model->get($relation->name); if ($value instanceof Model) { $loaded[] = $value; } if (is_array($value)) { foreach ($value as $related) { if (!$related instanceof Model) { continue; } $loaded[] = $related; } } } $relatedMeta = $relation->relation; if ($relatedMeta === null) { continue; } $relatedRepository = $this->relatedRepository($relatedMeta->relatedClass); $relatedRepository->loadRelationsInto($loaded, $nested, $depth + 1); } } /** * @param list $models */ private function loadOneRelation( array $models, PropertyMetadata $property, ClassMetadata $metadata, ): void { $relation = $property->relation; if ($relation === null) { return; } if ($relation->kind === RelationMetadata::KIND_BELONGS_TO_MANY) { $this->loadBelongsToMany($models, $property); return; } if ($relation->kind === RelationMetadata::KIND_BELONGS_TO) { $this->loadBelongsTo($models, $property, $metadata); return; } $this->loadHasManyOrOne($models, $property); } /** * @param list $models */ private function loadBelongsTo( array $models, PropertyMetadata $property, ClassMetadata $metadata, ): void { $relation = $property->relation; \assert($relation !== null); $foreignProperty = $metadata->resolveProperty($relation->foreignKey); if ($foreignProperty === null) { throw MetadataException::missingForeignKey( $metadata->class, $property->name, $relation->foreignKey, ); } $keys = []; foreach ($models as $model) { $value = $model->get($foreignProperty); if ($value !== null && $value !== '') { $keys[(string) $value] = $value; } } $relatedRepository = $this->relatedRepository($relation->relatedClass); $relatedMetadata = $relatedRepository->metadata(); $found = []; if ($keys !== []) { $records = $relatedRepository->find([ $relatedMetadata->primaryKey() => array_values($keys), ]); foreach ($records as $record) { $found[(string) $record->get($relatedMetadata->primaryKey())] = $record; } } foreach ($models as $model) { $value = $model->get($foreignProperty); if ($value === null || $value === '') { continue; } $model->set($property->name, $found[(string) $value] ?? null); } } /** * @param list $models */ private function loadHasManyOrOne(array $models, PropertyMetadata $property): void { $relation = $property->relation; \assert($relation !== null); $metadata = $this->metadata(); $ownerKey = $metadata->primaryKey(); $keys = []; foreach ($models as $model) { $value = $model->get($ownerKey); if ($value !== null && $value !== '') { $keys[(string) $value] = $value; } } $relatedRepository = $this->relatedRepository($relation->relatedClass); $relatedMetadata = $relatedRepository->metadata(); $grouped = []; if ($keys !== []) { $records = $relatedRepository->find([ $relation->foreignKey => array_values($keys), ]); foreach ($records as $record) { $grouped[(string) $record->get($relation->foreignKey)][] = $record; } } foreach ($models as $model) { $key = (string) $model->get($ownerKey); $matches = $grouped[$key] ?? []; if ($relation->isToMany()) { $model->set($property->name, $matches); continue; } $model->set($property->name, $matches[0] ?? null); } } /** * @param list $models */ private function loadBelongsToMany(array $models, PropertyMetadata $property): void { $relation = $property->relation; \assert($relation !== null); \assert($relation->through !== null); \assert($relation->foreignPivotKey !== null); \assert($relation->relatedPivotKey !== null); $metadata = $this->metadata(); $ownerKey = $metadata->primaryKey(); $keys = []; foreach ($models as $model) { $value = $model->get($ownerKey); if ($value !== null && $value !== '') { $keys[(string) $value] = $value; } } if ($keys === []) { foreach ($models as $model) { $model->set($property->name, []); } return; } $pivot = $this->dialect->quoteIdentifier($relation->through); $foreignPivot = $this->dialect->quoteIdentifier($relation->foreignPivotKey); $relatedPivot = $this->dialect->quoteIdentifier($relation->relatedPivotKey); $placeholders = implode(', ', array_fill(0, count($keys), '?')); $sql = 'SELECT ' . $foreignPivot . ' AS pivot_owner, ' . $relatedPivot . ' AS pivot_related' . ' FROM ' . $pivot . ' WHERE ' . $foreignPivot . ' IN (' . $placeholders . ')'; $rows = $this->connection->select($sql, array_values($keys)); $relatedRepository = $this->relatedRepository($relation->relatedClass); $relatedMetadata = $relatedRepository->metadata(); $grouped = []; $relatedKeys = []; foreach ($rows as $row) { if (!isset($row['pivot_owner'], $row['pivot_related'])) { continue; } $ownerId = (string) $row['pivot_owner']; $relatedId = (string) $row['pivot_related']; $grouped[$ownerId][] = $relatedId; $relatedKeys[$relatedId] = $row['pivot_related']; } $records = []; if ($relatedKeys !== []) { foreach ($relatedRepository->find([ $relatedMetadata->primaryKey() => array_values($relatedKeys), ]) as $record) { $records[(string) $record->get($relatedMetadata->primaryKey())] = $record; } } foreach ($models as $model) { $ownerId = (string) $model->get($ownerKey); $related = []; foreach ($grouped[$ownerId] ?? [] as $relatedId) { if (!isset($records[$relatedId])) { continue; } $related[] = $records[$relatedId]; } $model->set($property->name, $related); } } /** * @param true|array|list $with * @return list|array}> */ private function resolveRequestedRelations(ClassMetadata $metadata, bool|array $with): array { $requested = []; if ($with === true) { foreach ($metadata->relations() as $relation) { $requested[] = ['name' => $relation->name, 'nested' => []]; } return $requested; } foreach ($with as $key => $value) { if (is_int($key)) { $path = (string) $value; $segments = explode('.', $path); $name = $segments[0]; $nested = array_slice($segments, 1); // Remaining segments are one nested path, not sibling relations. $requested[] = [ 'name' => $name, 'nested' => $nested === [] ? [] : [implode('.', $nested)], ]; continue; } $nestedValue = $value === true || is_array($value) ? $value : []; $requested[] = ['name' => (string) $key, 'nested' => $nestedValue]; } return $requested; } private function relationMetadata(string $name): PropertyMetadata { $metadata = $this->metadata(); if (!$metadata->hasProperty($name) || $metadata->properties()[$name]->relation === null) { throw MetadataException::unknownRelation($this->class, $name); } return $metadata->properties()[$name]; } /** * Walks a requested path, validating every hop and enforcing the depth limit. * * @param true|array|list $nested */ private function validateRelationPath( ClassMetadata $metadata, string $name, bool|array $nested, int $depth, ): void { if ($depth > self::MAX_RELATION_DEPTH) { throw ConfigurationException::relationDepthExceeded(self::MAX_RELATION_DEPTH); } $relation = $metadata->hasProperty($name) ? $metadata->properties()[$name]->relation : null; if ($relation === null) { throw MetadataException::unknownRelation($metadata->class, $name); } if ($nested === true) { return; } $next = $this->relatedRepository($relation->relatedClass)->metadata(); foreach ($nested as $key => $value) { if (is_int($key)) { $segments = explode('.', (string) $value); $this->validateRelationPath( $next, $segments[0], array_slice($segments, 1), $depth + 1, ); continue; } $this->validateRelationPath( $next, (string) $key, is_array($value) ? $value : true, $depth + 1, ); } } /** * @param class-string $class * @return Repository */ private function relatedRepository(string $class): self { return new self($this->connection, $class, $this->dialect, $this->persister); } /** * @internal */ public function connection(): Connection { return $this->connection; } }