Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 24 additions & 8 deletions src/Illuminate/Container/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public function resolved($abstract)
* @param string $abstract
* @return bool
*/
public function isShared($abstract)
public function isShared($abstract)
{
if (isset($this->instances[$abstract])) {
return true;
Expand All @@ -281,23 +281,39 @@ public function isShared($abstract)
return false;
}

$reflection = new ReflectionClass($abstract);

if (! empty($reflection->getAttributes(Singleton::class))) {
return true;
if ($scopedType = $this->getScopedTyped(new ReflectionClass($abstract)) === null) {
return false;
}

if (! empty($reflection->getAttributes(Scoped::class))) {
if ($scopedType === 'scoped') {
if (! in_array($abstract, $this->scopedInstances, true)) {
$this->scopedInstances[] = $abstract;
}
}

return true;
return true;
}

/**
* Determine if a ReflectionClass has scoping attributes applied.
*
* @param ReflectionClass<object> $reflection
* @return "singleton"|"scoped"|null
*/
protected function getScopedTyped(ReflectionClass $reflection): ?string
{
if (! empty($reflection->getAttributes(Singleton::class))) {
return 'singleton';
}

return false;
if (! empty($reflection->getAttributes(Scoped::class))) {
return 'scoped';
}

return null;
}


/**
* Determine if a given string is an alias.
*
Expand Down
22 changes: 22 additions & 0 deletions tests/Container/ContainerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,17 @@ public function testNoMatchingEnvironmentAndNoWildcardThrowsBindingResolutionExc
$container->make(ProdEnvOnlyInterface::class);
}

public function testScopedSingletonWithBind()
{
$container = new Container;
$container->resolveEnvironmentUsing(fn ($environments) => true);

$original = $container->make(HasScope::class);
$new = $container->make(HasScope::class);

$this->assertSame($original, $new);
}

// public function testContainerCanCatchCircularDependency()
// {
// $this->expectException(\Illuminate\Contracts\Container\CircularDependencyException::class);
Expand Down Expand Up @@ -1131,3 +1142,14 @@ class OriginalConcrete implements OverrideInterface
class AltConcrete implements OverrideInterface
{
}


#[Bind(HasScopeConcrete::class)]
#[Scoped]
interface HasScope
{
}

class HasScopeConcrete implements HasScope
{
}
Loading