Skip to content

Commit

Permalink
Introduce Package::build() (#33)
Browse files Browse the repository at this point in the history
* Introduce Package::boot()

The new method allows building a container out of the package without
running any `ExecutableModule::run()`, simplifying unit tests.

Passing default modules to `Package::boot()` is now deprecated, for a
better separation of the "building" and "booting" steps, but it
continues to work while emitting a deprecation notice.

There's an edge case in which passing modules to `Package::boot()`
causes an exception, but one of the conditions is that
`Package::container()` was called before `Package::boot()` which
caused an exception before anyway, so the change is 100% backward
compatible.

Two new package statuses have been added:
- `Package::STATUS_MODULES_ADDED`
- `Package::STATUS_READY`

The first is necessary to distinguish the status after `build()`
was called but `boot()` was not.
The second was a missing status between initialized and ready.

Documentation and tests were added.

* Modernize tests code

* Fix tests

* Commit @Biont suggestions

* Move Package's ready status before the ready action

* Do not accept default modules as argument to Package::boot()

Props @Chrico

Also, make sure failures inside `build()` are caught the same way they
are in `boot()`, and introduce a "failed build" action hook as the
counterpart of the "failed boot" action hook.

* Catch failures in `addModule()` and `connect()`

Implement a uniform "failure flow", catching all the errors when debug
is off, and collecting them in a Throwable's "previous" hierarchy.

All the application flows are documented in a separate document.

Fix and add new tests for all the flows.

* Applicaton-flow.md // fix wrong formatting

Signed-off-by: Christian Leucht <3417446+Chrico@users.noreply.github.com>

* Use Package::statusIs() instead of === comparison

* Update for phpunit (#31)

* Update for phpunit

This allows to update phpunit/phpunit with it's dependencies to 8 to 9 and correctly work with PHP8.*

* phpunit 8 & 9

To satisfy PHP7.2 requirement we need to have dual version of PHP.

phpunit-update

* Remove unnecessary asset

* Increase test coverage, adapt to PHPUnit 9

---------

Signed-off-by: Christian Leucht <3417446+Chrico@users.noreply.github.com>
Co-authored-by: Christian Leucht <3417446+Chrico@users.noreply.github.com>
Co-authored-by: Gene Surov <esurov@gmail.com>
  • Loading branch information
3 people authored May 26, 2023
1 parent cc91569 commit 0bde4d1
Show file tree
Hide file tree
Showing 12 changed files with 1,131 additions and 256 deletions.
6 changes: 4 additions & 2 deletions .github/workflows/php-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ jobs:
uses: actions/checkout@v3

- name: Use coverage?
if: ${{ (matrix.php-versions == '7.4') && (matrix.dependency-versions == 'highest') && (matrix.container-versions == '^2') }}
if: ${{ (matrix.php-versions == '8.0') && (matrix.dependency-versions == 'highest') && (matrix.container-versions == '^2') }}
run: echo "USE_COVERAGE=yes" >> $GITHUB_ENV

- name: Setup PHP
Expand All @@ -46,7 +46,9 @@ jobs:
dependency-versions: ${{ matrix.dependency-versions }}

- name: Run unit tests
run: composer tests:${{ ((env.USE_COVERAGE == 'yes') && 'codecov') || 'no-cov' }}
run:
./vendor/bin/phpunit --atleast-version 9 && ./vendor/bin/phpunit --migrate-configuration || echo 'Config does not need updates.'
./vendor/bin/phpunit ${{ ((env.USE_COVERAGE == 'yes') && '--coverage-clover coverage.xml') || '--no-coverage' }}

- name: Update coverage
if: ${{ env.USE_COVERAGE == 'yes' }}
Expand Down
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@
"@psalm"
],
"tests": "@php ./vendor/phpunit/phpunit/phpunit",
"tests:codecov": "@php ./vendor/phpunit/phpunit/phpunit --coverage-clover coverage.xml",
"tests:no-cov": "@php ./vendor/phpunit/phpunit/phpunit --no-coverage"
},
"config": {
Expand Down
100 changes: 100 additions & 0 deletions docs/Applicaton-flow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# The application flow

Modularity implements its application flow in two stages:

- First, the application's dependencies tree is "composed" by collecting services declared in modules, adding sub-containers, and connecting other applications.
- After that, the application dependency tree is locked, and the services are "consumed" to execute their behavior.

The `Package` class implements the two stages above, respectively, in the two methods:

- **`Package::build()`**
- **`Package::boot()`**

For convenience, `Package::boot()` is "smart enough" to call `build()` if it was not called before, so the following code (that makes the two stages evident):

```php
Package::new($properties)->build()->boot();
```

is entirely equivalent to the following:

```php
Package::new($properties)->boot();
```

Both stages are implemented through a series of *steps*, and the application status progresses as the steps are complete. In the process, a few action hooks are fired to allow external code to interact with the flow.

At any point of the flow, by holding an instance of the `Package` is possible to inspect the current status via `Package::statusIs()`, passing as an argument one of the `Package::STATUS_*` constants.


## Building stage

1. Upon instantiation, the `Package` status is at **`Package::STATUS_IDLE`**
2. Default modules can be added by calling **`Package::addModule()`** on the instance.
3. The **`Package::ACTION_INIT`** action hook is fired, passing the package instance as an argument. That allows external code to add modules.
4. The `Package` status moves to **`Package::STATUS_INITIALIZED`**. The "building" stage is completed, and no more modules can be added.


## Booting stage

1. When the booting stage begins, the `Package` status moves to **`Package::STATUS_MODULES_ADDED`**.
2. A read-only PSR-11 container is created. It can lazily resolve the dependency tree defined in the previous stage.
3. **All executables modules run**. That is when all the application behavior happens. Note: Because the container is "lazy", only the consumed services are resolved. The `Package` never executes factory callbacks for services "registered" in the previous stage but not used in this stage.
4. The `Package` status moves to **`Package::STATUS_READY`**.
5. The **`Package::ACTION_READY`** action hook is fired, passing the package instance as an argument. External code hooking that action can access the read-only container instance, resolve services, and perform additional actions but not register modules.
6. The `Package` status moves to **`Package::STATUS_BOOTED`**. The booting stage is completed. `Package::boot()` returns true.


## The "failure flow"

The steps listed above for the two stages represent the "happy paths". If any exception is thrown at any of the steps above, the flows are halted and the "failure flow" starts.

### When the failure starts during the "building" stage

1. The `Package` status moves to **`Package::STATUS_FAILED`**.
2. The **`Package::ACTION_FAILED_BUILD`** action hook is fired, passing the raised `Throwable` as an argument.
3. If the `Package`'s `Properties` instance is in "debug mode" (`Properties::isDebug()` returns `true`), the exception bubbles up, and the flow stops here.
4. If the `Properties` instance is _not_ in "debug mode", the **`Package::ACTION_FAILED_BOOT`** action hook is fired, passing a `Throwable` whose `previous` property is the `Throwable` thrown during the building stage. The "previous hierarchy" could be several levels if during the building stage many failures happened.
5. `Package::boot()` returns false.

### When the failure starts during the "booting" stage

1. The `Package` status moves to **`Package::STATUS_FAILED`**.
2. The **`Package::ACTION_FAILED_BOOT`** action hook is fired, passing the raised `Throwable` as an argument.
3. If the `Package`'s `Properties` instance is in "debug mode" (`Properties::isDebug()` returns `true`), the exception bubbles up, and the flow stops here.
4. `Package::boot()` returns false.


## A note about default modules passed to boot()

The `Package::boot()` method accepts a list of modules. That has been deprecated since Modularity v1.7.

Considering that `Package::boot()` represents the "booting" stage that is supposed to happen *after* the "building" stage, it might be hard to figure out where the addition of those modules fits in the flows described above.

When `Package::boot()` is called without calling `Package::build()` first, as in:

```php
Package::new($properties)->boot(new ModuleOne(), new ModuleTwo());
```

The code is equivalent to the following:

```php
Package::new($properties)->addModule(new ModuleOne())->addModule(new ModuleTwo())->boot();
```

So the "building" flow is respected.

However, when `Package::boot()` is called after `Package::build()`, as in:

```php
Package::new($properties)->build()->boot(new ModuleOne(), new ModuleTwo());
```

The `Package` is at the end of the "building" flow after `Package::build()` is called, but it must "jump" back in the middle of "building" flow to add the modules.

In fact, after `Package::build()` is called the application status is at `Package::STATUS_INITIALIZED`, and no more modules can be added.

However, for backward compatibility reasons, in that case, the `Package` temporarily "hacks" the status back to `Package::STATUS_IDLE` so modules can be added, and then resets it to `Package::STATUS_INITIALIZED` so that the "booting" stage can start as usual.

This "hack" is why passing modules to `Package::boot()` has been deprecated and will be removed in the next major version when backward compatibility breaks are allowed.
128 changes: 91 additions & 37 deletions docs/Package.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ Retrieve the current status of the Application. Following are available:

- `Package::STATUS_IDLE` - before Application is booted.
- `Package::STATUS_INITIALIZED` - after first init action is triggered.
- `Package::STATUS_MODULES_ADDED` - after all modules have been added.
- `Package::STATUS_READY` - after the "ready" action has been fired.
- `Package::STATUS_BOOTED` - Application has successfully booted.
- `Package::STATUS_FAILED_BOOT` - when Application did not boot properly.

Expand Down Expand Up @@ -100,7 +102,7 @@ add_action(
);
```

By providing the `Acme\plugin()`-function, you’ll enable externals to hook into your Application:
By providing the `Acme\plugin()` function, you’ll enable external code to hook into your application:

```php
<?php
Expand All @@ -123,6 +125,94 @@ add_action(
);
```

## Building the package

Sometimes, especially in unit tests, it might be desirable to obtain services as defined for the
production code, but without calling any `ExecutableModule::run()`, which usually contains
WP-dependant code, and therefore requires heavy mocking.

For example, assuming a common `plugin()` function like the following:

```php
function plugin(): Modularity\Package {
static $package;
if (!$package) {
$properties = Modularity\Properties\PluginProperties::new(__FILE__);
$package = Modularity\Package::new($properties)
->addModule(new ModuleOne())
->addModule(new ModuleTwo())
}
return $package;
}
```

In unit test it will be possible (as of v1.7+) to do something like the following:

```php
$myService = plugin()->build()->container()->get(MyService::class);
static::assertTrue($myService->isValid());
```

### Booting a built container

The `Package::boot()` method can be called on already built package.

For example, the following is a valid unit test code:

```php
$plugin = plugin()->build();
$myService = $plugin->container()->get(MyService::class);

static::assertTrue($myService->isValid());
static::assertFalse($myService->isBooted());

$plugin->boot();

static::assertTrue($myService->isBooted());
```

### Deprecated boot parameters

Before Modularity v1.7.0, it was an accepted practice to pass default modules to `Package::boot()`,
as in:

```php
add_action(
'plugins_loaded',
static function(): void {
plugin()->boot(new ModuleOne(), new ModuleTwo());
}
);
```

This is now deprecated to allow a better separation of the "building" and "booting" steps.

While it still works (and it will work up to version 2.0), it will emit a deprecation notice.

The replacement is using `Package::addModule()`:

```php
plugin()->addModule(new ModuleOne())->addModule(new ModuleTwo())->boot();
```

There's only one case in which calling `Package::boot()` with default modules will throw an
exception (besides triggering a deprecated notice), that is when a passed modules was not added
before `Package::addModule()` and an instance of the container was already obtained from the package.

For example, this will throw an exception:

```php
$plugin = plugin()->build();

// Now that container is built, passing modules to `boot()` will raise an exception, because we
// can't add new modules to an already "compiled" container being that read-only.
$container = $plugin->container();

$plugin->boot(new ModuleOne());
```

To prevent the exception it would be necessary to add the module before calling `build()`, or alternatively, to call `$plugin->boot(new ModuleOne())` _before_ calling `$plugin->container()`.
In this latter case the exception is not thrown, but the deprecation will still be emitted.


## Connecting packages
Expand Down Expand Up @@ -180,39 +270,3 @@ Thanks to that, all plugins will be able to access the library's services in the
### Accessing connected packages' properties

In modules, we can access package properties calling `$container->get(Package::PROPERTIES)`. If we'd like to access any connected package properties, we could do that using a key whose format is: `sprintf('%s.%s', $connectedPackage->name(), Package::PROPERTIES)`.



## What happens on Package::boot()?

When booting your Application, following will happen inside:

**0. Package::statusIs(Package::STATUS_IDLE);**

Application is idle and ready to start.

**1. Register default Modules**

Default Modules which are injected before `Package::boot()` will be registered first by iterating over all Modules and calling `Package::addModule()`.

**2. Package::ACTION_INIT**

A custom WordPress action will be triggered first to allow registration of additional Modules via `Package::addModule()` by accessing the `Package`-class. Application will change into `Package::STATUS_INITIALIZED` afterwards.

Newly registered Modules via that hook will be executed after the default Modules which are injected before the `Package::boot()`-method.

**3. Compile read-only Container**

The default primary PSR-Container is generated by the ContainerConfigurator by injecting all Factories, Extension and child PSR-Containers into it.

**4. Execute all ExecutableModules**

After collecting all ExecutableModules, the Package-class will now iterate over all ExecutableModules and execute them by injecting the default primary PSR-Container.

**5. Package::ACTION_READY**

Last but not least, `Package::boot()` will trigger custom WordPress Action which allows you to access the Package-class again for the purpose of debugging all Modules.

**6. Done**

The package was either successfully booted and state changed to `Package::STATUS_BOOTED` or failed booting due some exceptions and state was changed to `Package::STATUS_FAILED_BOOT`.
3 changes: 2 additions & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.0/phpunit.xsd"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/8.5/phpunit.xsd"
bootstrap="./tests/boot.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
convertDeprecationsToExceptions="false"
backupGlobals="false"
stopOnFailure="false">
<filter>
Expand Down
13 changes: 7 additions & 6 deletions src/Container/PackageProxyContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public function __construct(Package $package)
*/
public function get(string $id)
{
assert(is_string($id));
$this->assertPackageBooted($id);

return $this->container->get($id);
Expand All @@ -50,8 +49,6 @@ public function get(string $id)
*/
public function has(string $id): bool
{
assert(is_string($id));

return $this->tryContainer() && $this->container->has($id);
}

Expand All @@ -67,7 +64,11 @@ private function tryContainer(): bool
return true;
}

if ($this->package->statusIs(Package::STATUS_BOOTED)) {
/** TODO: We need a better way to deal with status checking besides equality */
if (
$this->package->statusIs(Package::STATUS_READY)
|| $this->package->statusIs(Package::STATUS_BOOTED)
) {
$this->container = $this->package->container();
}

Expand All @@ -90,8 +91,8 @@ private function assertPackageBooted(string $id): void

$name = $this->package->name();
$status = $this->package->statusIs(Package::STATUS_FAILED)
? 'failed booting'
: 'is not booted yet';
? 'is errored'
: 'is not ready yet';

throw new class ("Error retrieving service {$id} because package {$name} {$status}.")
extends \Exception
Expand Down
Loading

0 comments on commit 0bde4d1

Please sign in to comment.