1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 17:09:40 +01:00
amp/lib/Loop/DriverFactory.php

74 lines
1.6 KiB
PHP
Raw Normal View History

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