Skip to content

perf: add Factories::get() v2 #8600

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

Merged
merged 5 commits into from
Mar 7, 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
4 changes: 4 additions & 0 deletions system/Common.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,10 @@ function command(string $command)
*/
function config(string $name, bool $getShared = true)
{
if ($getShared) {
return Factories::get('config', $name);
}

return Factories::config($name, ['getShared' => $getShared]);
}
}
Expand Down
18 changes: 16 additions & 2 deletions system/Config/Factories.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ public static function __callStatic(string $component, array $arguments)
$options = array_merge(self::getOptions($component), $options);

if (! $options['getShared']) {
if (isset(self::$aliases[$component][$alias])) {
$class = self::$aliases[$component][$alias];
if (isset(self::$aliases[$options['component']][$alias])) {
$class = self::$aliases[$options['component']][$alias];

return new $class(...$arguments);
}
Expand Down Expand Up @@ -173,6 +173,20 @@ public static function __callStatic(string $component, array $arguments)
return self::$instances[$options['component']][$class];
}

/**
* Simple method to get the shared instance fast.
*/
public static function get(string $component, string $alias): ?object
{
if (isset(self::$aliases[$component][$alias])) {
$class = self::$aliases[$component][$alias];

return self::$instances[$component][$class];
}

return self::__callStatic($component, [$alias]);
}

/**
* Gets the defined instance. If not exists, creates new one.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/system/Config/FactoriesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -465,4 +465,25 @@ public function testIsUpdated(array $data)

$this->assertFalse(Factories::isUpdated('config'));
}

public function testGetReturnsFactoriesConfigInstance()
{
$config = Factories::config('App');

$this->assertSame($config, Factories::get('config', 'App'));
}

public function testGetCreatesConfigInstanceAndFactoriesConfigReturnsIt()
{
$config = Factories::get('config', 'App');

$this->assertSame($config, Factories::config('App'));
}

public function testGetNonexistentClass()
{
$config = Factories::get('config', 'NonexistentClass');

$this->assertNull($config);
}
}