Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improve facade create instance #357

Merged
merged 1 commit into from
Jun 29, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
22 changes: 14 additions & 8 deletions src/System/Support/Facades/Facade.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ abstract class Facade
{
/**
* Application accessor.
*
* @var Application
*/
protected static $app;
protected static ?Application $app = null;

/**
* Instance accessor.
*
* @var mixed
* @var array<string, mixed>
*/
protected static $instance;
protected static $instance = [];

/**
* Set Accessor.
Expand All @@ -35,7 +33,7 @@ public function __construct(Application $app)
/**
* Set facade intance.
*/
public static function setFacadeBase(Application $app): void
public static function setFacadeBase(?Application $app = null): void
{
static::$app = $app;
}
Expand Down Expand Up @@ -71,11 +69,19 @@ protected static function getFacade()
*/
protected static function getFacadeBase(string $name)
{
if (isset(static::$instance[$name])) {
if (array_key_exists($name, static::$instance)) {
return static::$instance[$name];
}

return static::$instance[$name] = static::$app->get($name);
return static::$instance[$name] = static::$app->make($name);
}

/**
* Clear all of the instances.
*/
public static function flushInstance(): void
{
static::$instance = [];
}

/**
Expand Down
20 changes: 19 additions & 1 deletion tests/Support/Facades/FacadeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,27 @@ final public function itCanCallstatic()
$app = new Application(__DIR__);
$app->set(Collection::class, fn () => new Collection(['php' => 'greate']));

require_once __DIR__ . DIRECTORY_SEPARATOR . 'Sample' . DIRECTORY_SEPARATOR . 'FacadesTestClass.php';
Facade::setFacadeBase($app);
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Sample' . DIRECTORY_SEPARATOR . 'FacadesTestClass.php';

$this->assertTrue(FacadesTestClass::has('php'));
$app->flush();
Facade::flushInstance();
}

/**
* @test
*/
public function itThrowErrorWhenApplicationNotSet()
{
require_once __DIR__ . '/Sample/FacadesTestClass.php';

Facade::flushInstance();
Facade::setFacadeBase(null);
try {
FacadesTestClass::has('php');
} catch (Throwable $th) {
$this->assertEquals('Call to a member function make() on null', $th->getMessage());
}
}
}
Loading