Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better CLI loading for ServiceInterface implementations #438

Merged
merged 3 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/ClassAttributes/ShouldLoadInCliContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/**
* An attribute class used to indicate a ServiceInterface should be loaded in WP-CLI.
*
* @package EightshiftLibs\ClassAttributes
*/

namespace EightshiftLibs\ClassAttributes;

use Attribute;

/**
* A class attribute definition class, inspected with Reflection when setting up services for DI in Main.
* ServiceInterface classes annotated with this attribute should be loaded in the CLI context as well,
* although they don't have to implement ServiceCliInterface themselves.
*/
#[Attribute]
class ShouldLoadInCliContext
{
}
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