From 356bb34a09df979756a88b6a0821eacb967ff640 Mon Sep 17 00:00:00 2001 From: SonyPradana Date: Sat, 29 Jun 2024 10:27:05 +0700 Subject: [PATCH] feat: improve facade create instance - `Facade::class` use `Application::make()` instead of `Application::get()` to make more consistent --- src/System/Support/Facades/Facade.php | 22 ++++++++++++++-------- tests/Support/Facades/FacadeTest.php | 20 +++++++++++++++++++- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/src/System/Support/Facades/Facade.php b/src/System/Support/Facades/Facade.php index bec20b04..d6875ea2 100644 --- a/src/System/Support/Facades/Facade.php +++ b/src/System/Support/Facades/Facade.php @@ -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 */ - protected static $instance; + protected static $instance = []; /** * Set Accessor. @@ -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; } @@ -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 = []; } /** diff --git a/tests/Support/Facades/FacadeTest.php b/tests/Support/Facades/FacadeTest.php index 46efc16a..e1c0156e 100644 --- a/tests/Support/Facades/FacadeTest.php +++ b/tests/Support/Facades/FacadeTest.php @@ -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()); + } } }