2017-03-10 21:31:57 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Amp\Loop;
|
|
|
|
|
2017-03-14 22:33:45 +01:00
|
|
|
// @codeCoverageIgnoreStart
|
2018-06-18 20:00:01 +02:00
|
|
|
class DriverFactory
|
|
|
|
{
|
2017-03-10 21:31:57 +01:00
|
|
|
/**
|
|
|
|
* Creates a new loop instance and chooses the best available driver.
|
|
|
|
*
|
|
|
|
* @return Driver
|
2017-05-19 16:17:11 +02:00
|
|
|
*
|
|
|
|
* @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER
|
2017-03-10 21:31:57 +01:00
|
|
|
*/
|
2018-06-18 20:00:01 +02:00
|
|
|
public function create(): Driver
|
|
|
|
{
|
2017-05-19 16:17:11 +02:00
|
|
|
if ($driver = $this->createDriverFromEnv()) {
|
|
|
|
return $driver;
|
|
|
|
}
|
|
|
|
|
2017-03-12 11:25:21 +01:00
|
|
|
if (UvDriver::isSupported()) {
|
2017-03-12 11:21:44 +01:00
|
|
|
return new UvDriver;
|
2017-03-10 21:31:57 +01:00
|
|
|
}
|
|
|
|
|
2017-03-12 11:25:21 +01:00
|
|
|
if (EvDriver::isSupported()) {
|
2017-03-12 11:21:44 +01:00
|
|
|
return new EvDriver;
|
2017-03-10 21:31:57 +01:00
|
|
|
}
|
|
|
|
|
2017-03-12 11:25:21 +01:00
|
|
|
if (EventDriver::isSupported()) {
|
2017-03-12 11:21:44 +01:00
|
|
|
return new EventDriver;
|
2017-03-10 21:31:57 +01:00
|
|
|
}
|
|
|
|
|
2017-03-12 11:21:44 +01:00
|
|
|
return new NativeDriver;
|
2017-03-10 21:31:57 +01:00
|
|
|
}
|
2017-05-19 16:17:11 +02:00
|
|
|
|
2018-06-18 20:00:01 +02:00
|
|
|
private function createDriverFromEnv()
|
|
|
|
{
|
2017-05-19 16:17:11 +02:00
|
|
|
$driver = \getenv("AMP_LOOP_DRIVER");
|
|
|
|
|
|
|
|
if (!$driver) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!\class_exists($driver)) {
|
|
|
|
throw new \Error(\sprintf(
|
2017-05-19 16:51:20 +02:00
|
|
|
"Driver '%s' does not exist.",
|
2017-05-19 16:17:11 +02:00
|
|
|
$driver
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!\is_subclass_of($driver, Driver::class)) {
|
|
|
|
throw new \Error(\sprintf(
|
2017-05-19 16:51:20 +02:00
|
|
|
"Driver '%s' is not a subclass of '%s'.",
|
2017-05-19 16:17:11 +02:00
|
|
|
$driver,
|
|
|
|
Driver::class
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
|
|
|
return new $driver;
|
|
|
|
}
|
2017-03-14 22:33:45 +01:00
|
|
|
}
|
2017-04-24 15:39:08 +02:00
|
|
|
// @codeCoverageIgnoreEnd
|