Skip to content

Commit

Permalink
修复对象在 __init() 方法中初始化时抛出异常,对象还能被正常使用的问题 (#666)
Browse files Browse the repository at this point in the history
* 修复对象在 __init() 方法中初始化时抛出异常,对象还能被正常使用的问题

* 修复
  • Loading branch information
Yurunsoft authored Dec 18, 2023
1 parent e462020 commit f8dff84
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/Bean/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,16 +170,32 @@ private function __newInstance(string $id, array $params, bool $allowStore)

if ($data['recursion'] ?? true)
{
// @phpstan-ignore-next-line
BeanFactory::initInstance($object, $params, $originId);
if ($stored && $object !== $beanObjects[$originId])
if ($stored)
{
// 防止类 __init() 方法有协程上下文切换,导致单例被覆盖
return $beanObjects[$originId];
try
{
BeanFactory::initInstance($object, $params, $originId);
if ($object !== $beanObjects[$originId])
{
// 防止类 __init() 方法有协程上下文切换,导致单例被覆盖
return $beanObjects[$originId];
}
}
catch (\Throwable $th)
{
if ($object === $beanObjects[$originId])
{
unset($beanObjects[$originId]);
}
throw $th;
}
}
else
{
BeanFactory::initInstance($object, $params, $originId);
}
}

// @phpstan-ignore-next-line
return $object;
}

Expand Down Expand Up @@ -272,7 +288,6 @@ public function getSingleton(string $id, ...$params)
$singletonObjects[$originId] = $object;
}

// @phpstan-ignore-next-line
return $object;
}

Expand Down
30 changes: 30 additions & 0 deletions tests/unit/Component/Bean/InitClass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace Imi\Test\Component\Bean;

use Imi\App;

class InitClass
{
private bool $throw;

public function __construct()
{
$this->throw = App::get('InitClass.throw');
}

public function __init(): void
{
if ($this->throw)
{
throw new \RuntimeException('gg');
}
}

public function isThrow(): bool
{
return $this->throw;
}
}
18 changes: 18 additions & 0 deletions tests/unit/Component/Tests/BeanTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Imi\Test\Component\Bean\BeanA;
use Imi\Test\Component\Bean\BeanB;
use Imi\Test\Component\Bean\BeanC;
use Imi\Test\Component\Bean\InitClass;
use Imi\Test\Component\Enum\TestEnumBean;
use Imi\Test\Component\Enum\TestEnumBeanBacked;
use Imi\Util\Imi;
Expand Down Expand Up @@ -441,6 +442,23 @@ public function testEnumBean(): void
$this->assertEquals(TestEnumBeanBacked::B, $bean->getEnum3());
}

public function testInitThrow(): void
{
App::set('InitClass.throw', true);
try
{
App::getBean(InitClass::class);
}
catch (\Throwable $th)
{
$this->assertEquals('gg', $th->getMessage());
}

App::set('InitClass.throw', false);
$object = App::getBean(InitClass::class);
$this->assertFalse($object->isThrow());
}

// @phpstan-ignore-next-line
private function test1(): self
{
Expand Down

0 comments on commit f8dff84

Please sign in to comment.