Simplify checking environment class name

This commit is contained in:
Aaron Piotrowski 2017-11-30 23:58:41 -06:00
parent 3f7f21875d
commit 51b6421933
No known key found for this signature in database
GPG Key ID: ADD1EF783EDE9EEB
2 changed files with 13 additions and 21 deletions

View File

@ -51,21 +51,19 @@ Amp\Loop::run(function () {
$className = $options["e"]; $className = $options["e"];
try { if (!class_exists($className)) {
$reflection = new ReflectionClass($className); throw new Error(sprintf("Invalid environment class name '%s'", $className));
} catch (ReflectionException $e) {
throw new Error(sprintf("Invalid class name '%s'", $className));
} }
if (!$reflection->isInstantiable()) { if (!is_subclass_of($className, Worker\Environment::class)) {
throw new Error(sprintf("'%s' is not instatiable class", $className)); throw new Error(sprintf(
"The class '%s' does not implement '%s'",
$className,
Worker\Environment::class
));
} }
if (!$reflection->implementsInterface(Worker\Environment::class)) { return new $className;
throw new Error(sprintf("The class '%s' does not implement '%s'", $className,Worker\Environment::class));
}
return $reflection->newInstance();
})(); })();
$runner = new Worker\TaskRunner($channel, $environment); $runner = new Worker\TaskRunner($channel, $environment);

View File

@ -15,21 +15,15 @@ class WorkerThread extends AbstractWorker {
*/ */
public function __construct(string $envClassName = BasicEnvironment::class) { public function __construct(string $envClassName = BasicEnvironment::class) {
parent::__construct(new Thread(function (string $className): Promise { parent::__construct(new Thread(function (string $className): Promise {
try { if (!\class_exists($className)) {
$reflection = new \ReflectionClass($className); throw new \Error(\sprintf("Invalid environment class name '%s'", $className));
} catch (\ReflectionException $e) {
throw new \Error(\sprintf("Invalid class name '%s'", $className));
} }
if (!$reflection->isInstantiable()) { if (!\is_subclass_of($className, Environment::class)) {
throw new \Error(\sprintf("'%s' is not instatiable class", $className));
}
if (!$reflection->implementsInterface(Environment::class)) {
throw new \Error(\sprintf("The class '%s' does not implement '%s'", $className, Environment::class)); throw new \Error(\sprintf("The class '%s' does not implement '%s'", $className, Environment::class));
} }
$environment = $reflection->newInstance(); $environment = new $className;
if (!\defined("AMP_WORKER")) { if (!\defined("AMP_WORKER")) {
\define("AMP_WORKER", "amp-worker"); \define("AMP_WORKER", "amp-worker");