From c2d6fbc52a80d5678b06260cf6f522d57a48babc Mon Sep 17 00:00:00 2001
From: Bart Jaskulski <bjaskulski@protonmail.com>
Date: Wed, 27 Nov 2024 15:45:43 +0100
Subject: [PATCH] feat: improve detection of dev mode

Now, dev mode doesn't have to be explicitly set, only for WordPress,
which has production type defined.

Additionally, allow to build container without using cache, when server
does not support it (i.e. cannot write to the disk).

Signed-off-by: Bart Jaskulski <bjaskulski@protonmail.com>
---
 src/Kernel.php | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/src/Kernel.php b/src/Kernel.php
index 75e48cc..0416c85 100644
--- a/src/Kernel.php
+++ b/src/Kernel.php
@@ -92,10 +92,10 @@ final class Kernel {
 		return preg_replace( '/[^\w_]/', '_', implode("_", [ $plugin->get_slug(), $plugin->get_version(), 'container' ]) );
 	}
 
-	private function initialize_container( Plugin $plugin ): Container {
+	private function initialize_container( Plugin $plugin, bool $useCache = true ): Container {
 		$original_builder = new DiBuilder();
 
-		if ( $this->config->get( 'debug', false ) === false ) {
+		if ( $this->is_prod() && $useCache ) {
 			$original_builder->enableCompilation(
 				$this->get_cache_path(),
 				$this->get_container_name( $plugin )
@@ -112,7 +112,11 @@ final class Kernel {
 			$extension->build( $builder, $plugin, $this->config );
 		}
 
-		return $builder->build();
+		try {
+			return $builder->build();
+		} catch ( \Exception $e ) {
+			return $this->initialize_container( $plugin, false );
+		}
 	}
 
 	private function prepare_driver( ContainerInterface $container ): HookDriver {
@@ -125,7 +129,7 @@ final class Kernel {
 			new ClusteredLoader( $loader )
 		);
 
-		if ( $this->config->get( 'debug', false ) ) {
+		if ( $this->is_dev() ) {
 			$loader = new DebugBindingLoader( $loader );
 		}
 
@@ -146,4 +150,12 @@ final class Kernel {
 
 		return $driver;
 	}
+
+	private function is_dev(): bool {
+		return $this->config->get( 'debug', false ) || wp_get_environment_type() !== 'development';
+	}
+
+	private function is_prod(): bool {
+		return $this->is_dev() === false;
+	}
 }
-- 
GitLab