Skip to content

Commit

Permalink
feat: improve facade create instance
Browse files Browse the repository at this point in the history
- `Facade::class` use `Application::make()` instead of `Application::get()` to make more consistent
  • Loading branch information
SonyPradana committed Jun 29, 2024
1 parent 6c95f6a commit 356bb34
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
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());
}
}
}

0 comments on commit 356bb34

Please sign in to comment.