Skip to content

Commit

Permalink
Fix Model::__call throwing BadMethodCallException on empty results
Browse files Browse the repository at this point in the history
* fix: fixed builder method call when fail parent::__call.

* test: add test for Model::AffectedRows.

* style: ./vendor/bin/php-cs-fixer fix --verbose --diff

* docs: fix issue link.

* refactor: I made sure not to call magic method in the parent class.

* style: composer cs-fix

* style: removed unnecessary variable.

* docs: $this|null -> mixed
  • Loading branch information
ytetsuro authored Sep 30, 2021
1 parent 5d4f89d commit aff1f3a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 13 deletions.
21 changes: 8 additions & 13 deletions system/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -710,24 +710,19 @@ public function __isset(string $name): bool
* Provides direct access to method in the builder (if available)
* and the database connection.
*
* @return $this|null
* @return mixed
*/
public function __call(string $name, array $params)
{
$result = parent::__call($name, $params);
$builder = $this->builder();
$result = null;

if ($result === null && method_exists($builder = $this->builder(), $name)) {
if (method_exists($this->db, $name)) {
$result = $this->db->{$name}(...$params);
} elseif (method_exists($builder, $name)) {
$result = $builder->{$name}(...$params);
}

if (empty($result)) {
if (! method_exists($this->builder(), $name)) {
$className = static::class;

throw new BadMethodCallException('Call to undefined method ' . $className . '::' . $name);
}

return $result;
} else {
throw new BadMethodCallException('Call to undefined method ' . static::class . '::' . $name);
}

if ($result instanceof BaseBuilder) {
Expand Down
35 changes: 35 additions & 0 deletions tests/system/Models/AffectedRowsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Models;

use Tests\Support\Models\UserModel;

/**
* @internal
*/
final class AffectedRowsTest extends LiveModelTestCase
{
/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/5137
*/
public function testAffectedRowsWithEmptyUpdate(): void
{
$this->createModel(UserModel::class);
$notExistsId = -1;
$this->model
->set('country', 'US')
->where('id', $notExistsId)
->update();

$this->assertSame(0, $this->model->affectedRows());
}
}

0 comments on commit aff1f3a

Please sign in to comment.