Skip to content

Commit

Permalink
improve Model::$with phpdoc type
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek committed Jan 16, 2022
1 parent 277c607 commit 6c64608
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ class Model implements \IteratorAggregate
/** @var array Array of set order by. */
public $order = [];

/** @var array Array of WITH cursors set. */
/** @var array<string, array{'model': Model, 'mapping': array<int|string, string>, 'recursive': bool}> */
public $with = [];

/**
Expand Down Expand Up @@ -1075,7 +1075,7 @@ public function withId($id)
public function addWith(self $model, string $alias, array $mapping = [], bool $recursive = false)
{
if (isset($this->with[$alias])) {
throw (new Exception('With cursor already set with this alias'))
throw (new Exception('With cursor already set with given alias'))
->addMoreInfo('alias', $alias);
}

Expand Down
11 changes: 5 additions & 6 deletions src/Persistence/Sql.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,6 @@ public function initQuery(Model $model): Query
);
}

// add With cursors
$this->initWithCursors($model, $query);

return $query;
Expand All @@ -223,11 +222,12 @@ public function initQuery(Model $model): Query
*/
public function initWithCursors(Model $model, Query $query): void
{
if (!$with = $model->with) {
$with = $model->with;
if (count($with) === 0) {
return;
}

foreach ($with as $alias => ['model' => $withModel, 'mapping' => $withMapping, 'recursive' => $recursive]) {
foreach ($with as $alias => ['model' => $withModel, 'mapping' => $withMapping, 'recursive' => $withRecursive]) {
// prepare field names
$fieldsFrom = $fieldsTo = [];
foreach ($withMapping as $from => $to) {
Expand All @@ -237,14 +237,13 @@ public function initWithCursors(Model $model, Query $query): void

// prepare sub-query
if ($fieldsFrom) {
$withModel->setOnlyFields($fieldsFrom);
$withModel->setOnlyFields($fieldsFrom); // TODO this mutates model state
}
// 2nd parameter here strictly define which fields should be selected
// as result system fields will not be added if they are not requested
$subQuery = $withModel->action('select', [$fieldsFrom]);

// add With cursor
$query->with($subQuery, $alias, $fieldsTo ?: null, $recursive);
$query->with($subQuery, $alias, $fieldsTo ?: null, $withRecursive);
}
}

Expand Down

0 comments on commit 6c64608

Please sign in to comment.