1: <?php declare(strict_types=1);
2:
3: namespace Salient\Core\Concern;
4:
5: use Salient\Contract\Core\Facade\FacadeAwareInterface;
6: use Salient\Contract\Core\Facade\FacadeInterface;
7: use Salient\Contract\Core\Instantiable;
8: use Salient\Utility\Get;
9:
10: /**
11: * Maintains a list of facades the instance is being used by
12: *
13: * @api
14: *
15: * @template TService of Instantiable
16: *
17: * @phpstan-require-implements FacadeAwareInterface
18: */
19: trait FacadeAwareTrait
20: {
21: /** @var array<class-string<FacadeInterface<TService>>,class-string<FacadeInterface<TService>>> */
22: private array $Facades = [];
23:
24: /**
25: * @param class-string<FacadeInterface<TService>> $facade
26: */
27: public function withFacade(string $facade)
28: {
29: $this->Facades[Get::fqcn($facade)] = $facade;
30: return $this;
31: }
32:
33: /**
34: * @param class-string<FacadeInterface<TService>> $facade
35: */
36: public function withoutFacade(string $facade, bool $unloading)
37: {
38: if ($unloading) {
39: unset($this->Facades[Get::fqcn($facade)]);
40: }
41: return $this;
42: }
43:
44: /**
45: * Unload any facades where the object is the underlying instance
46: */
47: protected function unloadFacades(): void
48: {
49: if (!$this->Facades) {
50: return;
51: }
52:
53: foreach ($this->Facades as $fqcn => $facade) {
54: if ($facade::isLoaded() && $facade::getInstance() === $this) {
55: $facade::unload();
56: }
57: unset($this->Facades[$fqcn]);
58: }
59: }
60: }
61: