Skip to content

Commit

Permalink
[11.x] Improves Application::configure method (#49552)
Browse files Browse the repository at this point in the history
* Improves application builder

* [11.x] Infers base path from composer instead (#49553)

* Uses composer instead of `debug_backtrace`

* Removes non used import
  • Loading branch information
nunomaduro authored Jan 3, 2024
1 parent 06cd2bc commit 4deacb2
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/Illuminate/Foundation/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Foundation;

use Closure;
use Composer\Autoload\ClassLoader;
use Illuminate\Container\Container;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Contracts\Foundation\Application as ApplicationContract;
Expand Down Expand Up @@ -224,16 +225,30 @@ public function __construct($basePath = null)
*/
public static function configure(string $baseDirectory = null)
{
$baseDirectory = $ENV['APP_BASE_PATH'] ?? ($baseDirectory ?: dirname(dirname(
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file']
)));
$baseDirectory = match (true) {
is_string($baseDirectory) => $baseDirectory,
default => static::inferBaseDirectory(),
};

return (new Configuration\ApplicationBuilder(new static($baseDirectory)))
->withKernels()
->withEvents()
->withCommands();
}

/**
* Infer the application's base directory from the environment.
*
* @return string
*/
public static function inferBaseDirectory()
{
return match (true) {
isset($_ENV['APP_BASE_PATH']) => $_ENV['APP_BASE_PATH'],
default => dirname(array_keys(ClassLoader::getRegisteredLoaders())[0]),
};
}

/**
* Get the version number of the application.
*
Expand Down
44 changes: 44 additions & 0 deletions tests/Foundation/FoundationApplicationBuilderTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace Illuminate\Tests\Foundation;

use Illuminate\Foundation\Application;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class FoundationApplicationBuilderTest extends TestCase
{
protected function tearDown(): void
{
m::close();

unset($_ENV['APP_BASE_PATH']);

parent::tearDown();
}

public function testBaseDirectoryWithArg()
{
$_ENV['APP_BASE_PATH'] = __DIR__.'/as-env';

$app = Application::configure(__DIR__.'/as-arg')->create();

$this->assertSame(__DIR__.'/as-arg', $app->basePath());
}

public function testBaseDirectoryWithEnv()
{
$_ENV['APP_BASE_PATH'] = __DIR__.'/as-env';

$app = Application::configure()->create();

$this->assertSame(__DIR__.'/as-env', $app->basePath());
}

public function testBaseDirectoryWithComposer()
{
$app = Application::configure()->create();

$this->assertSame(dirname(__DIR__, 2), $app->basePath());
}
}

0 comments on commit 4deacb2

Please sign in to comment.