Skip to content

Instantly share code, notes, and snippets.

@coisa
Last active November 5, 2022 06:56
Show Gist options
  • Select an option

  • Save coisa/9ed9262f71ed1b20df4e0b95b8437049 to your computer and use it in GitHub Desktop.

Select an option

Save coisa/9ed9262f71ed1b20df4e0b95b8437049 to your computer and use it in GitHub Desktop.
<?php
namespace CoiSA\Facade;
abstract class AbstractFacade implements FacadeInterface
{
use FacadeTrait;
}
<?php
namespace CoiSA\Facade;
class Example extends AbstractFacade
{
protected static function test(): string
{
echo 'Test' . PHP_EOL;
}
}
$mockedObject = new class() extends Example
{
protected static function test(): string
{
echo 'Test Mock' . PHP_EOL;
}
}
Example::test(); // outputs Test
Example::setMockedObject($mockedObject);
Example::test(); // outputs Test Mock
class ExampleMock extends Example
{
private static string $suffix;
public function __construct(string $suffix = '')
{
static::$suffix = $suffix;
}
protected static function test(): string
{
echo 'Another Mock ' . static::$suffix . PHP_EOL;
}
}
$mockedObject = new ExampleMock();
Example::setMockedObject($mockedObject);
Example::test(); // outputs Another Mock
$mockedObject = new ExampleMock('With Suffix');
Example::setMockedObject($mockedObject);
Example::test(); // outputs Another Mock With Suffix
<?php
namespace CoiSA\Facade;
interface FacadeInterface
{
public static function setMockedObject(self $mockedFacadeObject): void;
}
<?php
namespace CoiSA\Facade;
use CoiSA\Factory\ValueFactory;
use CoiSA\Singleton\Singleton;
trait FacadeTrait
{
final public static function __callStatic($method, array $args = [])
{
$singleton = Singleton::getInstance(static::class);
return call_user_func_array([$singleton, $method], $args);
}
final public function setMockedObject(self $mockedFacadeObject)
{
Singleton::setFactory(static::class, new ValueFactory($mockFacadeObject));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment