Skip to content

Commit 64a9413

Browse files
authored
Merge pull request #15 from tweakphp/custom-loaders
Add custom loaders
2 parents bd07e1a + bd99c91 commit 64a9413

File tree

4 files changed

+50
-2
lines changed

4 files changed

+50
-2
lines changed

index.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
<?php
22

3+
use TweakPHP\Client\Cli;
34
use TweakPHP\Client\Loader;
45

56
require __DIR__.'/vendor/autoload.php';
@@ -11,7 +12,8 @@
1112
exit(1);
1213
}
1314

14-
$loader = Loader::load($arguments[1]);
15+
$customLoader = Cli::getArgument('loader');
16+
$loader = Loader::load($arguments[1], $customLoader);
1517

1618
if ($loader === null) {
1719
echo 'Invalid path'.PHP_EOL;

src/Cli.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace TweakPHP\Client;
4+
5+
class Cli
6+
{
7+
public static function getArgument(string $argument): string
8+
{
9+
$arguments = $_SERVER['argv'] ?? [];
10+
11+
foreach ($arguments as $arg) {
12+
if (strpos($arg, "--$argument=") === 0) {
13+
return substr($arg, strlen("--$argument="));
14+
}
15+
}
16+
17+
return '';
18+
}
19+
}

src/Loader.php

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,16 @@ class Loader
1414
/**
1515
* @return null|LoaderInterface
1616
*/
17-
public static function load(string $path)
17+
public static function load(string $path, ?string $encodedLoader = null)
1818
{
19+
if ($encodedLoader !== null) {
20+
$loaderClass = self::getLoaderClassFrom($encodedLoader);
21+
22+
if ($loaderClass !== null) {
23+
return new $loaderClass($path);
24+
}
25+
}
26+
1927
if (LaravelLoader::supports($path)) {
2028
return new LaravelLoader($path);
2129
}
@@ -38,4 +46,18 @@ public static function load(string $path)
3846

3947
return null;
4048
}
49+
50+
private static function getLoaderClassFrom(string $encodedLoader)
51+
{
52+
$declaredClassesBefore = get_declared_classes();
53+
$loader = base64_decode($encodedLoader);
54+
eval(str_replace('<?php', '', $loader));
55+
$declaredClassesAfter = get_declared_classes();
56+
$newClasses = array_diff($declaredClassesAfter, $declaredClassesBefore);
57+
if (empty($newClasses)) {
58+
return null;
59+
}
60+
61+
return reset($newClasses);
62+
}
4163
}

src/Loaders/BaseLoader.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,9 @@ public function casters(): array
4141
{
4242
return [];
4343
}
44+
45+
public static function supports(string $path): bool
46+
{
47+
return false;
48+
}
4449
}

0 commit comments

Comments
 (0)