Skip to content

Commit

Permalink
Adapt AbstractMain to ShouldLoadInCliContext
Browse files Browse the repository at this point in the history
Changes registerServices() so it only additionally loads ShouldLoadInCliContext annotated classes if and only if under WP-CLI.
  • Loading branch information
mbmjertan committed Oct 17, 2024
1 parent 57bbf20 commit 164813f
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/Main/AbstractMain.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
use DI\ContainerBuilder;
use DI\Definition\Helper\AutowireDefinitionHelper;
use DI\Definition\Reference;
use EightshiftLibs\ClassAttributes\ShouldLoadInCliContext;
use EightshiftLibs\Services\ServiceInterface;
use EightshiftLibs\Services\ServiceCliInterface;
// phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse
use Exception;
use ReflectionClass;

/**
* The main start class.
Expand Down Expand Up @@ -71,14 +73,29 @@ public function registerServices()
\array_walk(
$this->services,
function ($class) {
// Load services classes but not in the WP-CLI env.
// Load services classes but not in the WP-CLI env, unless they have the ShouldLoadInCliContext attr.
if (!\defined('WP_CLI') && $class instanceof ServiceInterface) {
$class->register();
}

// Load services CLI classes only in WP-CLI env.
if (\defined('WP_CLI') && $class instanceof ServiceCliInterface) {
$class->register();
if (\defined('WP_CLI')) {
if ($class instanceof ServiceCliInterface) {
// Classes implementing ServiceCliInterface should be loaded only in CLI contexts.
$class->register();
return;
}

// Allow loading service classes in CLI contexts if it
// or a parent class has ShouldLoadInCliContext attribute.
$reflection = new ReflectionClass($class);
while ($reflection) {
if (\count($reflection->getAttributes(ShouldLoadInCliContext::class))) {
$class->register();
return;
}

$reflection = $reflection->getParentClass();
}
}
}
);
Expand Down

0 comments on commit 164813f

Please sign in to comment.