Last active
January 9, 2017 15:29
-
-
Save Koopzington/47ca0f46a35e1efdc8c30960586f25e9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/php | |
| <?php | |
| require_once __DIR__ . '/vendor/autoload.php'; | |
| // Path to file was passed to the script, find out FQCN of the class with the power of PSR4 mapping! | |
| $file = substr(getcwd() . '/' . $argv[1], 0, -4); | |
| $namespaces = include __DIR__ . '/vendor/composer/autoload_psr4.php'; | |
| foreach ($namespaces as $namespace => $paths) { | |
| if (strpos($file, $paths[0]) === 0) { | |
| $file = str_replace( | |
| [$paths[0], '\\', '/'], | |
| [$namespace, '', '\\'], | |
| $file | |
| ); | |
| break; | |
| } | |
| } | |
| $explode = explode('\\', $file); | |
| $ns = $explode[0]; | |
| $class = new ReflectionClass($file); | |
| if ($class->hasMethod('__construct')) { | |
| $constructorArguments = $class->getConstructor()->getParameters(); | |
| // generate contents of Factory class | |
| $factory = '<?php' . PHP_EOL . PHP_EOL . 'namespace ' . $ns . '\Factory;' . PHP_EOL . PHP_EOL | |
| . 'use Interop\Container\ContainerInterface;' . PHP_EOL | |
| . 'use ' . $class->getName() . ';' . PHP_EOL; | |
| foreach ($constructorArguments as $item) { | |
| if ($item->getClass() !== null) { | |
| $factory .= 'use ' . $item->getClass()->getName() . ';' . PHP_EOL; | |
| } | |
| } | |
| $ind = ' '; | |
| $factory .= PHP_EOL . 'final class ' . $class->getShortName() . 'Factory' . PHP_EOL | |
| . '{' . PHP_EOL | |
| . $ind . 'public function __invoke(ContainerInterface $container): ' . $class->getShortName() . PHP_EOL | |
| . $ind . '{' . PHP_EOL | |
| . $ind . $ind . 'return new ' . $class->getShortName() . '(' . PHP_EOL; | |
| foreach ($constructorArguments as $item) { | |
| if ($item->getClass() !== null) { | |
| $factory .= $ind . $ind . $ind . '$container->get(' . $item->getClass()->getShortName() . '::class)'; | |
| } else { | |
| $factory .= $ind . $ind . $ind . '$' . $item->getName(); | |
| } | |
| // ommit last comma | |
| $factory .= $item === end($constructorArguments) ? PHP_EOL : ',' . PHP_EOL; | |
| } | |
| $factory .= $ind . $ind . ');' . PHP_EOL . $ind . '}' . PHP_EOL . '}'; | |
| $target = dirname($class->getFileName()) . '/../Factory/' . $class->getShortName() . 'Factory.php'; | |
| file_put_contents( | |
| $target, | |
| $factory | |
| ); | |
| echo 'Factory generated in ' . $target . '.' . PHP_EOL; | |
| echo $class->getName() . '::class => ' . $ns . '\Factory\\' . $class->getShortName() . 'Factory::class,' . PHP_EOL; | |
| } else { | |
| echo 'Class doesn\'t have a constructor!' . PHP_EOL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment