repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/view.php
app/config/view.php
<?php return array( /* |-------------------------------------------------------------------------- | View Storage Paths |-------------------------------------------------------------------------- | | Most templating systems load templates from disk. Here you may specify | an array of paths that should be checked for your views. Of course | the usual Laravel view path has already been registered for you. | */ 'paths' => array(__DIR__.'/../views'), /* |-------------------------------------------------------------------------- | Pagination View |-------------------------------------------------------------------------- | | This view will be used to render the pagination link output, and can | be easily customized here to show any view you like. A clean view | compatible with Twitter's Bootstrap is given to you by default. | */ 'pagination' => 'pagination::slider', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/database.php
app/config/database.php
<?php return array( /* |-------------------------------------------------------------------------- | PDO Fetch Style |-------------------------------------------------------------------------- | | By default, database results will be returned as instances of the PHP | stdClass object; however, you may desire to retrieve records in an | array format for simplicity. Here you can tweak the fetch style. | */ 'fetch' => PDO::FETCH_CLASS, /* |-------------------------------------------------------------------------- | Default Database Connection Name |-------------------------------------------------------------------------- | | Here you may specify which of the database connections below you wish | to use as your default connection for all database work. Of course | you may use many connections at once using the Database library. | */ 'default' => 'mysql', /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => array( 'sqlite' => array( 'driver' => 'sqlite', 'database' => __DIR__.'/../database/production.sqlite', 'prefix' => '', ), 'mysql' => array( 'driver' => 'mysql', 'host' => getenv('db_host'), 'database' => 'facebook-login', 'username' => getenv('db_username'), 'password' => getenv('db_password'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), 'pgsql' => array( 'driver' => 'pgsql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ), 'sqlsrv' => array( 'driver' => 'sqlsrv', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'prefix' => '', ), ), /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer set of commands than a typical key-value systems | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => array( 'cluster' => false, 'default' => array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ), ), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/facebook.php
app/config/facebook.php
<?php // app/config/facebook.php // Facebook app Config return array( 'appId' => getenv('fb_id'), 'secret' => getenv('fb_secret') );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/mail.php
app/config/mail.php
<?php return array( /* |-------------------------------------------------------------------------- | Mail Driver |-------------------------------------------------------------------------- | | Laravel supports both SMTP and PHP's "mail" function as drivers for the | sending of e-mail. You may specify which one you're using throughout | your application here. By default, Laravel is setup for SMTP mail. | | Supported: "smtp", "mail", "sendmail" | */ 'driver' => 'smtp', /* |-------------------------------------------------------------------------- | SMTP Host Address |-------------------------------------------------------------------------- | | Here you may provide the host address of the SMTP server used by your | applications. A default option is provided that is compatible with | the Postmark mail service, which will provide reliable delivery. | */ 'host' => 'smtp.mailgun.org', /* |-------------------------------------------------------------------------- | SMTP Host Port |-------------------------------------------------------------------------- | | This is the SMTP port used by your application to delivery e-mails to | users of your application. Like the host we have set this value to | stay compatible with the Postmark e-mail application by default. | */ 'port' => 587, /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => array('address' => null, 'name' => null), /* |-------------------------------------------------------------------------- | E-Mail Encryption Protocol |-------------------------------------------------------------------------- | | Here you may specify the encryption protocol that should be used when | the application send e-mail messages. A sensible default using the | transport layer security protocol should provide great security. | */ 'encryption' => 'tls', /* |-------------------------------------------------------------------------- | SMTP Server Username |-------------------------------------------------------------------------- | | If your SMTP server requires a username for authentication, you should | set it here. This will get used to authenticate with your server on | connection. You may also set the "password" value below this one. | */ 'username' => null, /* |-------------------------------------------------------------------------- | SMTP Server Password |-------------------------------------------------------------------------- | | Here you may set the password required by your SMTP server to send out | messages from your application. This will be given to the server on | connection so that the application will be able to send messages. | */ 'password' => null, /* |-------------------------------------------------------------------------- | Sendmail System Path |-------------------------------------------------------------------------- | | When using the "sendmail" driver to send e-mails, we will need to know | the path to where Sendmail lives on this server. A default path has | been provided here, which will work well on most of your systems. | */ 'sendmail' => '/usr/sbin/sendmail -bs', /* |-------------------------------------------------------------------------- | Mail "Pretend" |-------------------------------------------------------------------------- | | When this option is enabled, e-mail will not actually be sent over the | web and will instead be written to your application's logs files so | you may inspect the message. This is great for local development. | */ 'pretend' => false, );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/compile.php
app/config/compile.php
<?php return array( /* |-------------------------------------------------------------------------- | Additional Compiled Classes |-------------------------------------------------------------------------- | | Here you may specify additional classes to include in the compiled file | generated by the `artisan optimize` command. These should be classes | that are included on basically every request into the application. | */ );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/auth.php
app/config/auth.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Authentication Driver |-------------------------------------------------------------------------- | | This option controls the authentication driver that will be utilized. | This drivers manages the retrieval and authentication of the users | attempting to get access to protected areas of your application. | | Supported: "database", "eloquent" | */ 'driver' => 'eloquent', /* |-------------------------------------------------------------------------- | Authentication Model |-------------------------------------------------------------------------- | | When using the "Eloquent" authentication driver, we need to know which | Eloquent model should be used to retrieve your users. Of course, it | is often just the "User" model but you may use whatever you like. | */ 'model' => 'User', /* |-------------------------------------------------------------------------- | Authentication Table |-------------------------------------------------------------------------- | | When using the "Database" authentication driver, we need to know which | table should be used to retrieve your users. We have chosen a basic | default value but you may easily change it to any table you like. | */ 'table' => 'users', /* |-------------------------------------------------------------------------- | Password Reminder Settings |-------------------------------------------------------------------------- | | Here you may set the settings for password reminders, including a view | that should be used as your password reminder e-mail. You will also | be able to set the name of the table that holds the reset tokens. | */ 'reminder' => array( 'email' => 'emails.auth.reminder', 'table' => 'password_reminders', 'expire' => 60, ), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/testing/session.php
app/config/testing/session.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Session Driver |-------------------------------------------------------------------------- | | This option controls the default session "driver" that will be used on | requests. By default, we will use the lightweight native driver but | you may specify any of the other wonderful drivers provided here. | | Supported: "native", "cookie", "database", "apc", | "memcached", "redis", "array" | */ 'driver' => 'array', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/testing/cache.php
app/config/testing/cache.php
<?php return array( /* |-------------------------------------------------------------------------- | Default Cache Driver |-------------------------------------------------------------------------- | | This option controls the default cache "driver" that will be used when | using the Caching library. Of course, you may use other drivers any | time you wish. This is the default when another is not specified. | | Supported: "file", "database", "apc", "memcached", "redis", "array" | */ 'driver' => 'array', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/local/session.php
app/config/local/session.php
<?php return array( 'driver' => 'native', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/local/cache.php
app/config/local/cache.php
<?php return array( 'driver' => 'file', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/config/local/database.php
app/config/local/database.php
<?php return array( 'connections' => array( 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'facebook-login', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), ), );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/database/seeds/DatabaseSeeder.php
app/database/seeds/DatabaseSeeder.php
<?php class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); // $this->call('UserTableSeeder'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/database/migrations/2013_08_19_055233_create_profiles_table.php
app/database/migrations/2013_08_19_055233_create_profiles_table.php
<?php use Illuminate\Database\Migrations\Migration; class CreateProfilesTable extends Migration { public function up() { Schema::create('profiles', function($table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('username'); $table->biginteger('uid')->unsigned(); $table->string('access_token'); $table->string('access_token_secret'); $table->timestamps(); }); } public function down() { Schema::drop('profiles'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/app/database/migrations/2013_08_19_055228_create_users_table.php
app/database/migrations/2013_08_19_055228_create_users_table.php
<?php use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { public function up() { Schema::create('users', function($table) { $table->increments('id'); $table->string('email')->unique(); $table->string('photo'); $table->string('name'); $table->string('password'); $table->timestamps(); }); } public function down() { Schema::drop('users'); } }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/bootstrap/start.php
bootstrap/start.php
<?php /* |-------------------------------------------------------------------------- | Create The Application |-------------------------------------------------------------------------- | | The first thing we will do is create a new Laravel application instance | which serves as the "glue" for all the components of Laravel, and is | the IoC container for the system binding all of the various parts. | */ $app = new Illuminate\Foundation\Application; //$app->redirectIfTrailingSlash(); /* |-------------------------------------------------------------------------- | Detect The Application Environment |-------------------------------------------------------------------------- | | Laravel takes a dead simple approach to your application environments | so you can just specify a machine name or HTTP host that matches a | given environment, then we will automatically detect it for you. | */ $env = $app->detectEnvironment(array( 'local' => array('*localhost*'), )); /* |-------------------------------------------------------------------------- | Bind Paths |-------------------------------------------------------------------------- | | Here we are binding the paths configured in paths.php to the app. You | should not be changing these here. If you need to change these you | may do so within the paths.php file and they will be bound here. | */ $app->bindInstallPaths(require __DIR__.'/paths.php'); /* |-------------------------------------------------------------------------- | Load The Application |-------------------------------------------------------------------------- | | Here we will load the Illuminate application. We'll keep this is in a | separate location so we can isolate the creation of an application | from the actual running of the application with a given request. | */ $framework = $app['path.base'].'/vendor/laravel/framework/src'; require $framework.'/Illuminate/Foundation/start.php'; /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app;
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/bootstrap/autoload.php
bootstrap/autoload.php
<?php define('LARAVEL_START', microtime(true)); /* |-------------------------------------------------------------------------- | Register The Composer Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader | for our application. We just need to utilize it! We'll require it | into the script here so that we do not have to worry about the | loading of any our classes "manually". Feels great to relax. | */ require __DIR__.'/../vendor/autoload.php'; /* |-------------------------------------------------------------------------- | Include The Compiled Class File |-------------------------------------------------------------------------- | | To dramatically increase your application's performance, you may use a | compiled class file which contains all of the classes commonly used | by a request. The Artisan "optimize" is used to create this file. | */ if (file_exists($compiled = __DIR__.'/compiled.php')) { require $compiled; } /* |-------------------------------------------------------------------------- | Setup Patchwork UTF-8 Handling |-------------------------------------------------------------------------- | | The Patchwork library provides solid handling of UTF-8 strings as well | as provides replacements for all mb_* and iconv type functions that | are not available by default in PHP. We'll setup this stuff here. | */ Patchwork\Utf8\Bootup::initMbstring(); /* |-------------------------------------------------------------------------- | Register The Laravel Auto Loader |-------------------------------------------------------------------------- | | We register an auto-loader "behind" the Composer loader that can load | model classes on the fly, even if the autoload files have not been | regenerated for the application. We'll add it to the stack here. | */ Illuminate\Support\ClassLoader::register(); /* |-------------------------------------------------------------------------- | Register The Workbench Loaders |-------------------------------------------------------------------------- | | The Laravel workbench provides a convenient place to develop packages | when working locally. However we will need to load in the Composer | auto-load files for the packages so that these can be used here. | */ if (is_dir($workbench = __DIR__.'/../workbench')) { Illuminate\Workbench\Starter::start($workbench); }
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/bootstrap/paths.php
bootstrap/paths.php
<?php return array( /* |-------------------------------------------------------------------------- | Application Path |-------------------------------------------------------------------------- | | Here we just defined the path to the application directory. Most likely | you will never need to change this value as the default setup should | work perfectly fine for the vast majority of all our applications. | */ 'app' => __DIR__.'/../app', /* |-------------------------------------------------------------------------- | Public Path |-------------------------------------------------------------------------- | | The public path contains the assets for your web application, such as | your JavaScript and CSS files, and also contains the primary entry | point for web requests into these applications from the outside. | */ 'public' => __DIR__.'/../public', /* |-------------------------------------------------------------------------- | Base Path |-------------------------------------------------------------------------- | | The base path is the root of the Laravel installation. Most likely you | will not need to change this value. But, if for some wild reason it | is necessary you will do so here, just proceed with some caution. | */ 'base' => __DIR__.'/..', /* |-------------------------------------------------------------------------- | Storage Path |-------------------------------------------------------------------------- | | The storage path is used by Laravel to store cached Blade views, logs | and other pieces of information. You may modify the path here when | you want to change the location of this directory for your apps. | */ 'storage' => __DIR__.'/../app/storage', );
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
msurguy/laravel-facebook-login
https://github.com/msurguy/laravel-facebook-login/blob/69a8a7707caa879000d64fc24e1ae20a36e96e64/public/index.php
public/index.php
<?php /** * Laravel - A PHP Framework For Web Artisans * * @package Laravel * @author Taylor Otwell <taylorotwell@gmail.com> */ /* |-------------------------------------------------------------------------- | Register The Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader | for our application. We just need to utilize it! We'll require it | into the script here so that we do not have to worry about the | loading of any our classes "manually". Feels great to relax. | */ require __DIR__.'/../bootstrap/autoload.php'; /* |-------------------------------------------------------------------------- | Turn On The Lights |-------------------------------------------------------------------------- | | We need to illuminate PHP development, so let's turn on the lights. | This bootstraps the framework and gets it ready for use, then it | will load up this application so that we can run it and send | the responses back to the browser and delight these users. | */ $app = require_once __DIR__.'/../bootstrap/start.php'; /* |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can simply call the run method, | which will execute the request and send the response back to | the client's browser allowing them to enjoy the creative | and wonderful applications we have created for them. | */ $app->run(); /* |-------------------------------------------------------------------------- | Shutdown The Application |-------------------------------------------------------------------------- | | Once the app has finished running, we will fire off the shutdown events | so that any final work may be done by the application before we shut | down the process. This is the last thing to happen to the request. | */ $app->shutdown();
php
MIT
69a8a7707caa879000d64fc24e1ae20a36e96e64
2026-01-05T04:56:51.782788Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/CURLException.php
src/CURLException.php
<?php namespace mpyw\Co; class CURLException extends \RuntimeException { private $handle; /** * Constructor. * @param string $message * @param int $code * @param resource $handle */ public function __construct($message, $code, $handle) { parent::__construct($message, $code); $this->handle = $handle; } /** * Get cURL handle. * @return resource $handle */ public function getHandle() { return $this->handle; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/CoInterface.php
src/CoInterface.php
<?php namespace mpyw\Co; interface CoInterface { const RETURN_WITH = '__RETURN_WITH__'; const RETURN_ = '__RETURN_WITH__'; // alias const RET = '__RETURN_WITH__'; // alias const RTN = '__RETURN_WITH__'; // alias const SAFE = '__SAFE__'; const DELAY = '__DELAY__'; const SLEEP = '__DELAY__'; // alias public static function setDefaultOptions(array $options); public static function getDefaultOptions(); public static function wait($value, array $options = []); public static function async($value, $throw = null); public static function isRunning(); public static function race($value); public static function any($value); public static function all($value); }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/AllFailedException.php
src/AllFailedException.php
<?php namespace mpyw\Co; class AllFailedException extends \RuntimeException { private $reasons; /** * Constructor. * @param string $message Dummy message. * @param int $code Always zero. * @param mixed $reasons Reasons why jobs are failed. */ public function __construct($message, $code, $reasons) { parent::__construct($message, $code); $this->reasons = $reasons; } /** * Get value. * @return mixed */ public function getReasons() { return $this->reasons; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Co.php
src/Co.php
<?php namespace mpyw\Co; use mpyw\Co\Internal\TypeUtils; use mpyw\Co\Internal\ControlUtils; use mpyw\Co\Internal\YieldableUtils; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\GeneratorContainer; use mpyw\Co\Internal\Pool; use React\Promise\Deferred; use React\Promise\PromiseInterface; use React\Promise\ExtendedPromiseInterface; use React\Promise\FulfilledPromise; use React\Promise\RejectedPromise; class Co implements CoInterface { /** * Instance of myself. * @var Co */ private static $self; /** * Options. * @var CoOption */ private $options; /** * cURL request pool object. * @var Pool */ private $pool; /** * Running cURL or Generator identifiers. * @var array */ private $runners = []; /** * Overwrite CoOption default. * @param array $options */ public static function setDefaultOptions(array $options) { CoOption::setDefault($options); } /** * Get CoOption default as array. * @return array */ public static function getDefaultOptions() { return CoOption::getDefault(); } /** * Wait until value is recursively resolved to return it. * This function call must be atomic. * @param mixed $value * @param array $options * @return mixed */ public static function wait($value, array $options = []) { try { if (self::$self) { throw new \BadMethodCallException('Co::wait() is already running. Use Co::async() instead.'); } self::$self = new self; self::$self->options = new CoOption($options); self::$self->pool = new Pool(self::$self->options); return self::$self->start($value); } finally { self::$self = null; } // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd /** * Value is recursively resolved, but we never wait it. * This function must be called along with Co::wait(). * @param mixed $value * @param mixed $throw */ public static function async($value, $throw = null) { if (!self::$self) { throw new \BadMethodCallException('Co::async() must be called along with Co::wait(). '); } if ($throw !== null) { $throw = filter_var($throw, FILTER_VALIDATE_BOOLEAN, [ 'flags' => FILTER_NULL_ON_FAILURE, ]); if ($throw === null) { throw new \InvalidArgumentException("\$throw must be null or boolean."); } } self::$self->start($value, false, $throw); } /** * Return if Co::wait() is running. * @return bool */ public static function isRunning() { return (bool)self::$self; } /** * External instantiation is forbidden. */ private function __construct() {} /** * Start resovling. * @param mixed $value * @param bool $wait * @param mixed $throw Used for Co::async() overrides. * @param mixed If $wait, return resolved value. */ private function start($value, $wait = true, $throw = null) { $return = null; // For convenience, all values are wrapped into generator $con = YieldableUtils::normalize($this->getRootGenerator($throw, $value, $return)); $promise = $this->processGeneratorContainerRunning($con); if ($promise instanceof ExtendedPromiseInterface) { // This is actually 100% true; just used for unwrapping Exception thrown. $promise->done(); } // We have to wait $return only if $wait if ($wait) { $this->pool->wait(); return $return; } } /** * Handle resolving generators. * @param GeneratorContainer $gc * @return PromiseInterface */ private function processGeneratorContainer(GeneratorContainer $gc) { return $gc->valid() ? $this->processGeneratorContainerRunning($gc) : $this->processGeneratorContainerDone($gc); } /** * Handle resolving generators already done. * @param GeneratorContainer $gc * @return PromiseInterface */ private function processGeneratorContainerDone(GeneratorContainer $gc) { // If exception has been thrown in generator, we have to propagate it as rejected value if ($gc->thrown()) { return new RejectedPromise($gc->getReturnOrThrown()); } // Now we normalize returned value $returned = YieldableUtils::normalize($gc->getReturnOrThrown(), $gc->getYieldKey()); $yieldables = YieldableUtils::getYieldables($returned, [], $this->runners); // If normalized value contains yieldables, we have to chain resolver if ($yieldables) { $deferred = new Deferred; return $this->promiseAll($yieldables, true) ->then( YieldableUtils::getApplier($returned, $yieldables, [$deferred, 'resolve']), [$deferred, 'reject'] ) ->then(function () use ($yieldables, $deferred) { $this->runners = array_diff_key($this->runners, $yieldables); return $deferred->promise(); }); } // Propagate normalized returned value return new FulfilledPromise($returned); } /** * Handle resolving generators still running. * @param GeneratorContainer $gc * @return PromiseInterface */ private function processGeneratorContainerRunning(GeneratorContainer $gc) { // Check delay request yields if ($gc->key() === CoInterface::DELAY) { return $this->pool->addDelay($gc->current()) ->then(function () use ($gc) { $gc->send(null); return $this->processGeneratorContainer($gc); }); } // Now we normalize yielded value $yielded = YieldableUtils::normalize($gc->current()); $yieldables = YieldableUtils::getYieldables($yielded, [], $this->runners); if (!$yieldables) { // If there are no yieldables, send yielded value back into generator $gc->send($yielded); // Continue return $this->processGeneratorContainer($gc); } // Chain resolver return $this->promiseAll($yieldables, $gc->key() !== CoInterface::SAFE) ->then( YieldableUtils::getApplier($yielded, $yieldables, [$gc, 'send']), [$gc, 'throw_'] )->then(function () use ($gc, $yieldables) { // Continue $this->runners = array_diff_key($this->runners, $yieldables); return $this->processGeneratorContainer($gc); }); } /** * Return root wrapper generator. * @param mixed $throw * @param mixed $value * @param mixed &$return */ private function getRootGenerator($throw, $value, &$return) { try { if ($throw !== null) { $key = $throw ? null : CoInterface::SAFE; } else { $key = $this->options['throw'] ? null : CoInterface::SAFE; } $return = (yield $key => $value); return; } catch (\Throwable $e) {} catch (\Exception $e) {} $this->pool->reserveHaltException($e); } /** * Promise all changes in yieldables are prepared. * @param array $yieldables * @param bool $throw_acceptable * @return PromiseInterface */ private function promiseAll(array $yieldables, $throw_acceptable) { $promises = []; foreach ($yieldables as $yieldable) { // Add or enqueue cURL handles if (TypeUtils::isCurl($yieldable['value'])) { $promises[(string)$yieldable['value']] = $this->pool->addCurl($yieldable['value']); continue; } // Process generators if (TypeUtils::isGeneratorContainer($yieldable['value'])) { $promises[(string)$yieldable['value']] = $this->processGeneratorContainer($yieldable['value']); continue; } } // If caller cannot accept exception, // we handle rejected value as resolved. if (!$throw_acceptable) { $promises = array_map( ['\mpyw\Co\Internal\YieldableUtils', 'safePromise'], $promises ); } return \React\Promise\all($promises); } /** * Wrap value with the Generator that returns the first successful result. * If all yieldables failed, AllFailedException is thrown. * If no yieldables found, AllFailedException is thrown. * * @param mixed $value * @return \Generator Resolved value. * @throws AllFailedException */ public static function any($value) { yield Co::RETURN_WITH => (yield ControlUtils::anyOrRace( $value, ['\mpyw\Co\Internal\ControlUtils', 'reverse'], 'Co::any() failed.' )); // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd /** * Wrap value with the Generator that returns the first result. * If no yieldables found, AllFailedException is thrown. * * @param mixed $value * @return \Generator Resolved value. * @throws \RuntimeException|AllFailedException */ public static function race($value) { yield Co::RETURN_WITH => (yield ControlUtils::anyOrRace( $value, ['\mpyw\Co\Internal\ControlUtils', 'fail'], 'Co::race() failed.' )); // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd /** * Wrap value with the Generator that returns the all results. * Normally you don't have to use this method, just yield an array that contains yieldables. * You should use only with Co::race() or Co::any(). * * @param mixed $value * @return \Generator Resolved value. * @throws \RuntimeException */ public static function all($value) { yield Co::RETURN_WITH => (yield $value); // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/ManualScheduler.php
src/Internal/ManualScheduler.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\CURLException; use React\Promise\Deferred; use React\Promise\PromiseInterface; class ManualScheduler extends AbstractScheduler { /** * cURL handles those have not been dispatched. * @var array */ private $queue = []; /** * Constructor. * Initialize cURL multi handle. * @param CoOption $options * @param resource $mh curl_multi */ public function __construct(CoOption $options, $mh) { $this->mh = $mh; $this->options = $options; } /** * Call curl_multi_add_handle() or push into queue. * @param resource $ch * @return PromiseInterface */ public function add($ch) { $deferred = new Deferred; $this->options['concurrency'] > 0 && count($this->added) >= $this->options['concurrency'] ? $this->addReserved($ch, $deferred) : $this->addImmediate($ch, $deferred); return $deferred->promise(); } /** * Are there no cURL handles? * @return bool */ public function isEmpty() { return !$this->added && !$this->queue; } /** * Call curl_multi_add_handle(). * @param resource $ch * @param Deferred $deferred */ private function addImmediate($ch, Deferred $deferred = null) { $errno = curl_multi_add_handle($this->mh, $ch); if ($errno !== CURLM_OK) { // @codeCoverageIgnoreStart $msg = curl_multi_strerror($errno) . ": $ch"; $deferred && $deferred->reject(new \RuntimeException($msg)); return; // @codeCoverageIgnoreEnd } $this->added[(string)$ch] = $ch; $deferred && $this->deferreds[(string)$ch] = $deferred; } /** * Push into queue. * @param resource $ch * @param Deferred $deferred */ private function addReserved($ch, Deferred $deferred = null) { $this->queue[(string)$ch] = $ch; $deferred && $this->deferreds[(string)$ch] = $deferred; } /** * Add cURL handles from waiting queue. */ protected function interruptConsume() { if ($this->queue) { $this->addImmediate(array_shift($this->queue)); } } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/Pool.php
src/Internal/Pool.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\CURLException; use React\Promise\PromiseInterface; class Pool { /** * Options. * @var CoOption */ private $options; /** * cURL multi handle. * @var resource */ private $mh; /** * Used for halting loop. * @var \Throwable|\Exception */ private $haltException; /** * cURL handle scheduler. * @var AbstractScheduler */ private $scheduler; /** * Delay controller. * @var Delayer */ private $delayer; /** * Constructor. * Initialize cURL multi handle. * @param CoOption $options */ public function __construct(CoOption $options) { $this->mh = curl_multi_init(); $flags = (int)$options['pipeline'] + (int)$options['multiplex'] * 2; curl_multi_setopt($this->mh, CURLMOPT_PIPELINING, $flags); $this->options = $options; $this->scheduler = $options['autoschedule'] ? new AutoScheduler($options, $this->mh) : new ManualScheduler($options, $this->mh); $this->delayer = new Delayer; } /** * Call curl_multi_add_handle() or push into queue. * @param resource $ch * @return PromiseInterface */ public function addCurl($ch) { return $this->scheduler->add($ch); } /** * Add delay. * @param int $time * @return PromiseInterface */ public function addDelay($time) { return $this->delayer->add($time); } /** * Run curl_multi_exec() loop. */ public function wait() { curl_multi_exec($this->mh, $active); // Start requests. do { // if cURL handle is running, use curl_multi_select() // otherwise, just sleep until nearest time $this->scheduler->isEmpty() ? $this->delayer->sleep() : curl_multi_select($this->mh, $this->options['interval']) < 0 && usleep($this->options['interval'] * 1000000); curl_multi_exec($this->mh, $active); $this->scheduler->consume(); $this->delayer->consume(); } while (!$this->haltException && (!$this->scheduler->isEmpty() || !$this->delayer->isEmpty())); if ($this->haltException) { throw $this->haltException; } } /** * Used for halting loop. * @param \Throwable|\RuntimeException $e */ public function reserveHaltException($e) { $this->haltException = $e; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/Delayer.php
src/Internal/Delayer.php
<?php namespace mpyw\Co\Internal; use React\Promise\Deferred; use React\Promise\PromiseInterface; class Delayer { /** * Delays to be ended at. * @var array */ private $untils = []; /** * Deferreds. * @var array */ private $deferreds = []; /** * Add delay. * @param int $time * @return PromiseInterface */ public function add($time) { $deferred = new Deferred; $time = filter_var($time, FILTER_VALIDATE_FLOAT); if ($time === false) { throw new \InvalidArgumentException('Delay must be number.'); } if ($time < 0) { throw new \DomainException('Delay must be positive.'); } do { $id = uniqid(); } while (isset($this->untils[$id])); $this->untils[$id] = microtime(true) + $time; $this->deferreds[$id] = $deferred; return $deferred->promise(); } /** * Sleep at least required. */ public function sleep() { $now = microtime(true); $min = null; foreach ($this->untils as $id => $until) { $diff = $until - $now; if ($diff < 0) { // @codeCoverageIgnoreStart return; // @codeCoverageIgnoreEnd } if ($min !== null && $diff >= $min) { continue; } $min = $diff; } $min && usleep($min * 1000000); } /** * Consume delay queue. */ public function consume() { foreach ($this->untils as $id => $until) { $diff = $until - microtime(true); if ($diff > 0.0 || !isset($this->deferreds[$id])) { continue; } $deferred = $this->deferreds[$id]; unset($this->deferreds[$id], $this->untils[$id]); $deferred->resolve(null); } } /** * Is $untils empty? * @return bool */ public function isEmpty() { return !$this->untils; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/ControlException.php
src/Internal/ControlException.php
<?php namespace mpyw\Co\Internal; class ControlException extends \Exception { private $value; /** * Constructor. * @param mixed $value Value to be retrived. */ public function __construct($value) { parent::__construct(); $this->value = $value; } /** * Get value. * @return mixed */ public function getValue() { return $this->value; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/ControlUtils.php
src/Internal/ControlUtils.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\AllFailedException; use mpyw\Co\CoInterface; class ControlUtils { /** * Executed by Co::any() or Co::race(). * @param mixed $value * @param callable $filter self::reverse or self::fail. * @param string $message Used for failure. * @return \Generator */ public static function anyOrRace($value, callable $filter, $message) { $value = YieldableUtils::normalize($value); $yieldables = YieldableUtils::getYieldables($value); $wrapper = self::getWrapperGenerator($yieldables, $filter); try { $results = (yield $wrapper); } catch (ControlException $e) { yield CoInterface::RETURN_WITH => $e->getValue(); } $apply = YieldableUtils::getApplier($value, $yieldables); throw new AllFailedException($message, 0, $apply($results)); } /** * Wrap yieldables with specified filter function. * @param array $yieldables * @param callable $filter self::reverse or self::fail. * @return \Generator */ public static function getWrapperGenerator(array $yieldables, callable $filter) { $gens = []; foreach ($yieldables as $yieldable) { $gens[(string)$yieldable['value']] = $filter($yieldable['value']); } yield CoInterface::RETURN_WITH => (yield $gens); // @codeCoverageIgnoreStart } // @codeCoverageIgnoreEnd /** * Handle success as ControlException, failure as resolved. * @param mixed $yieldable * @return \Generator */ public static function reverse($yieldable) { try { $result = (yield $yieldable); } catch (\RuntimeException $e) { yield CoInterface::RETURN_WITH => $e; } throw new ControlException($result); } /** * Handle success as ControlException. * @param mixed $yieldable * @return \Generator */ public static function fail($yieldable) { throw new ControlException(yield $yieldable); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/CoOption.php
src/Internal/CoOption.php
<?php namespace mpyw\Co\Internal; class CoOption implements \ArrayAccess { /** * Field types. * @var array */ private static $types = [ 'throw' => 'Bool', // Throw CURLExceptions? 'pipeline' => 'Bool', // Use HTTP/1.1 pipelining? 'multiplex' => 'Bool', // Use HTTP/2 multiplexing? 'autoschedule' => 'Bool', // Use AutoScheduler? 'interval' => 'NaturalFloat', // curl_multi_select() timeout 'concurrency' => 'NaturalInt', // Limit of TCP connections ]; /** * Default values. * @var array */ private static $defaults = [ 'throw' => true, 'pipeline' => false, 'multiplex' => true, 'autoschedule' => false, 'interval' => 0.002, 'concurrency' => 6, ]; /** * Actual values. * @var array */ private $options; /** * Set default options. * @param array $options */ public static function setDefault(array $options) { self::$defaults = self::validateOptions($options) + self::$defaults; } /** * Get default options. * @return array $options */ public static function getDefault() { return self::$defaults; } /** * Constructor. * @param array $options */ public function __construct(array $options = []) { $this->options = self::validateOptions($options) + self::$defaults; } /** * Reconfigure to get new instance. * @return CoOption */ public function reconfigure(array $options) { return new self($options + $this->options); } /** * Implemention of ArrayAccess. * @param mixed $offset * @return bool */ public function offsetExists($offset) { return isset($this->options[$offset]); } /** * Implemention of ArrayAccess. * @param mixed $offset * @return mixed */ public function offsetGet($offset) { if (!isset($this->options[$offset])) { throw new \DomainException('Undefined field: ' + $offset); } return $this->options[$offset]; } /** * Implemention of ArrayAccess. * @param mixed $offset * @param mixed $value * @throws BadMethodCallException */ public function offsetSet($offset, $value) { throw new \BadMethodCallException('The instance of CoOptions is immutable.'); } /** * Implemention of ArrayAccess. * @param mixed $offset * @throws BadMethodCallException */ public function offsetUnset($offset) { throw new \BadMethodCallException('The instance of CoOptions is immutable.'); } /** * Validate options. * @param array $options * @return array */ private static function validateOptions(array $options) { foreach ($options as $key => $value) { if (!isset(self::$types[$key])) { throw new \DomainException("Unknown option: $key"); } if ($key === 'autoschedule' && !defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) { throw new \OutOfBoundsException('"autoschedule" can be used only on PHP 7.0.7 or later.'); } $validator = [__CLASS__, 'validate' . self::$types[$key]]; $options[$key] = $validator($key, $value); } return $options; } /** * Validate bool value. * @param string $key * @param mixed $value * @throws InvalidArgumentException * @return bool */ private static function validateBool($key, $value) { $value = filter_var($value, FILTER_VALIDATE_BOOLEAN, [ 'flags' => FILTER_NULL_ON_FAILURE, ]); if ($value === null) { throw new \InvalidArgumentException("Option[$key] must be boolean."); } return $value; } /** * Validate natural float value. * @param string $key * @param mixed $value * @throws InvalidArgumentException * @return float */ private static function validateNaturalFloat($key, $value) { $value = filter_var($value, FILTER_VALIDATE_FLOAT); if ($value === false) { throw new \InvalidArgumentException("Option[$key] must be float."); } if ($value < 0.0) { throw new \DomainException("Option[$key] must be positive or zero."); } return $value; } /** * Validate natural int value. * @param string $key * @param mixed $value * @throws InvalidArgumentException * @return int */ private static function validateNaturalInt($key, $value) { $value = filter_var($value, FILTER_VALIDATE_INT); if ($value === false) { throw new \InvalidArgumentException("Option[$key] must be integer."); } if ($value < 0) { throw new \DomainException("Option[$key] must be positive or zero."); } return $value; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/AutoScheduler.php
src/Internal/AutoScheduler.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\CURLException; use React\Promise\Deferred; use React\Promise\PromiseInterface; class AutoScheduler extends AbstractScheduler { /** * Constructor. * Initialize cURL multi handle. * @param CoOption $options * @param resource $mh curl_multi */ public function __construct(CoOption $options, $mh) { curl_multi_setopt($mh, CURLMOPT_MAX_TOTAL_CONNECTIONS, $options['concurrency']); $this->mh = $mh; $this->options = $options; } /** * Call curl_multi_add_handle(). * @param resource $ch * @return PromiseInterface */ public function add($ch) { $deferred = new Deferred; $errno = curl_multi_add_handle($this->mh, $ch); if ($errno !== CURLM_OK) { // @codeCoverageIgnoreStart $msg = curl_multi_strerror($errno) . ": $ch"; $deferred->reject(new \RuntimeException($msg)); return $deferred->promise(); // @codeCoverageIgnoreEnd } $this->added[(string)$ch] = $ch; $this->deferreds[(string)$ch] = $deferred; return $deferred->promise(); } /** * Are there no cURL handles? * @return bool */ public function isEmpty() { return !$this->added; } /** * Do nothing. */ protected function interruptConsume() {} }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/TypeUtils.php
src/Internal/TypeUtils.php
<?php namespace mpyw\Co\Internal; class TypeUtils { /** * Check if value is a valid cURL handle. * @param mixed $value * @return bool */ public static function isCurl($value) { return is_resource($value) && get_resource_type($value) === 'curl'; } /** * Check if value is a valid Generator. * @param mixed $value * @return bool */ public static function isGeneratorContainer($value) { return $value instanceof GeneratorContainer; } /** * Check if value is a valid Generator closure. * @param mixed $value * @return bool */ public static function isGeneratorClosure($value) { return $value instanceof \Closure && (new \ReflectionFunction($value))->isGenerator(); } /** * Check if value is Throwable, excluding RuntimeException. * @param mixed $value * @return bool */ public static function isFatalThrowable($value) { return !$value instanceof \RuntimeException && ($value instanceof \Throwable || $value instanceof \Exception); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/AbstractScheduler.php
src/Internal/AbstractScheduler.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\CURLException; use React\Promise\PromiseInterface; abstract class AbstractScheduler { /** * cURL multi handle. * @var resource */ protected $mh; /** * Options. * @var CoOption */ protected $options; /** * cURL handles those have been already dispatched. * @var array */ protected $added = []; /** * Deferreds. * @var array */ protected $deferreds = []; /** * Constructor. * Initialize cURL multi handle. * @param CoOption $options * @param resource $mh curl_multi */ abstract public function __construct(CoOption $options, $mh); /** * Call curl_multi_add_handle() or push into queue. * @param resource $ch * @return PromiseInterface */ abstract public function add($ch); /** * Are there no cURL handles? * @return bool */ abstract public function isEmpty(); /** * Do somthing with consumed handle. */ abstract protected function interruptConsume(); /** * Poll completed cURL entries, consume cURL queue and resolve them. */ public function consume() { $entries = $this->readCompletedEntries(); foreach ($entries as $entry) { curl_multi_remove_handle($this->mh, $entry['handle']); unset($this->added[(string)$entry['handle']]); $this->interruptConsume(); } $this->resolveEntries($entries); } /** * Poll completed cURL entries. * @return array */ protected function readCompletedEntries() { $entries = []; // DO NOT call curl_multi_add_handle() until polling done while ($entry = curl_multi_info_read($this->mh)) { $entries[] = $entry; } return $entries; } /** * Resolve polled cURLs. * @param array $entries Polled cURL entries. */ protected function resolveEntries(array $entries) { foreach ($entries as $entry) { $deferred = $this->deferreds[(string)$entry['handle']]; unset($this->deferreds[(string)$entry['handle']]); $entry['result'] === CURLE_OK ? $deferred->resolve(curl_multi_getcontent($entry['handle'])) : $deferred->reject(new CURLException(curl_error($entry['handle']), $entry['result'], $entry['handle'])); } } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/YieldableUtils.php
src/Internal/YieldableUtils.php
<?php namespace mpyw\Co\Internal; use React\Promise\PromiseInterface; class YieldableUtils { /** * Recursively normalize value. * Generator Closure -> GeneratorContainer * Array -> Array (children's are normalized) * Others -> Others * @param mixed $value * @param mixed $yield_key * @return mixed */ public static function normalize($value, $yield_key = null) { if (TypeUtils::isGeneratorClosure($value)) { $value = $value(); } if ($value instanceof \Generator) { return new GeneratorContainer($value, $yield_key); } if (is_array($value)) { $tmp = []; foreach ($value as $k => $v) { $tmp[$k] = self::normalize($v, $yield_key); } return $tmp; } return $value; } /** * Recursively search yieldable values. * Each entries are assoc those contain keys 'value' and 'keylist'. * value -> the value itself. * keylist -> position of the value. nests are represented as array values. * @param mixed $value Must be already normalized. * @param array $keylist Internally used. * @param array &$runners Running cURL or Generator identifiers. * @return array */ public static function getYieldables($value, array $keylist = [], array &$runners = []) { $r = []; if (!is_array($value)) { if (TypeUtils::isCurl($value) || TypeUtils::isGeneratorContainer($value)) { if (isset($runners[(string)$value])) { throw new \DomainException('Duplicated cURL resource or Generator instance found.'); } $r[(string)$value] = $runners[(string)$value] = [ 'value' => $value, 'keylist' => $keylist, ]; } return $r; } foreach ($value as $k => $v) { $newlist = array_merge($keylist, [$k]); $r = array_merge($r, self::getYieldables($v, $newlist, $runners)); } return $r; } /** * Return function that apply changes in yieldables. * @param mixed $yielded * @param array $yieldables * @param callable|null $next * @return mixed */ public static function getApplier($yielded, array $yieldables, callable $next = null) { return function (array $results) use ($yielded, $yieldables, $next) { foreach ($results as $hash => $resolved) { $current = &$yielded; foreach ($yieldables[$hash]['keylist'] as $key) { $current = &$current[$key]; } $current = $resolved; unset($current); } return $next ? $next($yielded) : $yielded; }; } /** * Return Promise that absorbs rejects, excluding fatal Throwable. * @param PromiseInterface $promise * @return PromiseInterface */ public static function safePromise(PromiseInterface $promise) { return $promise->then(null, function ($value) { if (TypeUtils::isFatalThrowable($value)) { throw $value; } return $value; }); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/src/Internal/GeneratorContainer.php
src/Internal/GeneratorContainer.php
<?php namespace mpyw\Co\Internal; use mpyw\Co\CoInterface; class GeneratorContainer { /** * Generator. * @var \Generator */ private $g; /** * Generator object hash. * @var string */ private $h; /** * Thrown exception. * @var \Throwable|\Exception */ private $e; /** * Parent yield key. * @var mixed */ private $yieldKey; /** * Constructor. * @param \Generator $g */ public function __construct(\Generator $g, $yield_key = null) { $this->g = $g; $this->h = spl_object_hash($g); $this->yieldKey = $yield_key; $this->valid(); } /** * Return parent yield key. * @return mixed */ public function getYieldKey() { return $this->yieldKey; } /** * Return generator hash. * @return string */ public function __toString() { return $this->h; } /** * Return whether generator is actually working. * @return bool */ public function valid() { try { $this->g->current(); return $this->e === null && $this->g->valid() && $this->g->key() !== CoInterface::RETURN_WITH; } catch (\Throwable $e) {} catch (\Exception $e) {} $this->e = $e; return false; } /** * Return current key. * @return mixed */ public function key() { $this->validateValidity(); return $this->g->key(); } /** * Return current value. * @return mixed */ public function current() { $this->validateValidity(); return $this->g->current(); } /** * Send value into generator. * @param mixed $value * @NOTE: This method returns nothing, * while original generator returns something. */ public function send($value) { $this->validateValidity(); try { $this->g->send($value); return; } catch (\Throwable $e) {} catch (\Exception $e) {} $this->e = $e; } /** * Throw exception into generator. * @param \Throwable|\Exception $e * @NOTE: This method returns nothing, * while original generator returns something. */ public function throw_($e) { $this->validateValidity(); try { $this->g->throw($e); return; } catch (\Throwable $e) {} catch (\Exception $e) {} $this->e = $e; } /** * Return whether Throwable is thrown. * @return bool */ public function thrown() { return $this->e !== null; } /** * Return value that generator has returned or thrown. * @return mixed */ public function getReturnOrThrown() { $this->validateInvalidity(); if ($this->e === null && $this->g->valid() && !$this->valid()) { return $this->g->current(); } if ($this->e) { return $this->e; } return method_exists($this->g, 'getReturn') ? $this->g->getReturn() : null; } /** * Validate that generator has finished running. * @throws \BadMethodCallException */ private function validateValidity() { if (!$this->valid()) { throw new \BadMethodCallException('Unreachable here.'); } } /** * Validate that generator is still running. * @throws \BadMethodCallException */ private function validateInvalidity() { if ($this->valid()) { throw new \BadMethodCallException('Unreachable here.'); } } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_bootstrap.php
tests/_bootstrap.php
<?php // This is global bootstrap for autoloading include __DIR__.'/../vendor/autoload.php'; // composer autoload \Codeception\Specify\Config::setDeepClone(false); $kernel = \AspectMock\Kernel::getInstance(); $kernel->init([ 'debug' => true, 'includePaths' => [__DIR__ . '/../src'], ]);
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/acceptance/_bootstrap.php
tests/acceptance/_bootstrap.php
<?php // Here you can initialize variables that will be available to your tests
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/PoolTest.php
tests/unit/PoolTest.php
<?php require_once __DIR__ . '/DummyCurl.php'; require_once __DIR__ . '/DummyCurlMulti.php'; require_once __DIR__ . '/DummyCurlFunctions.php'; use mpyw\Co\Co; use mpyw\Co\CoInterface; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\Pool; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; use AspectMock\Test as test; use React\Promise\Deferred; /** * @requires PHP 7.0 */ class PoolTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $pool; public function _before() { test::double('mpyw\Co\Internal\TypeUtils', ['isCurl' => function ($arg) { return $arg instanceof \DummyCurl; }]); } public function _after() { test::clean(); } public function testInvalidDelayType() { $pool = new Pool(new CoOption(['concurrency' => 3])); $this->setExpectedException(\InvalidArgumentException::class); $pool->addDelay([], new Deferred); } public function testInvalidDelayDomain() { $pool = new Pool(new CoOption(['concurrency' => 3])); $this->setExpectedException(\DomainException::class); $pool->addDelay(-1, new Deferred); } public function testCurlWithoutDeferred() { $pool = new Pool(new CoOption); $pool->addCurl(new DummyCurl('valid', 1)); $pool->addCurl(new DummyCurl('invalid', 1, true)); $pool->wait(); $this->assertTrue(true); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/DummyCurlMulti.php
tests/unit/DummyCurlMulti.php
<?php class DummyCurlMulti { private $pool = []; private $execCount = 0; public function addHandle($ch) : int { if (isset($this->pool[(string)$ch])) { return 7; } $this->pool[(string)$ch] = $ch; return 0; } public function removeHandle($ch) : int { unset($this->pool[(string)$ch]); return 0; } public function exec(&$active) : int { $active = 0; foreach ($this->pool as $ch) { if ($ch->prepared() || $ch->running()) { $ch->update($this->execCount); if ($ch->running()) { $active = 1; } } } ++$this->execCount; return 0; } public function infoRead(&$msgs_in_queue) { $i = 0; foreach ($this->pool as $ch) { ++$i; if ($ch->done() && !$ch->alreadyRead()) { $ch->read(); $msgs_in_queue = count($this->pool) - $i; return [ 'handle' => $ch, 'result' => $ch->errno(), ]; } } return false; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/AutoPoolTest.php
tests/unit/AutoPoolTest.php
<?php require_once __DIR__ . '/DummyCurl.php'; require_once __DIR__ . '/DummyCurlMulti.php'; require_once __DIR__ . '/DummyCurlFunctions.php'; use mpyw\Co\Co; use mpyw\Co\CoInterface; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\Pool; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; use AspectMock\Test as test; use React\Promise\Deferred; /** * @requires PHP 7.0.7 */ class AutoPoolTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $pool; public function _before() { test::double('mpyw\Co\Internal\TypeUtils', ['isCurl' => function ($arg) { return $arg instanceof \DummyCurl; }]); } public function _after() { test::clean(); } public function testInvalidOption() { $this->setExpectedException(\OutOfBoundsException::class); $pool = new Pool(new CoOption(['autoschedule' => true])); } public function testWait() { $pool = new Pool(new CoOption(['concurrency' => 1, 'autoschedule' => true])); $curls = []; foreach (range(1, 100) as $i) { $curls[] = new DummyCurl($i, 2); } $done = []; foreach ($curls as $ch) { $pool->addCurl($ch)->then( function ($result) use (&$done) { $done[] = $result; }, function () { $this->assertTrue(false); } );; } $pool->wait(); foreach ($curls as $curl) { $str = str_replace('DummyCurl', 'Response', (string)$curl); $this->assertContains($str, $done); $this->assertEquals([0, 2], [$curl->startedAt(), $curl->stoppedAt()]); } } public function testUnlimitedConcurrency() { $pool = new Pool(new CoOption(['concurrency' => 0, 'autoschedule' => true])); $curls = []; foreach (range(1, 100) as $i) { $curls[] = new DummyCurl($i, 2); } $done = []; foreach ($curls as $ch) { $pool->addCurl($ch)->then( function ($result) use (&$done) { $done[] = $result; }, function () { $this->assertTrue(false); } );; } $pool->wait(); foreach ($curls as $curl) { $str = str_replace('DummyCurl', 'Response', (string)$curl); $this->assertContains($str, $done); $this->assertEquals([0, 2], [$curl->startedAt(), $curl->stoppedAt()]); } } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/ControlTest.php
tests/unit/ControlTest.php
<?php require_once __DIR__ . '/DummyCurl.php'; require_once __DIR__ . '/DummyCurlMulti.php'; require_once __DIR__ . '/DummyCurlFunctions.php'; use mpyw\Co\Co; use mpyw\Co\CoInterface; use mpyw\Co\CURLException; use mpyw\Co\AllFailedException; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\Pool; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; use AspectMock\Test as test; /** * @requires PHP 7.0 */ class ControlTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $pool; public function _before() { test::double('mpyw\Co\Internal\TypeUtils', ['isCurl' => function ($arg) { return $arg instanceof \DummyCurl; }]); } public function _after() { test::clean(); } public function testRaceSuccess() { $r = Co::wait(Co::race([ new DummyCurl('A', 3, true), new DummyCurl('B', 2), ])); $this->assertEquals('Response[B]', $r); } public function testRaceFailure() { $this->setExpectedException(CURLException::class, 'Error[B]'); $r = Co::wait(Co::race([ new DummyCurl('A', 3), new DummyCurl('B', 2, true), ])); } public function testRaceEmpty() { try { Co::wait(Co::race(['A', 'B'])); $this->assertTrue(false); } catch (AllFailedException $e) { $this->assertEquals('Co::race() failed.', $e->getMessage()); $this->assertEquals(['A', 'B'], $e->getReasons()); } } public function testAnyAllSuccess() { $r = Co::wait(Co::any([ new DummyCurl('A', 3), new DummyCurl('B', 2), ])); $this->assertEquals('Response[B]', $r); } public function testAnyPartialSuccess() { $r = Co::wait(Co::any([ new DummyCurl('A', 3), new DummyCurl('B', 2, true), ])); $this->assertEquals('Response[A]', $r); } public function testAnyAllFailure() { try { Co::wait(Co::any([ new DummyCurl('A', 3, true), new DummyCurl('B', 2, true), ])); $this->assertTrue(false); } catch (AllFailedException $e) { $this->assertEquals('Co::any() failed.', $e->getMessage()); $this->assertEquals('Error[A]', $e->getReasons()[0]->getMessage()); $this->assertEquals('Error[B]', $e->getReasons()[1]->getMessage()); } } public function testAnyEmpty() { try { Co::wait(Co::any(['A', 'B'])); $this->assertTrue(false); } catch (AllFailedException $e) { $this->assertEquals('Co::any() failed.', $e->getMessage()); $this->assertEquals(['A', 'B'], $e->getReasons()); } } public function testAll() { $a = new DummyCurl('A', 3); $b = new DummyCurl('B', 2); $r = Co::wait(Co::all([$a, $b])); $this->assertEquals('Response[A]', $r[0]); $this->assertEquals('Response[B]', $r[1]); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/CoTest.php
tests/unit/CoTest.php
<?php require_once __DIR__ . '/DummyCurl.php'; require_once __DIR__ . '/DummyCurlMulti.php'; require_once __DIR__ . '/DummyCurlFunctions.php'; use mpyw\Co\Co; use mpyw\Co\CoInterface; use mpyw\Co\CURLException; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\Pool; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; use AspectMock\Test as test; /** * @requires PHP 7.0 */ class CoTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $pool; public function _before() { test::double('mpyw\Co\Internal\TypeUtils', ['isCurl' => function ($arg) { return $arg instanceof \DummyCurl; }]); if (!defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) { define('CURLMOPT_MAX_TOTAL_CONNECTIONS', 13); } } public function _after() { test::clean(); } public function testRunningTrue() { $result = null; Co::wait(function () use (&$result) { yield; $result = Co::isRunning(); }); $this->assertSame(true, $result); } public function testRunningFalse() { $result = Co::isRunning(); $this->assertSame(false, $result); } public function testSetDefaultOptions() { try { $this->assertTrue(Proxy::get(CoOption::class)->getStatic('defaults')['throw']); Co::setDefaultOptions(['throw' => false]); $this->assertFalse(Proxy::get(CoOption::class)->getStatic('defaults')['throw']); } finally { Co::setDefaultOptions(['throw' => true]); } } public function testGetDefaultOptions() { $expected = Proxy::get(CoOption::class)->getStatic('defaults'); $actual = Co::getDefaultOptions(); $this->assertEquals($expected, $actual); } public function testWaitBasic() { $this->assertEquals([1], Co::wait([1])); $genfunc = function () { $x = yield 3; $y = yield 2; return $x + $y; }; $this->assertEquals(5, Co::wait($genfunc)); $genfunc = function () { $x = yield function () { yield Co::RETURN_WITH => yield function () { return yield function () { return 3; yield; }; yield; }; yield; }; $y = yield 2; return $x + $y; }; $this->assertEquals(5, Co::wait($genfunc)); $genfunc = function () { yield; return array_sum(array_map('current', yield [ [function () { return 7; yield; }], [function () { return 9; yield; }], [function () { yield; return 13; }], ])); }; $this->assertEquals(29, Co::wait($genfunc)); } public function testAsyncBasic() { $i = 0; $genfunc = function () use (&$i) { yield; Co::async(function () use (&$i) { yield; ++$i; }); Co::async(function () use (&$i) { yield; ++$i; }); }; Co::wait($genfunc); $this->assertEquals($i, 2); } public function testAsyncOverridesThrowInvalid() { $this->setExpectedException(\InvalidArgumentException::class); $r = Co::wait(function () { yield; Co::async(function () { yield; throw new \RuntimeException; }, []); return 'done'; }, ['throw' => false]); } public function testAsyncOverridesThrowTrue() { $this->setExpectedException(\RuntimeException::class); Co::wait(function () { yield; Co::async(function () { yield; throw new \RuntimeException; }, true); }, ['throw' => false]); } public function testAsyncOverridesThrowFalse() { $r = Co::wait(function () { yield; Co::async(function () { yield; throw new \RuntimeException; }, false); return 'done'; }, ['throw' => true]); $this->assertEquals('done', $r); } public function testWaitCurl() { $result = Co::wait([ 'A' => new DummyCurl('A', mt_rand(1, 10)), [ 'B' => new DummyCurl('B', mt_rand(1, 10)), ], [ [ 'C' => new DummyCurl('C', mt_rand(1, 10)), ] ] ]); $this->assertEquals([ 'A' => 'Response[A]', [ 'B' => 'Response[B]', ], [ [ 'C' => 'Response[C]', ], ], ], $result); } public function testRuntimeExceptionCaptured() { $e = Co::wait(function () { $e = yield Co::SAFE => function () { yield; throw new \RuntimeException; }; $this->assertInstanceOf(\RuntimeException::class, $e); return $e; }); $this->assertInstanceOf(\RuntimeException::class, $e); } public function testRuntimeExceptionThrown() { $this->setExpectedException(\RuntimeException::class); Co::wait(function () { yield function () { yield; throw new \RuntimeException; }; }); } public function testRuntimeExceptionTrappedTopLevel() { $e = Co::wait(function () { yield function () { yield; throw new \RuntimeException; }; }, ['throw' => false]); $this->assertInstanceOf(\RuntimeException::class, $e); } public function testRuntimeExceptionCapturedDerivedFromReturn() { $e = Co::wait(function () { $e = yield Co::SAFE => function () { return function () { yield; throw new \RuntimeException; }; yield; }; $this->assertInstanceOf(\RuntimeException::class, $e); return $e; }); $this->assertInstanceOf(\RuntimeException::class, $e); } public function testLogicExceptionHandling() { Co::wait(function () { try { yield function () { yield; throw new \LogicException; }; } catch (\LogicException $e) { $this->assertTrue(true); } }, ['throw' => false]); $this->setExpectedException(\LogicException::class); Co::wait(function () { yield function () { yield; throw new \LogicException; }; }, ['throw' => false]); } public function testComplicated01() { $expected = ['Response[1]', 'Response[7]']; $actual = Co::wait([new DummyCurl('1', 7), function () { $expected = ['Response[2]', 'Response[3]']; $actual = yield [new DummyCurl('2', 3), new DummyCurl('3', 4)]; $this->assertEquals($expected, $actual); $expected = ['Response[5]', ['x' => ['y' => 'Response[6]']]]; $actual = yield [ function () { $this->assertEquals('Response[4]', yield new DummyCurl('4', 1)); return new DummyCurl('5', 1); }, function () { $e = yield CO::SAFE => new DummyCurl('invalid-01', 1, true); $this->assertInstanceOf(CURLException::class, $e); $this->assertEquals('Error[invalid-01]', $e->getMessage()); try { yield new DummyCurl('invalid-02', 1, true); $this->assertTrue(false); } catch (CURLException $e) { $this->assertEquals('Error[invalid-02]', $e->getMessage()); } return ['x' => ['y' => function () { yield; return new DummyCurl('6', 2); }]]; } ]; $this->assertEquals($expected, $actual); return new DummyCurl('7', 1); }]); $this->assertEquals($expected, $actual); } public function testComplicated02() { $expected = ['Response[1]', 'Response[4]']; $actual = Co::wait([new DummyCurl('1', 5), function () { $y = yield Co::SAFE => [ new DummyCurl('2', 3), function () { yield; throw new \RuntimeException('01'); }, ]; $this->assertEquals('Response[2]', $y[0]); $this->assertInstanceOf(\RuntimeException::class, $y[1]); $this->assertEquals('01', $y[1]->getMessage()); $y = yield Co::SAFE => [ function () { $this->assertEquals('Response[3]', yield new DummyCurl('3', 1)); $y = yield Co::SAFE => function () { yield; throw new \RuntimeException('02'); }; $this->assertInstanceOf(\RuntimeException::class, $y); $this->assertEquals('02', $y->getMessage()); yield Co::SAFE => function () { yield; throw new \RuntimeException('03'); }; $this->assertTrue(false); }, function () { $y = yield Co::SAFE => function () { yield; throw new \RuntimeException('04'); }; $this->assertInstanceOf(\RuntimeException::class, $y); $this->assertEquals('04', $y->getMessage()); yield Co::SAFE => function () { yield; throw new \RuntimeException('05'); }; $this->assertTrue(false); } ]; $y = yield Co::SAFE => function () { yield function () { $y = yield Co::SAFE => function () { yield function () { yield new DummyCurl('invalid', 1, true); }; }; throw $y; }; }; $this->assertInstanceOf(CURLException::class, $y); $this->assertEquals('Error[invalid]', $y->getMessage()); return new DummyCurl('4', 1); }]); $this->assertEquals($expected, $actual); } public function testComplicatedAsync() { $async_results = []; $sync_results = Co::wait([new DummyCurl('5', 1), function () use (&$async_results) { yield; Co::async(function () use (&$async_results) { $async_results[] = yield new DummyCurl('2', 6); Co::async(function () use (&$async_results) { $async_results[] = yield new DummyCurl('4', 4); }); $async_results[] = yield new DummyCurl('3', 3); }); Co::async(function () use (&$async_results) { $async_results[] = yield new DummyCurl('1', 1); }); return new DummyCurl('6', 2); }]); $this->assertEquals(['Response[5]', 'Response[6]'], $sync_results); $this->assertEquals(['Response[1]', 'Response[2]', 'Response[3]', 'Response[4]'], $async_results); } public function testDelay() { $results = Co::wait([ function () use (&$x1, &$y1) { yield Co::DELAY => 0.5; $x1 = microtime(true); yield Co::DELAY => 1.5; $y1 = microtime(true); return true; }, function () use (&$x2, &$y2) { yield Co::DELAY => 0.6; $x2 = microtime(true); yield Co::DELAY => 0.7; $y2 = microtime(true); throw new \RuntimeException; }, ], ['throw' => false]); $this->assertNotNull($x1); $this->assertNotNull($y1); $this->assertNotNull($x2); $this->assertNotNull($y2); $this->assertTrue($x1 < $x2); $this->assertTrue($x2 < $y2); $this->assertTrue($y2 < $y1); $this->assertTrue($results[0]); $this->assertInstanceOf(\RuntimeException::class, $results[1]); } public function testBadWaitCall() { $this->setExpectedException(\BadMethodCallException::class); Co::wait(function () { yield; Co::wait(1); }); } public function testBadAsyncCall() { $this->setExpectedException(\BadMethodCallException::class); Co::async(1); } public function testUncaughtRuntimeExceptionInClosureParallelToInfiniteDelayLoop() { $this->setExpectedException(\RuntimeException::class); Co::wait([ function () { while (true) { yield Co::SLEEP => 0.1; } }, function () { yield; throw new \RuntimeException; } ]); } public function testUncaughtRuntimeExceptionInGeneratorParallelToInfiniteDelayLoop() { $this->setExpectedException(\RuntimeException::class); Co::wait([ function () { while (true) { yield Co::SLEEP => 0.1; } }, function () { yield; throw new \RuntimeException; } ]); } public function testDuplicatedGenerators() { $this->setExpectedException(\DomainException::class); $func = function () { yield Co::DELAY => 0.01; }; $gen = $func(); Co::wait([$gen, $gen]); } public function testDuplicatedAdd() { $this->setExpectedException(\DomainException::class, 'Duplicated cURL resource or Generator instance found.'); Co::wait([ new DummyCurl('A', 2), new DummyCurl('B', 3), new DummyCurl('C', 4), new DummyCurl('C', 5), ], ['concurrency' => 4]); } public function testDuplicatedEnqueue() { $this->setExpectedException(\DomainException::class, 'Duplicated cURL resource or Generator instance found.'); Co::wait([ new DummyCurl('A', 2), new DummyCurl('B', 3), new DummyCurl('C', 4), new DummyCurl('C', 5), ], ['concurrency' => 2]); } public function testDuplicatedBetweenAddAndEnqueue() { $this->setExpectedException(\DomainException::class, 'Duplicated cURL resource or Generator instance found.'); Co::wait([ new DummyCurl('A', 2), new DummyCurl('B', 3), new DummyCurl('C', 4), new DummyCurl('C', 5), ], ['concurrency' => 3]); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/DummyCurl.php
tests/unit/DummyCurl.php
<?php class DummyCurl { private $multiHandle; private $identifier; private $cost; private $reservedErrno; private $reservedErrstr; private $reservedResponse; private $counter = 0; private $read = false; private $response = ''; private $errno = -1; private $errstr = ''; private $startedAt = -1; private $stoppedAt = -1; public function setMultiHandle(DummyCurlMulti $mh) { $this->multiHandle = $mh; } public function getMultiHandle(DummyCurlMulti $mh) { return $this->multiHandle; } public function __construct(string $identifier, int $cost, bool $error = false) { assert($cost > 0); $this->identifier = "DummyCurl[$identifier]"; $this->cost = $cost; if (!$error) { $this->reservedErrno = 0; $this->reservedErrstr = ''; $this->reservedResponse = "Response[$identifier]"; } else { $this->reservedErrno = 1; $this->reservedErrstr = "Error[$identifier]"; $this->reservedResponse = ''; } $this->reset(); } public function reset() { $this->counter = $this->cost; $this->read = false; $this->response = ''; $this->errno = 0; $this->errstr = ''; $this->startedAt = -1; $this->stoppedAt = -1; } public function __toString() : string { return $this->identifier; } public function getContent() : string { return $this->response; } public function errno() : int { return $this->errno; } public function errstr() : string { return $this->errstr; } public function prepared() : bool { return $this->counter === $this->cost; } public function running() : bool { return $this->counter > 0 && $this->counter < $this->cost; } public function done() : bool { return $this->counter === 0; } public function update(int $exec_count) { assert($this->counter > 0); if ($this->startedAt === -1) { $this->startedAt = $exec_count; } elseif (--$this->counter === 0) { $this->stoppedAt = $exec_count; $this->response = $this->reservedResponse; $this->errno = $this->reservedErrno; $this->errstr = $this->reservedErrstr; } } public function read() { $this->read = true; } public function alreadyRead() : bool { return $this->read; } public function startedAt() : int { return $this->startedAt; } public function stoppedAt() : int { return $this->stoppedAt; } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/_bootstrap.php
tests/unit/_bootstrap.php
<?php // Here you can initialize variables that will be available to your tests // function vd(...$args) { ob_start(); var_dump(...$args); $data = ob_get_clean(); file_put_contents('php://stderr', "\n$data\n"); }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/CoOptionTest.php
tests/unit/CoOptionTest.php
<?php use mpyw\Co\Internal\CoOption; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; /** * @requires PHP 7.0 */ class CoOptionTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $CoOption; public function _before() { $this->default = CoOption::getDefault(); self::$CoOption = Proxy::get(CoOption::class); } public function _after() { CoOption::setDefault($this->default); } public function testConstructor() { $this->specify('default construction', function () { $options = new CoOption(); $defaults = self::$CoOption::getStatic('defaults'); foreach ($defaults as $key => $value) { $this->assertEquals($value, $options[$key]); } }); $this->specify('custom construction', function () { $def = [ 'throw' => false, 'pipeline' => true, 'multiplex' => false, 'interval' => 0.3, 'concurrency' => 1, ]; $options = new CoOption($def); foreach ($def as $key => $value) { $this->assertEquals($value, $options[$key]); } }); } public function testStaticDefaults() { $def = [ 'throw' => false, 'pipeline' => true, 'multiplex' => false, 'interval' => 0.3, 'concurrency' => 1, ]; CoOption::setDefault($def); $options = CoOption::getDefault(); foreach ($def as $key => $value) { $this->assertEquals($value, $options[$key]); } } public function testValidateNaturalInt() { $this->assertEquals(self::$CoOption::validateNaturalInt('', 1), 1); $this->assertEquals(self::$CoOption::validateNaturalInt('', '3'), 3); $this->assertEquals(self::$CoOption::validateNaturalInt('', 3.0), 3); $invalid_cases = [ function () { self::$CoOption::validateNaturalInt('', []); }, function () { self::$CoOption::validateNaturalInt('', '3.0'); }, function () { self::$CoOption::validateNaturalInt('', INF); }, ]; foreach ($invalid_cases as $i => $case) { $this->specify("invalid types ($i)", $case, ['throws' => \InvalidArgumentException::class]); } $invalid_cases = [ function () { self::$CoOption::validateNaturalInt('', -1); }, ]; foreach ($invalid_cases as $i => $case) { $this->specify("invalid domains ($i)", $case, ['throws' => \DomainException::class]); } } public function testValidateNaturalFloat() { $this->assertEquals(self::$CoOption::validateNaturalFloat('', 1), 1.0); $this->assertEquals(self::$CoOption::validateNaturalFloat('', '3'), 3.0); $this->assertEquals(self::$CoOption::validateNaturalFloat('', 3.0), 3.0); $this->assertEquals(self::$CoOption::validateNaturalFloat('', '3.0'), 3.0); $invalid_cases = [ function () { self::$CoOption::validateNaturalFloat('', []); }, function () { self::$CoOption::validateNaturalFloat('', INF); }, ]; foreach ($invalid_cases as $i => $case) { $this->specify("invalid types ($i)", $case, ['throws' => \InvalidArgumentException::class]); } $invalid_cases = [ function () { self::$CoOption::validateNaturalFloat('', -1.0); }, ]; foreach ($invalid_cases as $i => $case) { $this->specify("invalid domains ($i)", $case, ['throws' => \DomainException::class]); } } public function testValidateBool() { $this->assertEquals(self::$CoOption::validateBool('', true), true); $this->assertEquals(self::$CoOption::validateBool('', false), false); $this->assertEquals(self::$CoOption::validateBool('', 'true'), true); $this->assertEquals(self::$CoOption::validateBool('', 'false'), false); $this->assertEquals(self::$CoOption::validateBool('', 'yes'), true); $this->assertEquals(self::$CoOption::validateBool('', 'no'), false); $this->assertEquals(self::$CoOption::validateBool('', '1'), true); $this->assertEquals(self::$CoOption::validateBool('', '0'), false); $this->specify('invalid', function () { self::$CoOption::validateBool('', []); }, ['throws' => \InvalidArgumentException::class]); } public function testReconfigure() { $options = new CoOption(); $new_options = $options->reconfigure(['pipeline' => true]); $this->assertTrue($new_options['pipeline']); $this->assertNotEquals($new_options, $options); } public function testSpecialMethodCall() { $options = new CoOption(); $this->assertTrue(isset($options['pipeline'])); $this->assertFalse(isset($options['invalid'])); $this->specify('invalid construction', function () use ($options) { new CoOption(['invalid' => true]); }, ['throws' => \DomainException::class]); $this->specify('invalid assignment', function () use ($options) { $options['pipeline'] = false; }, ['throws' => \BadMethodCallException::class]); $this->specify('invalid unset', function () use ($options){ unset($options['pipeline']); }, ['throws' => \BadMethodCallException::class]); $this->specify('Undefined field', function () use ($options){ $options['invalid']; }, ['throws' => \DomainException::class]); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/GeneratorContainerTest.php
tests/unit/GeneratorContainerTest.php
<?php use mpyw\Co\CoInterface; use mpyw\Co\Internal\GeneratorContainer; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; /** * @requires PHP 7.0 */ class GeneratorContainerTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $GeneratorContainer; public function _before() { self::$GeneratorContainer = Proxy::get(GeneratorContainer::class); } public function _after() { } public function testConstructor() { $gen = (function () { yield 1; })(); $con = self::$GeneratorContainer::new($gen); $this->assertEquals($gen, $con->g); $this->assertEquals(spl_object_hash($gen), $con->h); } public function testToString() { $gen = (function () { yield 1; })(); $con = new GeneratorContainer($gen); $this->assertEquals(spl_object_hash($gen), (string)$con); } public function testNormalFlow() { $gen = (function () { $this->assertEquals(2, yield 1); $this->assertEquals(4, yield 3); return 5; })(); $con = new GeneratorContainer($gen); $this->assertEquals($con->current(), 1); $con->send(2); $this->assertEquals($con->current(), 3); $con->send(4); $this->assertFalse($con->valid()); $this->assertEquals(5, $con->getReturnOrThrown()); $this->setExpectedException(\LogicException::class); $con->send(null); } public function testPseudoReturn() { $gen = (function () { $this->assertEquals(2, yield 1); $this->assertEquals(4, yield 3); yield CoInterface::RETURN_WITH => 5; })(); $con = new GeneratorContainer($gen); $this->assertEquals($con->current(), 1); $con->send(2); $this->assertEquals($con->current(), 3); $con->send(4); $this->assertFalse($con->valid()); $this->assertEquals(5, $con->getReturnOrThrown()); $this->setExpectedException(\LogicException::class); $con->send(null); } public function testInvalidGetReturn() { $gen = (function () { yield null; yield null; })(); $con = new GeneratorContainer($gen); $this->setExpectedException(\LogicException::class); $con->getReturnOrThrown(); } public function testInternalException() { $genfunc = function () { throw new \RuntimeException; yield null; yield null; }; $con = new GeneratorContainer($genfunc()); $this->assertFalse($con->valid()); $this->assertTrue($con->thrown()); $this->assertInstanceOf(\RuntimeException::class, $con->getReturnOrThrown()); } public function testExternalException() { $gen = (function () { $this->assertInstanceOf(\RuntimeException::class, yield CoInterface::SAFE => null); yield null; })(); $con = new GeneratorContainer($gen); $con->key() === CoInterface::SAFE ? $con->send(new \RuntimeException) : $con->throw_(new \RuntimeException); $this->assertTrue($con->valid()); $this->assertFalse($con->thrown()); $gen = (function () { yield null; yield null; })(); $con = new GeneratorContainer($gen); $con->key() === CoInterface::SAFE ? $con->send(new \RuntimeException) : $con->throw_(new \RuntimeException); $this->assertFalse($con->valid()); $this->assertTrue($con->thrown()); $this->assertInstanceOf(\RuntimeException::class, $con->getReturnOrThrown()); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/DummyCurlFunctions.php
tests/unit/DummyCurlFunctions.php
<?php namespace mpyw\Co\Internal; function defined(string $name) : bool { if (!\defined($name)) { define($name, 114514); } foreach (debug_backtrace() as $trace) { if (isset($trace['class']) && $trace['class'] === 'AutoPoolTest') { return $trace['function'] !== 'testInvalidOption'; } } return \defined($name); } function curl_errno(\DummyCurl $ch) : int { return $ch->errno(); } function curl_error(\DummyCurl $ch) : string { return $ch->errstr(); } function curl_multi_init() : \DummyCurlMulti { return new \DummyCurlMulti; } function curl_multi_setopt(\DummyCurlMulti $ch, int $key, $value) : bool { return true; } function curl_multi_add_handle(\DummyCurlMulti $mh, \DummyCurl $ch) : int { return $mh->addHandle($ch); } function curl_multi_remove_handle(\DummyCurlMulti $mh, \DummyCurl $ch) : int { return $mh->removeHandle($ch); } function curl_multi_select(\DummyCurlMulti $mh, float $timeout = 1.0) : int { return -1; } function curl_multi_exec(\DummyCurlMulti $mh, &$active) : int { return $mh->exec($active); } function curl_multi_info_read(\DummyCurlMulti $mh, &$msgs_in_queue = null) { return $mh->infoRead($msgs_in_queue); } function curl_multi_getcontent(\DummyCurl $ch) : string { return $ch->getContent(); }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/UtilsTest.php
tests/unit/UtilsTest.php
<?php use mpyw\Co\CoInterface; use mpyw\Co\Internal\GeneratorContainer; use mpyw\Co\Internal\YieldableUtils; use mpyw\Co\Internal\TypeUtils; use mpyw\Co\Internal\CoOption; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; /** * @requires PHP 7.0 */ class UtilsTest extends \Codeception\TestCase\Test { use \Codeception\Specify; public function _before() { } public function _after() { } public function testIsCurl() { $ch = curl_init(); $this->assertTrue(TypeUtils::isCurl($ch)); curl_close($ch); $this->assertFalse(TypeUtils::isCurl($ch)); $this->assertFalse(TypeUtils::isCurl(curl_multi_init())); $this->assertFalse(TypeUtils::isCurl([1])); $this->assertFalse(TypeUtils::isCurl((object)[1])); } public function testIsGeneratorContainer() { $gen = (function () { yield 1; })(); $con = new GeneratorContainer($gen); $this->assertTrue(TypeUtils::isGeneratorContainer($con)); $this->assertFalse(TypeUtils::isGeneratorContainer($gen)); } public function testBasicNormalize() { $options = new CoOption; $genfunc = function () { $x = yield function () { return [1, 2, yield function () { $y = yield 3; $this->assertEquals($y, 'A'); return 4; }]; }; $this->assertEquals($x, 'B'); $z = yield 5; $this->assertEquals($z, 'C'); return [ function () use ($x) { return yield $x; }, $z, ]; }; $gen1 = YieldableUtils::normalize($genfunc, $options); $this->assertInstanceOf(GeneratorContainer::class, $gen1); $this->assertInstanceOf(\Closure::class, $gen1->current()); $gen2 = YieldableUtils::normalize($gen1->current(), $options); $this->assertInstanceOf(GeneratorContainer::class, $gen2); $this->assertInstanceOf(\Closure::class, $gen2->current()); $gen3 = YieldableUtils::normalize($gen2->current(), $options); $this->assertInstanceOf(GeneratorContainer::class, $gen3); $this->assertEquals(3, $gen3->current()); $gen3->send('A'); $this->assertFalse($gen3->valid()); $this->assertFalse($gen3->thrown()); $r1 = YieldableUtils::normalize($gen3->getReturnOrThrown(), $options); $this->assertEquals(4, $r1); $gen2->send(4); $this->assertFalse($gen2->valid()); $this->assertFalse($gen2->thrown()); $r2 = YieldableUtils::normalize($gen2->getReturnOrThrown(), $options); $this->assertEquals([1, 2, 4], $r2); $gen1->send('B'); $this->assertEquals(5, $gen1->current()); $gen1->send('C'); $this->assertFalse($gen1->valid()); $this->assertFalse($gen1->thrown()); $r3 = YieldableUtils::normalize($gen1->getReturnOrThrown(), $options); $this->assertInstanceOf(GeneratorContainer::class, $r3[0]); $this->assertEquals('C', $r3[1]); $gen4 = $r3[0]; $this->assertEquals('B', $gen4->current()); $gen4->send('D'); $this->assertFalse($gen4->valid()); $this->assertFalse($gen4->thrown()); $r4 = YieldableUtils::normalize($gen4->getReturnOrThrown(), $options); $this->assertEquals('D', $r4); } public function testNormalizeWithYieldKeysOnGeneratorFunction() { $genfunc = function () { yield CoInterface::SAFE => function () { throw new \RuntimeException; yield null; }; yield function () { throw new \RuntimeException; yield null; }; yield null; }; $gen1 = YieldableUtils::normalize($genfunc); $this->assertInstanceOf(GeneratorContainer::class, $gen1); $this->assertTrue($gen1->valid()); $this->assertEquals(CoInterface::SAFE, $gen1->key()); $this->assertInstanceOf(\Closure::class, $gen1->current()); $gen2 = YieldableUtils::normalize($gen1->current(), $gen1->key()); $this->assertInstanceOf(GeneratorContainer::class, $gen2); $this->assertFalse($gen2->valid()); $this->assertTrue($gen2->thrown()); $this->assertInstanceOf(\RuntimeException::class, $gen2->getReturnOrThrown()); $gen2->getYieldKey() === CoInterface::SAFE ? $gen1->send($gen2->getReturnOrThrown()) : $gen1->throw_($gen2->getReturnOrThrown()); $this->assertTrue($gen1->valid()); $gen3 = YieldableUtils::normalize($gen1->current(), $gen1->key()); $this->assertInstanceOf(GeneratorContainer::class, $gen3); $this->assertFalse($gen3->valid()); $this->assertTrue($gen3->thrown()); $this->assertInstanceOf(\RuntimeException::class, $gen3->getReturnOrThrown()); $gen3->getYieldKey() === CoInterface::SAFE ? $gen1->send($gen3->getReturnOrThrown()) : $gen1->throw_($gen3->getReturnOrThrown()); $this->assertFalse($gen1->valid()); } public function testGetYieldables() { $genfunc = function () { yield null; }; $r = [ 'x' => [ 'y1' => (object)[ 'ignored_0' => curl_init(), 'ignored_1' => new GeneratorContainer($genfunc()), ], 'y2' => [ 'z1' => $z1 = curl_init(), 'z2' => $z2 = new GeneratorContainer($genfunc()), ], ], ]; $this->assertEquals([ (string)$z1 => [ 'value' => $z1, 'keylist' => ['x', 'y2', 'z1'], ], (string)$z2 => [ 'value' => $z2, 'keylist' => ['x', 'y2', 'z2'], ], ], YieldableUtils::getYieldables($r)); } public function testTwoTypesOfFunctions() { $v = YieldableUtils::normalize([ function () { return 1; }, function () { return yield 1; }, ], new CoOption); $this->assertInstanceOf(\Closure::class, $v[0]); $this->assertInstanceOf(GeneratorContainer::class, $v[1]); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/unit/ManualPoolTest.php
tests/unit/ManualPoolTest.php
<?php require_once __DIR__ . '/DummyCurl.php'; require_once __DIR__ . '/DummyCurlMulti.php'; require_once __DIR__ . '/DummyCurlFunctions.php'; use mpyw\Co\Co; use mpyw\Co\CoInterface; use mpyw\Co\Internal\CoOption; use mpyw\Co\Internal\Pool; use mpyw\Privator\Proxy; use mpyw\Privator\ProxyException; use AspectMock\Test as test; use React\Promise\Deferred; /** * @requires PHP 7.0.7 */ class ManualPoolTest extends \Codeception\TestCase\Test { use \Codeception\Specify; private static $pool; public function _before() { test::double('mpyw\Co\Internal\TypeUtils', ['isCurl' => function ($arg) { return $arg instanceof \DummyCurl; }]); } public function _after() { test::clean(); } public function testWait() { $pool = new Pool(new CoOption(['concurrency' => 3])); $a = new Deferred; $curls = [ new DummyCurl('E', 5), // 0===1===2===3===4===5 (0, 5) new DummyCurl('A', 1), // 0===1 (0, 1) new DummyCurl('D', 4), // 0===1===2===3===4 (0, 4) new DummyCurl('C', 3), // 0---1---2===3===4===5 (2, 5) new DummyCurl('B', 2), // 0---1---2---3---4---5===6===7 (5, 7) ]; $invalids = [ new DummyCurl('X', 3, true), // 0---1---2---3---4---5---6===7===8===9 (6, 9) new DummyCurl('Y', 2, true), // 0---1---2---3---4---5---6===7===8 (6, 8) ]; $curl_timings = [[0, 5], [0, 1], [0, 4], [2, 5], [5, 7]]; $invalid_timings = [[6, 9], [6, 8]]; $done = []; $failed = []; foreach ($curls as $ch) { $pool->addCurl($ch)->then( function ($result) use (&$done) { $done[] = $result; }, function () { $this->assertTrue(false); } ); } foreach ($invalids as $ch) { $pool->addCurl($ch)->then( function () { $this->assertTrue(false); }, function ($e) use (&$failed) { $failed[] = $e; } ); } $pool->wait(); $failed = array_map(function (\RuntimeException $e) { $e->getHandle(); // Just for coverage return $e->getMessage(); }, $failed); foreach ($curls as $i => $curl) { $str = str_replace('DummyCurl', 'Response', (string)$curl); $this->assertContains($str, $done); $this->assertEquals($curl_timings[$i], [$curl->startedAt(), $curl->stoppedAt()]); } foreach ($invalids as $i => $curl) { $str = str_replace('DummyCurl', 'Error', (string)$curl); $this->assertContains($str, $failed); $this->assertEquals($invalid_timings[$i], [$curl->startedAt(), $curl->stoppedAt()]); } } public function testWaitCurlAndDelay() { $pool = new Pool(new CoOption(['concurrency' => 3])); $pool->addCurl(new DummyCurl('A', 10))->then(function () use (&$x) { $x = microtime(true); }); $pool->addDelay(1.3)->then(function () use (&$y) { $y = microtime(true); }); $pool->addDelay(1.1)->then(function () use (&$z) { $z = microtime(true); }); $pool->addDelay(1.2)->then(function () use (&$w) { $w = microtime(true); }); $pool->wait(); $this->assertNotNull($x); $this->assertNotNull($y); $this->assertNotNull($z); $this->assertNotNull($w); $this->assertTrue($x < $z); $this->assertTrue($z < $w); $this->assertTrue($w < $y); } public function testUnlimitedConcurrency() { $pool = new Pool(new CoOption(['concurrency' => 0])); $curls = []; foreach (range(1, 100) as $i) { $curls[] = new DummyCurl($i, 2); } $done = []; foreach ($curls as $ch) { $pool->addCurl($ch)->then( function ($result) use (&$done) { $done[] = $result; }, function () { $this->assertTrue(false); } );; } $pool->wait(); foreach ($curls as $curl) { $str = str_replace('DummyCurl', 'Response', (string)$curl); $this->assertContains($str, $done); $this->assertEquals([0, 2], [$curl->startedAt(), $curl->stoppedAt()]); } } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/AcceptanceTester.php
tests/_support/AcceptanceTester.php
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class AcceptanceTester extends \Codeception\Actor { use _generated\AcceptanceTesterActions; /** * Define custom actions here */ }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/UnitTester.php
tests/_support/UnitTester.php
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class UnitTester extends \Codeception\Actor { use _generated\UnitTesterActions; /** * Define custom actions here */ }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/FunctionalTester.php
tests/_support/FunctionalTester.php
<?php /** * Inherited Methods * @method void wantToTest($text) * @method void wantTo($text) * @method void execute($callable) * @method void expectTo($prediction) * @method void expect($prediction) * @method void amGoingTo($argumentation) * @method void am($role) * @method void lookForwardTo($achieveValue) * @method void comment($description) * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL) * * @SuppressWarnings(PHPMD) */ class FunctionalTester extends \Codeception\Actor { use _generated\FunctionalTesterActions; /** * Define custom actions here */ }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/Helper/Functional.php
tests/_support/Helper/Functional.php
<?php namespace Helper; // here you can define custom actions // all public methods declared in helper class will be available in $I class Functional extends \Codeception\Module { }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/Helper/Unit.php
tests/_support/Helper/Unit.php
<?php namespace Helper; // here you can define custom actions // all public methods declared in helper class will be available in $I class Unit extends \Codeception\Module { }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/Helper/Acceptance.php
tests/_support/Helper/Acceptance.php
<?php namespace Helper; // here you can define custom actions // all public methods declared in helper class will be available in $I class Acceptance extends \Codeception\Module { }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/_generated/AcceptanceTesterActions.php
tests/_support/_generated/AcceptanceTesterActions.php
<?php //[STAMP] 0313d1b3990d7fd01d357b6dec376b7f namespace _generated; // This class was automatically generated by build task // You should not change it manually as it will be overwritten on next build // @codingStandardsIgnoreFile use Codeception\Module\PhpBrowser; use Helper\Acceptance; trait AcceptanceTesterActions { /** * @return \Codeception\Scenario */ abstract protected function getScenario(); /** * [!] Method is generated. Documentation taken from corresponding module. * * Sets the HTTP header to the passed value - which is used on * subsequent HTTP requests through PhpBrowser. * * Example: * ```php * <?php * $I->setHeader('X-Requested-With', 'Codeception'); * $I->amOnPage('test-headers.php'); * ?> * ``` * * @param string $name the name of the request header * @param string $value the value to set it to for subsequent * requests * @see \Codeception\Module\PhpBrowser::setHeader() */ public function setHeader($name, $value) { return $this->getScenario()->runStep(new \Codeception\Step\Action('setHeader', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Deletes the header with the passed name. Subsequent requests * will not have the deleted header in its request. * * Example: * ```php * <?php * $I->setHeader('X-Requested-With', 'Codeception'); * $I->amOnPage('test-headers.php'); * // ... * $I->deleteHeader('X-Requested-With'); * $I->amOnPage('some-other-page.php'); * ?> * ``` * * @param string $name the name of the header to delete. * @see \Codeception\Module\PhpBrowser::deleteHeader() */ public function deleteHeader($name) { return $this->getScenario()->runStep(new \Codeception\Step\Action('deleteHeader', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Authenticates user for HTTP_AUTH * * @param $username * @param $password * @see \Codeception\Module\PhpBrowser::amHttpAuthenticated() */ public function amHttpAuthenticated($username, $password) { return $this->getScenario()->runStep(new \Codeception\Step\Condition('amHttpAuthenticated', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Open web page at the given absolute URL and sets its hostname as the base host. * * ``` php * <?php * $I->amOnUrl('http://codeception.com'); * $I->amOnPage('/quickstart'); // moves to http://codeception.com/quickstart * ?> * ``` * @see \Codeception\Module\PhpBrowser::amOnUrl() */ public function amOnUrl($url) { return $this->getScenario()->runStep(new \Codeception\Step\Condition('amOnUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Changes the subdomain for the 'url' configuration parameter. * Does not open a page; use `amOnPage` for that. * * ``` php * <?php * // If config is: 'http://mysite.com' * // or config is: 'http://www.mysite.com' * // or config is: 'http://company.mysite.com' * * $I->amOnSubdomain('user'); * $I->amOnPage('/'); * // moves to http://user.mysite.com/ * ?> * ``` * * @param $subdomain * * @return mixed * @see \Codeception\Module\PhpBrowser::amOnSubdomain() */ public function amOnSubdomain($subdomain) { return $this->getScenario()->runStep(new \Codeception\Step\Condition('amOnSubdomain', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Low-level API method. * If Codeception commands are not enough, use [Guzzle HTTP Client](http://guzzlephp.org/) methods directly * * Example: * * ``` php * <?php * $I->executeInGuzzle(function (\GuzzleHttp\Client $client) { * $client->get('/get', ['query' => ['foo' => 'bar']]); * }); * ?> * ``` * * It is not recommended to use this command on a regular basis. * If Codeception lacks important Guzzle Client methods, implement them and submit patches. * * @param callable $function * @see \Codeception\Module\PhpBrowser::executeInGuzzle() */ public function executeInGuzzle($function) { return $this->getScenario()->runStep(new \Codeception\Step\Action('executeInGuzzle', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Opens the page for the given relative URI. * * ``` php * <?php * // opens front page * $I->amOnPage('/'); * // opens /register page * $I->amOnPage('/register'); * ``` * * @param $page * @see \Codeception\Lib\InnerBrowser::amOnPage() */ public function amOnPage($page) { return $this->getScenario()->runStep(new \Codeception\Step\Condition('amOnPage', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Perform a click on a link or a button, given by a locator. * If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. * For buttons, the "value" attribute, "name" attribute, and inner text are searched. * For links, the link text is searched. * For images, the "alt" attribute and inner text of any parent links are searched. * * The second parameter is a context (CSS or XPath locator) to narrow the search. * * Note that if the locator matches a button of type `submit`, the form will be submitted. * * ``` php * <?php * // simple link * $I->click('Logout'); * // button of form * $I->click('Submit'); * // CSS button * $I->click('#form input[type=submit]'); * // XPath * $I->click('//form/*[@type=submit]'); * // link in context * $I->click('Logout', '#nav'); * // using strict locator * $I->click(['link' => 'Login']); * ?> * ``` * * @param $link * @param $context * @see \Codeception\Lib\InnerBrowser::click() */ public function click($link, $context = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('click', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string (case insensitive). * * You can specify a specific HTML element (via CSS or XPath) as the second * parameter to only search within that element. * * ``` php * <?php * $I->see('Logout'); // I can suppose user is logged in * $I->see('Sign Up', 'h1'); // I can suppose it's a signup page * $I->see('Sign Up', '//body/h1'); // with XPath * ``` * * Note that the search is done after stripping all HTML tags from the body, * so `$I->see('strong')` will return true for strings like: * * - `<p>I am Stronger than thou</p>` * - `<script>document.createElement('strong');</script>` * * But will *not* be true for strings like: * * - `<strong>Home</strong>` * - `<div class="strong">Home</strong>` * - `<!-- strong -->` * * For checking the raw source code, use `seeInSource()`. * * @param $text * @param null $selector * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::see() */ public function canSee($text, $selector = null) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('see', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string (case insensitive). * * You can specify a specific HTML element (via CSS or XPath) as the second * parameter to only search within that element. * * ``` php * <?php * $I->see('Logout'); // I can suppose user is logged in * $I->see('Sign Up', 'h1'); // I can suppose it's a signup page * $I->see('Sign Up', '//body/h1'); // with XPath * ``` * * Note that the search is done after stripping all HTML tags from the body, * so `$I->see('strong')` will return true for strings like: * * - `<p>I am Stronger than thou</p>` * - `<script>document.createElement('strong');</script>` * * But will *not* be true for strings like: * * - `<strong>Home</strong>` * - `<div class="strong">Home</strong>` * - `<!-- strong -->` * * For checking the raw source code, use `seeInSource()`. * * @param $text * @param null $selector * @see \Codeception\Lib\InnerBrowser::see() */ public function see($text, $selector = null) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('see', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page doesn't contain the text specified (case insensitive). * Give a locator as the second parameter to match a specific region. * * ```php * <?php * $I->dontSee('Login'); // I can suppose user is already logged in * $I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page * $I->dontSee('Sign Up','//body/h1'); // with XPath * ``` * * Note that the search is done after stripping all HTML tags from the body, * so `$I->dontSee('strong')` will fail on strings like: * * - `<p>I am Stronger than thou</p>` * - `<script>document.createElement('strong');</script>` * * But will ignore strings like: * * - `<strong>Home</strong>` * - `<div class="strong">Home</strong>` * - `<!-- strong -->` * * For checking the raw source code, use `seeInSource()`. * * @param $text * @param null $selector * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSee() */ public function cantSee($text, $selector = null) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSee', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page doesn't contain the text specified (case insensitive). * Give a locator as the second parameter to match a specific region. * * ```php * <?php * $I->dontSee('Login'); // I can suppose user is already logged in * $I->dontSee('Sign Up','h1'); // I can suppose it's not a signup page * $I->dontSee('Sign Up','//body/h1'); // with XPath * ``` * * Note that the search is done after stripping all HTML tags from the body, * so `$I->dontSee('strong')` will fail on strings like: * * - `<p>I am Stronger than thou</p>` * - `<script>document.createElement('strong');</script>` * * But will ignore strings like: * * - `<strong>Home</strong>` * - `<div class="strong">Home</strong>` * - `<!-- strong -->` * * For checking the raw source code, use `seeInSource()`. * * @param $text * @param null $selector * @see \Codeception\Lib\InnerBrowser::dontSee() */ public function dontSee($text, $selector = null) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSee', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string in its * raw source code. * * ``` php * <?php * $I->seeInSource('<h1>Green eggs &amp; ham</h1>'); * ``` * * @param $raw * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeInSource() */ public function canSeeInSource($raw) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeInSource', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string in its * raw source code. * * ``` php * <?php * $I->seeInSource('<h1>Green eggs &amp; ham</h1>'); * ``` * * @param $raw * @see \Codeception\Lib\InnerBrowser::seeInSource() */ public function seeInSource($raw) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeInSource', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string in its * raw source code. * * ```php * <?php * $I->dontSeeInSource('<h1>Green eggs &amp; ham</h1>'); * ``` * * @param $raw * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeInSource() */ public function cantSeeInSource($raw) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInSource', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current page contains the given string in its * raw source code. * * ```php * <?php * $I->dontSeeInSource('<h1>Green eggs &amp; ham</h1>'); * ``` * * @param $raw * @see \Codeception\Lib\InnerBrowser::dontSeeInSource() */ public function dontSeeInSource($raw) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeInSource', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that there's a link with the specified text. * Give a full URL as the second parameter to match links with that exact URL. * * ``` php * <?php * $I->seeLink('Logout'); // matches <a href="#">Logout</a> * $I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a> * ?> * ``` * * @param $text * @param null $url * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeLink() */ public function canSeeLink($text, $url = null) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeLink', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that there's a link with the specified text. * Give a full URL as the second parameter to match links with that exact URL. * * ``` php * <?php * $I->seeLink('Logout'); // matches <a href="#">Logout</a> * $I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a> * ?> * ``` * * @param $text * @param null $url * @see \Codeception\Lib\InnerBrowser::seeLink() */ public function seeLink($text, $url = null) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeLink', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the page doesn't contain a link with the given string. * If the second parameter is given, only links with a matching "href" attribute will be checked. * * ``` php * <?php * $I->dontSeeLink('Logout'); // I suppose user is not logged in * $I->dontSeeLink('Checkout now', '/store/cart.php'); * ?> * ``` * * @param $text * @param null $url * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeLink() */ public function cantSeeLink($text, $url = null) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeLink', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the page doesn't contain a link with the given string. * If the second parameter is given, only links with a matching "href" attribute will be checked. * * ``` php * <?php * $I->dontSeeLink('Logout'); // I suppose user is not logged in * $I->dontSeeLink('Checkout now', '/store/cart.php'); * ?> * ``` * * @param $text * @param null $url * @see \Codeception\Lib\InnerBrowser::dontSeeLink() */ public function dontSeeLink($text, $url = null) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeLink', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that current URI contains the given string. * * ``` php * <?php * // to match: /home/dashboard * $I->seeInCurrentUrl('home'); * // to match: /users/1 * $I->seeInCurrentUrl('/users/'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeInCurrentUrl() */ public function canSeeInCurrentUrl($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeInCurrentUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that current URI contains the given string. * * ``` php * <?php * // to match: /home/dashboard * $I->seeInCurrentUrl('home'); * // to match: /users/1 * $I->seeInCurrentUrl('/users/'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::seeInCurrentUrl() */ public function seeInCurrentUrl($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeInCurrentUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URI doesn't contain the given string. * * ``` php * <?php * $I->dontSeeInCurrentUrl('/users/'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeInCurrentUrl() */ public function cantSeeInCurrentUrl($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInCurrentUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URI doesn't contain the given string. * * ``` php * <?php * $I->dontSeeInCurrentUrl('/users/'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::dontSeeInCurrentUrl() */ public function dontSeeInCurrentUrl($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeInCurrentUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL is equal to the given string. * Unlike `seeInCurrentUrl`, this only matches the full URL. * * ``` php * <?php * // to match root url * $I->seeCurrentUrlEquals('/'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeCurrentUrlEquals() */ public function canSeeCurrentUrlEquals($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeCurrentUrlEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL is equal to the given string. * Unlike `seeInCurrentUrl`, this only matches the full URL. * * ``` php * <?php * // to match root url * $I->seeCurrentUrlEquals('/'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::seeCurrentUrlEquals() */ public function seeCurrentUrlEquals($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeCurrentUrlEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL doesn't equal the given string. * Unlike `dontSeeInCurrentUrl`, this only matches the full URL. * * ``` php * <?php * // current url is not root * $I->dontSeeCurrentUrlEquals('/'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlEquals() */ public function cantSeeCurrentUrlEquals($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCurrentUrlEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL doesn't equal the given string. * Unlike `dontSeeInCurrentUrl`, this only matches the full URL. * * ``` php * <?php * // current url is not root * $I->dontSeeCurrentUrlEquals('/'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlEquals() */ public function dontSeeCurrentUrlEquals($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeCurrentUrlEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL matches the given regular expression. * * ``` php * <?php * // to match root url * $I->seeCurrentUrlMatches('~$/users/(\d+)~'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeCurrentUrlMatches() */ public function canSeeCurrentUrlMatches($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeCurrentUrlMatches', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the current URL matches the given regular expression. * * ``` php * <?php * // to match root url * $I->seeCurrentUrlMatches('~$/users/(\d+)~'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::seeCurrentUrlMatches() */ public function seeCurrentUrlMatches($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeCurrentUrlMatches', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that current url doesn't match the given regular expression. * * ``` php * <?php * // to match root url * $I->dontSeeCurrentUrlMatches('~$/users/(\d+)~'); * ?> * ``` * * @param $uri * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlMatches() */ public function cantSeeCurrentUrlMatches($uri) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCurrentUrlMatches', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that current url doesn't match the given regular expression. * * ``` php * <?php * // to match root url * $I->dontSeeCurrentUrlMatches('~$/users/(\d+)~'); * ?> * ``` * * @param $uri * @see \Codeception\Lib\InnerBrowser::dontSeeCurrentUrlMatches() */ public function dontSeeCurrentUrlMatches($uri) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeCurrentUrlMatches', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Executes the given regular expression against the current URI and returns the first match. * If no parameters are provided, the full URI is returned. * * ``` php * <?php * $user_id = $I->grabFromCurrentUrl('~$/user/(\d+)/~'); * $uri = $I->grabFromCurrentUrl(); * ?> * ``` * * @param null $uri * * @return mixed * @see \Codeception\Lib\InnerBrowser::grabFromCurrentUrl() */ public function grabFromCurrentUrl($uri = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('grabFromCurrentUrl', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the specified checkbox is checked. * * ``` php * <?php * $I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms * $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form. * $I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]'); * ?> * ``` * * @param $checkbox * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeCheckboxIsChecked() */ public function canSeeCheckboxIsChecked($checkbox) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeCheckboxIsChecked', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the specified checkbox is checked. * * ``` php * <?php * $I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms * $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form. * $I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]'); * ?> * ``` * * @param $checkbox * @see \Codeception\Lib\InnerBrowser::seeCheckboxIsChecked() */ public function seeCheckboxIsChecked($checkbox) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeCheckboxIsChecked', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Check that the specified checkbox is unchecked. * * ``` php * <?php * $I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms * $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form. * ?> * ``` * * @param $checkbox * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeCheckboxIsChecked() */ public function cantSeeCheckboxIsChecked($checkbox) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeCheckboxIsChecked', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Check that the specified checkbox is unchecked. * * ``` php * <?php * $I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms * $I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form. * ?> * ``` * * @param $checkbox * @see \Codeception\Lib\InnerBrowser::dontSeeCheckboxIsChecked() */ public function dontSeeCheckboxIsChecked($checkbox) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('dontSeeCheckboxIsChecked', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the given input field or textarea contains the given value. * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath. * * ``` php * <?php * $I->seeInField('Body','Type your comment here'); * $I->seeInField('form textarea[name=body]','Type your comment here'); * $I->seeInField('form input[type=hidden]','hidden_value'); * $I->seeInField('#searchform input','Search'); * $I->seeInField('//form/*[@name=search]','Search'); * $I->seeInField(['name' => 'search'], 'Search'); * ?> * ``` * * @param $field * @param $value * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::seeInField() */ public function canSeeInField($field, $value) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('seeInField', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that the given input field or textarea contains the given value. * For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath. * * ``` php * <?php * $I->seeInField('Body','Type your comment here'); * $I->seeInField('form textarea[name=body]','Type your comment here'); * $I->seeInField('form input[type=hidden]','hidden_value'); * $I->seeInField('#searchform input','Search'); * $I->seeInField('//form/*[@name=search]','Search'); * $I->seeInField(['name' => 'search'], 'Search'); * ?> * ``` * * @param $field * @param $value * @see \Codeception\Lib\InnerBrowser::seeInField() */ public function seeInField($field, $value) { return $this->getScenario()->runStep(new \Codeception\Step\Assertion('seeInField', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that an input field or textarea doesn't contain the given value. * For fuzzy locators, the field is matched by label text, CSS and XPath. * * ``` php * <?php * $I->dontSeeInField('Body','Type your comment here'); * $I->dontSeeInField('form textarea[name=body]','Type your comment here'); * $I->dontSeeInField('form input[type=hidden]','hidden_value'); * $I->dontSeeInField('#searchform input','Search'); * $I->dontSeeInField('//form/*[@name=search]','Search'); * $I->dontSeeInField(['name' => 'search'], 'Search'); * ?> * ``` * * @param $field * @param $value * Conditional Assertion: Test won't be stopped on fail * @see \Codeception\Lib\InnerBrowser::dontSeeInField() */ public function cantSeeInField($field, $value) { return $this->getScenario()->runStep(new \Codeception\Step\ConditionalAssertion('dontSeeInField', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that an input field or textarea doesn't contain the given value. * For fuzzy locators, the field is matched by label text, CSS and XPath. * * ``` php * <?php * $I->dontSeeInField('Body','Type your comment here'); * $I->dontSeeInField('form textarea[name=body]','Type your comment here'); * $I->dontSeeInField('form input[type=hidden]','hidden_value');
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
true
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/_generated/FunctionalTesterActions.php
tests/_support/_generated/FunctionalTesterActions.php
<?php //[STAMP] bc472f8f73298de32089ceb3152b40dd namespace _generated; // This class was automatically generated by build task // You should not change it manually as it will be overwritten on next build // @codingStandardsIgnoreFile use Helper\Functional; trait FunctionalTesterActions { /** * @return \Codeception\Scenario */ abstract protected function getScenario(); }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/_support/_generated/UnitTesterActions.php
tests/_support/_generated/UnitTesterActions.php
<?php //[STAMP] 6e841f8cf4534489e89238d437883046 namespace _generated; // This class was automatically generated by build task // You should not change it manually as it will be overwritten on next build // @codingStandardsIgnoreFile use Codeception\Module\Asserts; use Helper\Unit; trait UnitTesterActions { /** * @return \Codeception\Scenario */ abstract protected function getScenario(); /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that two variables are equal. * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertEquals() */ public function assertEquals($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that two variables are not equal * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertNotEquals() */ public function assertNotEquals($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that two variables are same * * @param $expected * @param $actual * @param string $message * @return mixed|void * @see \Codeception\Module\Asserts::assertSame() */ public function assertSame($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertSame', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that two variables are not same * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertNotSame() */ public function assertNotSame($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotSame', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that actual is greater than expected * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertGreaterThan() */ public function assertGreaterThan($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThan', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that actual is greater or equal than expected * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertGreaterThanOrEqual() */ public function assertGreaterThanOrEqual($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterThanOrEqual', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that actual is less than expected * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertLessThan() */ public function assertLessThan($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessThan', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that actual is less or equal than expected * * @param $expected * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertLessThanOrEqual() */ public function assertLessThanOrEqual($expected, $actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessThanOrEqual', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that haystack contains needle * * @param $needle * @param $haystack * @param string $message * @see \Codeception\Module\Asserts::assertContains() */ public function assertContains($needle, $haystack, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertContains', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that haystack doesn't contain needle. * * @param $needle * @param $haystack * @param string $message * @see \Codeception\Module\Asserts::assertNotContains() */ public function assertNotContains($needle, $haystack, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotContains', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that string match with pattern * * @param string $pattern * @param string $string * @param string $message * @see \Codeception\Module\Asserts::assertRegExp() */ public function assertRegExp($pattern, $string, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertRegExp', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that string not match with pattern * * @param string $pattern * @param string $string * @param string $message * @see \Codeception\Module\Asserts::assertNotRegExp() */ public function assertNotRegExp($pattern, $string, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotRegExp', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that variable is empty. * * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertEmpty() */ public function assertEmpty($actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertEmpty', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that variable is not empty. * * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertNotEmpty() */ public function assertNotEmpty($actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotEmpty', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that variable is NULL * * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertNull() */ public function assertNull($actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNull', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that variable is not NULL * * @param $actual * @param string $message * @see \Codeception\Module\Asserts::assertNotNull() */ public function assertNotNull($actual, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotNull', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that condition is positive. * * @param $condition * @param string $message * @see \Codeception\Module\Asserts::assertTrue() */ public function assertTrue($condition, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertTrue', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks that condition is negative. * * @param $condition * @param string $message * @see \Codeception\Module\Asserts::assertFalse() */ public function assertFalse($condition, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFalse', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks if file exists * * @param string $filename * @param string $message * @see \Codeception\Module\Asserts::assertFileExists() */ public function assertFileExists($filename, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFileExists', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Checks if file doesn't exist * * @param string $filename * @param string $message * @see \Codeception\Module\Asserts::assertFileNotExists() */ public function assertFileNotExists($filename, $message = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertFileNotExists', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $expected * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertGreaterOrEquals() */ public function assertGreaterOrEquals($expected, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertGreaterOrEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $expected * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertLessOrEquals() */ public function assertLessOrEquals($expected, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertLessOrEquals', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertIsEmpty() */ public function assertIsEmpty($actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertIsEmpty', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $key * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertArrayHasKey() */ public function assertArrayHasKey($key, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayHasKey', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $key * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertArrayNotHasKey() */ public function assertArrayNotHasKey($key, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertArrayNotHasKey', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $class * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertInstanceOf() */ public function assertInstanceOf($class, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInstanceOf', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $class * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertNotInstanceOf() */ public function assertNotInstanceOf($class, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertNotInstanceOf', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * @param $type * @param $actual * @param $description * @see \Codeception\Module\Asserts::assertInternalType() */ public function assertInternalType($type, $actual, $description = null) { return $this->getScenario()->runStep(new \Codeception\Step\Action('assertInternalType', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Fails the test with message. * * @param $message * @see \Codeception\Module\Asserts::fail() */ public function fail($message) { return $this->getScenario()->runStep(new \Codeception\Step\Action('fail', func_get_args())); } /** * [!] Method is generated. Documentation taken from corresponding module. * * Handles and checks exception called inside callback function. * Either exception class name or exception instance should be provided. * * ```php * <?php * $I->expectException(MyException::class, function() { * $this->doSomethingBad(); * }); * * $I->expectException(new MyException(), function() { * $this->doSomethingBad(); * }); * ``` * If you want to check message or exception code, you can pass them with exception instance: * ```php * <?php * // will check that exception MyException is thrown with "Don't do bad things" message * $I->expectException(new MyException("Don't do bad things"), function() { * $this->doSomethingBad(); * }); * ``` * * @param $exception string or \Exception * @param $callback * @see \Codeception\Module\Asserts::expectException() */ public function expectException($exception, $callback) { return $this->getScenario()->runStep(new \Codeception\Step\Action('expectException', func_get_args())); } }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/tests/functional/_bootstrap.php
tests/functional/_bootstrap.php
<?php // Here you can initialize variables that will be available to your tests
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/localhost/client-init.php
examples/localhost/client-init.php
<?php require __DIR__ . '/../../vendor/autoload.php'; set_time_limit(0); /** * REST API * @param string $path * @param array $q * @return resource */ function curl(string $path, array $q = []) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => "http://localhost:8080$path?" . http_build_query($q, '', '&'), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_FAILONERROR => true, ]); return $ch; } /** * Streaming API * @param string $path * @param callable $callback * @param array $q * @return resource */ function curl_streaming(string $path, callable $callback, array $q = []) { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => "http://localhost:8080$path?" . http_build_query($q, '', '&'), CURLOPT_WRITEFUNCTION => function ($ch, $buf) use ($callback) { $callback($buf); return strlen($buf); }, ]); return $ch; } /** * Print elapsed time */ function print_time() { static $start; if (!$start) { $start = microtime(true); echo "【Time】0.0 s\n"; } else { $diff = sprintf('%.1f', microtime(true) - $start); echo "【Time】$diff s\n"; } } /** * Unwrap exception message * @param mixed $value * @return mixed */ function unwrap($value) { if (is_array($value)) { return array_map(__FUNCTION__, $value); } if (!$value instanceof \RuntimeException) { return $value; } $class = get_class($value); $message = $value->getMessage(); return "$class: $message"; }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/localhost/client-01.php
examples/localhost/client-01.php
<?php use mpyw\Co\Co; use mpyw\Co\CURLException; require __DIR__ . '/client-init.php'; // Wait 7 sec print_time(); $result = Co::wait([curl('/rest', ['id' => 1, 'sleep' => 7]), function () { // Wait 4 sec print_r(yield [ curl('/rest', ['id' => 2, 'sleep' => 3]), curl('/rest', ['id' => 3, 'sleep' => 4]), ]); print_time(); // Wait 2 sec print_r(yield [ function () { // Wait 1 sec echo yield curl('/rest', ['id' => 4, 'sleep' => 1]), "\n"; print_time(); return curl('/rest', ['id' => 5, 'sleep' => 1]); }, function () { // Wait 0 sec echo unwrap(yield CO::SAFE => curl('/invalid')), "\n"; print_time(); try { // Wait 0 sec yield curl('/invalid'); } catch (CURLException $e) { echo unwrap($e), "\n"; print_time(); } return ['x' => ['y' => function () { return yield curl('/rest', ['id' => 6, 'sleep' => 2]); }]]; } ]); print_time(); return curl('/rest', ['id' => 7, 'sleep' => 1]); }]); print_r($result); print_time();
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/localhost/server.php
examples/localhost/server.php
<?php require __DIR__ . '/../../vendor/autoload.php'; set_time_limit(0); declare(ticks = 1); pcntl_signal(SIGCHLD, 'signal_handler'); serve(); /** * Erorr-safe fwrite(). * @param resource $con * @param string $data * @throws \RuntimeException */ function fsend($con, string $data) { if (!@fwrite($con, $data)) { $error = error_get_last(); throw new \RuntimeException($error['message']); } } /** * Respond to the REST endpoints. * @param resource $con * @param int $status * @param string $message * @param string $content */ function respond_rest($con, int $status, string $message, string $content) { try { $length = strlen($content); fsend($con, "HTTP/1.1 $status $message\r\n"); fsend($con, "Content-Length: $length\r\n"); fsend($con, "\r\n"); fsend($con, $content); } catch (\RuntimeException $e) { fwrite(STDERR, $e->getMessage() . "\n"); } fclose($con); } /** * Respond to the Streaming endpoints. * @param resource $con * @param callable $tick_function * @param int $tick * @param Int $times */ function respond_streaming($con, callable $tick_function, int $tick, int $times) { try { fsend($con, "HTTP/1.1 200 OK\r\n"); fsend($con, "Transfer-Encoding: chunked\r\n"); fsend($con, "\r\n"); for ($i = 1; $i <= $times; ++$i) { $content = $tick_function($i); $length = base_convert(strlen($content), 10, 16); fsend($con, "$length\r\n"); fsend($con, "$content\r\n"); sleep($tick); } fsend($con, "0\r\n"); fsend($con, "\r\n"); } catch (\RuntimeException $e) { fwrite(STDERR, $e->getMessage() . "\n"); } fclose($con); } /** * Launch HTTP server. */ function serve() { $socket = stream_socket_server("tcp://localhost:8080", $errno, $errstr); if (!$socket) { fwrite(STDERR, "[Server] $errstr($errno)\n"); exit(1); } while (true) { $con = @stream_socket_accept($socket, -1); if (!$con) { $err = error_get_last(); if (strpos($err['message'], 'Interrupted system call') !== false) { continue; } fwrite(STDERR, "[Server] $err[message]\n"); exit(1); } if (-1 === $pid = pcntl_fork()) { fwrite(STDERR, "[Server] Failed to fork\n"); exit(1); } if ($pid) { // parent process continue; } // child process $endpoints = [ '/rest' => function ($con, $q) { $sleep = isset($q['sleep']) ? (int)$q['sleep'] : 0; sleep($sleep); $id = isset($q['id']) ? (int)$q['id'] : '?'; respond_rest($con, 200, 'OK', "Rest response #$id (sleep: $sleep sec)\n"); }, '/streaming' => function ($con, $q) { $tick = isset($q['tick']) ? (int)$q['tick'] : 1; $id = isset($q['id']) ? (int)$q['id'] : '?'; $times = isset($q['times']) ? (int)$q['times'] : 10; respond_streaming($con, function ($i) use ($id, $times) { return "Rest response #$id ($i / $times, tick: $tick sec)\n"; }, $tick, $times); }, '' => function ($con, $q) { respond_rest($con, 404, 'Not Found', "Undefined path\n"); }, ]; $parts = explode(' ', fgets($con)); $parsed = parse_url($parts[1]); parse_str(isset($parsed['query']) ? $parsed['query'] : '', $q); foreach ($endpoints as $endpoint => $action) { if ($parsed['path'] === $endpoint || $endpoint === '') { if ($endpoint === '') $endpoint = '[Undefined]'; fwrite(STDERR, "Request: $parts[1]\n"); $action($con, $q); exit(0); } } exit(0); // Unreachable here } } function signal_handler(int $sig) { if ($sig !== SIGCHLD) { return; } $ignore = NULL; while (($rc = pcntl_waitpid(-1, $ignore, WNOHANG)) > 0); if ($rc !== -1 || pcntl_get_last_error() === PCNTL_ECHILD) { return; } fwrite(STDERR, 'waitpid() failed: ' . pcntl_strerror(pcntl_get_last_error()) . "\n"); exit(1); }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/localhost/client-02.php
examples/localhost/client-02.php
<?php use mpyw\Co\Co; use mpyw\Co\CURLException; require __DIR__ . '/client-init.php'; // Wait 5 sec print_time(); $result = Co::wait([curl('/rest', ['id' => 1, 'sleep' => 5]), function () { // Wait 3 sec print_r(unwrap(yield Co::SAFE => [ curl('/rest', ['id' => 2, 'sleep' => 3]), function () { yield; throw new \RuntimeException('01'); } ])); print_time(); // Wait 1 sec print_r(unwrap(yield Co::SAFE => [ function () { // Wait 1 sec echo yield curl('/rest', ['id' => 3, 'sleep' => 1]), "\n"; print_time(); echo unwrap(yield Co::SAFE => function () { yield; throw new \RuntimeException('02'); }) . "\n"; yield function () { yield; throw new \RuntimeException('03'); }; return 'Unreachable'; }, function () { echo unwrap(yield Co::SAFE => function () { yield; throw new \RuntimeException('04'); }) . "\n"; yield function () { yield; throw new \RuntimeException('05'); }; return 'Unreachable'; }, ])); echo unwrap(yield Co::SAFE => function () { yield curl('/invalid'); return 'Unreachable'; }) . "\n"; // Wait 1 sec return curl('/rest', ['id' => 4, 'sleep' => 1]); }]); print_r($result); print_time();
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/github/download_follower_avatars_pipelined_unlimited.php
examples/github/download_follower_avatars_pipelined_unlimited.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; function curl_init_with(string $url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FAILONERROR => true, CURLOPT_ENCODING => 'gzip', CURLOPT_TIMEOUT => 5, ], $options); curl_setopt_array($ch, $options); return $ch; } function get_github_followers_async(string $username, int $page, &$has_more) : \Generator { $dom = new DOMDocument; $html = yield curl_init_with("https://github.com/$username/followers?page=$page"); @$dom->loadHTML($html); $xpath = new \DOMXPath($dom); $sources = []; foreach ($xpath->query('//li[contains(@class, "follow-list-item")]//img') as $node) { $sources[substr($node->getAttribute('alt'), 1)] = $node->getAttribute('src'); } $has_more = (bool)$xpath->evaluate('string(//div[contains(@class, "pagination")]/a[string() = "Next"])'); $has_more_int = (int)$has_more; echo "Downloaded https://github.com/$username/followers?page=$page (has_more = $has_more_int)\n"; return $sources; } function download_image_async(string $url, string $basename, string $savedir = '/tmp') : \Generator { static $exts = [ 'image/jpeg' => '.jpg', 'image/png' => '.png', 'image/gif' => '.gif', ]; $content = yield curl_init_with($url); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($content); $ext = isset($exts[$type]) ? $exts[$type] : ''; file_put_contents("$savedir/$basename$ext", $content); echo "Downloaded $url, saved as $savedir/$basename$ext\n"; } // Who are you? while (true) { do { if (feof(STDIN)) { exit; } fwrite(STDERR, 'USERNAME: '); $username = preg_replace('/[^\w-]++/', '', trim(fgets(STDIN))); } while ($username === ''); if (@file_get_contents("https://github.com/$username")) { define('USERNAME', $username); break; } fwrite(STDERR, error_get_last()['message'] . "\n"); } Co::wait(function () { $page = 0; do { $sources = yield get_github_followers_async(USERNAME, ++$page, $has_more); Co::async(function () use ($sources) { $requests = []; foreach ($sources as $username => $src) { $requests[] = download_image_async($src, $username); } yield $requests; }); } while ($has_more); }, ['concurrency' => 0, 'pipeline' => true]);
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/github/download_follower_avatars_default.php
examples/github/download_follower_avatars_default.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; function curl_init_with(string $url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FAILONERROR => true, CURLOPT_ENCODING => 'gzip', CURLOPT_TIMEOUT => 5, ], $options); curl_setopt_array($ch, $options); return $ch; } function get_github_followers_async(string $username, int $page, &$has_more) : \Generator { $dom = new DOMDocument; $html = yield curl_init_with("https://github.com/$username/followers?page=$page"); @$dom->loadHTML($html); $xpath = new \DOMXPath($dom); $sources = []; foreach ($xpath->query('//li[contains(@class, "follow-list-item")]//img') as $node) { $sources[substr($node->getAttribute('alt'), 1)] = $node->getAttribute('src'); } $has_more = (bool)$xpath->evaluate('string(//div[contains(@class, "pagination")]/a[string() = "Next"])'); $has_more_int = (int)$has_more; echo "Downloaded https://github.com/$username/followers?page=$page (has_more = $has_more_int)\n"; return $sources; } function download_image_async(string $url, string $basename, string $savedir = '/tmp') : \Generator { static $exts = [ 'image/jpeg' => '.jpg', 'image/png' => '.png', 'image/gif' => '.gif', ]; $content = yield curl_init_with($url); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($content); $ext = isset($exts[$type]) ? $exts[$type] : ''; file_put_contents("$savedir/$basename$ext", $content); echo "Downloaded $url, saved as $savedir/$basename$ext\n"; } // Who are you? while (true) { do { if (feof(STDIN)) { exit; } fwrite(STDERR, 'USERNAME: '); $username = preg_replace('/[^\w-]++/', '', trim(fgets(STDIN))); } while ($username === ''); if (@file_get_contents("https://github.com/$username")) { define('USERNAME', $username); break; } fwrite(STDERR, error_get_last()['message'] . "\n"); } Co::wait(function () { $page = 0; do { $sources = yield get_github_followers_async(USERNAME, ++$page, $has_more); Co::async(function () use ($sources) { $requests = []; foreach ($sources as $username => $src) { $requests[] = download_image_async($src, $username); } yield $requests; }); } while ($has_more); });
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/github/download_follower_avatars_pipelined.php
examples/github/download_follower_avatars_pipelined.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; function curl_init_with(string $url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_FAILONERROR => true, CURLOPT_ENCODING => 'gzip', CURLOPT_TIMEOUT => 5, ], $options); curl_setopt_array($ch, $options); return $ch; } function get_github_followers_async(string $username, int $page, &$has_more) : \Generator { $dom = new DOMDocument; $html = yield curl_init_with("https://github.com/$username/followers?page=$page"); @$dom->loadHTML($html); $xpath = new \DOMXPath($dom); $sources = []; foreach ($xpath->query('//li[contains(@class, "follow-list-item")]//img') as $node) { $sources[substr($node->getAttribute('alt'), 1)] = $node->getAttribute('src'); } $has_more = (bool)$xpath->evaluate('string(//div[contains(@class, "pagination")]/a[string() = "Next"])'); $has_more_int = (int)$has_more; echo "Downloaded https://github.com/$username/followers?page=$page (has_more = $has_more_int)\n"; return $sources; } function download_image_async(string $url, string $basename, string $savedir = '/tmp') : \Generator { static $exts = [ 'image/jpeg' => '.jpg', 'image/png' => '.png', 'image/gif' => '.gif', ]; $content = yield curl_init_with($url); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($content); $ext = isset($exts[$type]) ? $exts[$type] : ''; file_put_contents("$savedir/$basename$ext", $content); echo "Downloaded $url, saved as $savedir/$basename$ext\n"; } // Who are you? while (true) { do { if (feof(STDIN)) { exit; } fwrite(STDERR, 'USERNAME: '); $username = preg_replace('/[^\w-]++/', '', trim(fgets(STDIN))); } while ($username === ''); if (@file_get_contents("https://github.com/$username")) { define('USERNAME', $username); break; } fwrite(STDERR, error_get_last()['message'] . "\n"); } Co::wait(function () { $page = 0; do { $sources = yield get_github_followers_async(USERNAME, ++$page, $has_more); Co::async(function () use ($sources) { $requests = []; foreach ($sources as $username => $src) { $requests[] = download_image_async($src, $username); } yield $requests; }); } while ($has_more); }, ['concurrency' => 0, 'pipeline' => true]);
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/timer/timer.php
examples/timer/timer.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; Co::wait([ function () { for ($i = 0; $i < 8; ++$i) { yield CO::DELAY => 1.1; echo "[A] Timer: $i\n"; } }, function () { for ($i = 0; $i < 5; ++$i) { yield CO::DELAY => 1.7; echo "[B] Timer: $i\n"; } } ]);
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/timer/request-timer.php
examples/timer/request-timer.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; Co::wait(function () { yield [timer($stop), main($stop)]; }); function curl_init_with(string $url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, ], $options); curl_setopt_array($ch, $options); return $ch; } function timer(&$stop) { $ms = 0; while (true) { yield CO::DELAY => 0.2; if ($stop) break; $ms += 200; echo "[Timer]: $ms miliseconds passed\n"; } } function main(&$stop) { echo "Started first requests...\n"; var_dump(array_map('strlen', yield [ 'Content-Length of github.com' => curl_init_with('https://github.com/mpyw'), 'Content-Length of twitter.com' => curl_init_with('https://twitter.com/mpyw'), ])); echo "Started second requests...\n"; var_dump(array_map('strlen', yield [ 'Content-Length of example.com' => curl_init_with('http://example.com'), ])); $stop = true; }
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/intro/intro-php7.php
examples/intro/intro-php7.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; function curl_init_with(string $url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, ], $options); curl_setopt_array($ch, $options); return $ch; } function get_xpath_async(string $url) : \Generator { $dom = new \DOMDocument; @$dom->loadHTML(yield curl_init_with($url)); return new \DOMXPath($dom); } var_dump(Co::wait([ 'Delay 5 secs' => function () { echo "[Delay] I start to have a pseudo-sleep in this coroutine for about 5 secs\n"; for ($i = 0; $i < 5; ++$i) { yield Co::DELAY => 1; if ($i < 4) { printf("[Delay] %s\n", str_repeat('.', $i + 1)); } } echo "[Delay] Done!\n"; }, "google.com HTML" => curl_init_with("https://google.com"), "Content-Length of github.com" => function () { echo "[GitHub] I start to request for github.com to calculate Content-Length\n"; $content = yield curl_init_with("https://github.com"); echo "[GitHub] Done! Now I calculate length of contents\n"; return strlen($content); }, "Save mpyw's Gravatar Image URL to local" => function () { echo "[Gravatar] I start to request for github.com to get Gravatar URL\n"; $src = (yield get_xpath_async('https://github.com/mpyw')) ->evaluate('string(//img[contains(@class,"avatar")]/@src)'); echo "[Gravatar] Done! Now I download its data\n"; yield curl_init_with($src, [CURLOPT_FILE => fopen('/tmp/mpyw.png', 'wb')]); echo "[Gravatar] Done! Saved as /tmp/mpyw.png\n"; } ]));
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
mpyw/co
https://github.com/mpyw/co/blob/ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39/examples/intro/intro-php55.php
examples/intro/intro-php55.php
<?php require __DIR__ . '/../../vendor/autoload.php'; use mpyw\Co\Co; use mpyw\Co\CURLException; function curl_init_with($url, array $options = []) { $ch = curl_init(); $options = array_replace([ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, ], $options); curl_setopt_array($ch, $options); return $ch; } function get_xpath_async($url) { $dom = new \DOMDocument; @$dom->loadHTML(yield curl_init_with($url)); yield Co::RETURN_WITH => new \DOMXPath($dom); } var_dump(Co::wait([ 'Delay 5 secs' => function () { echo "[Delay] I start to have a pseudo-sleep in this coroutine for about 5 secs\n"; for ($i = 0; $i < 5; ++$i) { yield Co::DELAY => 1; if ($i < 4) { printf("[Delay] %s\n", str_repeat('.', $i + 1)); } } echo "[Delay] Done!\n"; }, "google.com HTML" => curl_init_with("https://google.com"), "Content-Length of github.com" => function () { echo "[GitHub] I start to request for github.com to calculate Content-Length\n"; $content = (yield curl_init_with("https://github.com")); echo "[GitHub] Done! Now I calculate length of contents\n"; yield Co::RETURN_WITH => strlen($content); }, "Save mpyw's Gravatar Image URL to local" => function () { echo "[Gravatar] I start to request for github.com to get Gravatar URL\n"; $xpath = (yield get_xpath_async('https://github.com/mpyw')); $src = $xpath->evaluate('string(//img[contains(@class,"avatar")]/@src)'); echo "[Gravatar] Done! Now I download its data\n"; yield curl_init_with($src, [CURLOPT_FILE => fopen('/tmp/mpyw.png', 'wb')]); echo "[Gravatar] Done! Saved as /tmp/mpyw.png\n"; } ]));
php
MIT
ca7d2c1ad3b0f8b8602b7988ac7a7b0f87331a39
2026-01-05T04:56:52.685374Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Api.php
src/Api.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Swoole\Coroutine; use Swoole\Coroutine\Barrier; use Xielei\Swoole\Cmd\BindUid; use Xielei\Swoole\Cmd\CloseClient; use Xielei\Swoole\Cmd\DeleteSession; use Xielei\Swoole\Cmd\GetClientCount; use Xielei\Swoole\Cmd\GetClientCountByGroup; use Xielei\Swoole\Cmd\GetClientInfo; use Xielei\Swoole\Cmd\GetClientList; use Xielei\Swoole\Cmd\GetClientListByGroup; use Xielei\Swoole\Cmd\GetClientListByUid; use Xielei\Swoole\Cmd\GetGroupList; use Xielei\Swoole\Cmd\GetSession; use Xielei\Swoole\Cmd\GetUidCount; use Xielei\Swoole\Cmd\GetUidList; use Xielei\Swoole\Cmd\GetUidListByGroup; use Xielei\Swoole\Cmd\IsOnline; use Xielei\Swoole\Cmd\JoinGroup; use Xielei\Swoole\Cmd\LeaveGroup; use Xielei\Swoole\Cmd\SendToAll; use Xielei\Swoole\Cmd\SendToClient; use Xielei\Swoole\Cmd\SendToGroup; use Xielei\Swoole\Cmd\SetSession; use Xielei\Swoole\Cmd\UnBindUid; use Xielei\Swoole\Cmd\UnGroup; use Xielei\Swoole\Cmd\UpdateSession; use Xielei\Swoole\Library\ClientPool; class Api { public static $address_list = null; /** * 给客户端发消息 * * @param string $client 客户端 * @param string $message 消息内容 * @return void */ public static function sendToClient(string $client, string $message) { $address = self::clientToAddress($client); self::sendToAddress($address, SendToClient::encode($address['fd'], $message)); } /** * 给绑定了指定uid的客户端发消息 * * @param string $uid uid * @param string $message 消息内容 * @param array $without_client_list 要排除的客户端列表 * @return void */ public static function sendToUid(string $uid, string $message, array $without_client_list = []) { foreach (self::getClientListByUid($uid) as $client) { if (!in_array($client, $without_client_list)) { self::sendToClient($client, $message); } } } /** * 给指定分组下的所有客户端发消息 * * @param string $group 组名称 * @param string $message 消息内容 * @param array $without_client_list 要排除的客户端 * @return void */ public static function sendToGroup(string $group, string $message, array $without_client_list = []) { foreach (self::$address_list as $address) { self::sendToAddress($address, SendToGroup::encode($group, $message, (function () use ($address, $without_client_list): array { $res = []; foreach ($without_client_list as $client) { $tmp = self::clientToAddress($client); if ($tmp['lan_host'] == $address['lan_host'] && $tmp['lan_port'] == $address['lan_port']) { $res[] = $tmp['fd']; } } return $res; })())); } } /** * 给所有客户端发消息 * * @param string $message 发送的内容 * @param array $without_client_list 要排除的客户端 * @return void */ public static function sendToAll(string $message, array $without_client_list = []) { foreach (self::$address_list as $address) { self::sendToAddress($address, SendToAll::encode($message, (function () use ($address, $without_client_list): array { $res = []; foreach ($without_client_list as $client) { $tmp = self::clientToAddress($client); if ($tmp['lan_host'] == $address['lan_host'] && $tmp['lan_port'] == $address['lan_port']) { $res[] = $tmp['fd']; } } return $res; })())); } } /** * 判断指定客户端是否在线 * * @param string $client * @return boolean */ public static function isOnline(string $client): bool { $address = self::clientToAddress($client); return isOnline::result(self::sendToAddressAndRecv($address, IsOnline::encode($address['fd']))); } /** * 判断指定uid是否在线 * * @param string $uid * @return boolean */ public static function isUidOnline(string $uid): bool { foreach (self::getClientListByUid($uid) as $value) { return true; } return false; } /** * 获取指定分组下的客户列表 * * @param string $group 分组名称 * @param string $prev_client 从该客户端开始读取 * @return iterable */ public static function getClientListByGroup(string $group, string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = self::clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } $buffer = GetClientListByGroup::encode($group); foreach (self::$address_list as $address) { if ($start || $address == $prev_address) { $res = self::sendToAddressAndRecv($address, $buffer); foreach (unpack('N*', $res) as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield self::addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $start = true; } } } /** * 获取所有客户端数量 * * @return integer */ public static function getClientCount(): int { $items = []; $buffer = GetClientCount::encode(); foreach (self::$address_list as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = self::sendToAddressListAndRecv($items); $count = 0; foreach ($buffers as $key => $buffer) { $data = unpack('Nnum', $buffer); $count += $data['num']; } return $count; } /** * 获取指定分组下的客户端数量 * * @param string $group * @return integer */ public static function getClientCountByGroup(string $group): int { $items = []; $buffer = GetClientCountByGroup::encode($group); foreach (self::$address_list as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = self::sendToAddressListAndRecv($items); $count = 0; foreach ($buffers as $key => $buffer) { $data = unpack('Ncount', $buffer); $count += $data['count']; } return $count; } /** * 获取客户端列表 * * @param string $prev_client 从该客户端开始读取 * @return iterable */ public static function getClientList(string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = self::clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } foreach (self::$address_list as $address) { if ($start || $address == $prev_address) { $tmp_prev_fd = 0; while ($fd_list = unpack('N*', self::sendToAddressAndRecv($address, GetClientList::encode(100, $tmp_prev_fd)))) { foreach ($fd_list as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield self::addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $tmp_prev_fd = $fd; } $start = true; } } } /** * 获取某个uid下绑定的客户端列表 * * @param string $uid * @param string $prev_client 从该客户但开始读取 * @return iterable */ public static function getClientListByUid(string $uid, string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = self::clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } $buffer = GetClientListByUid::encode($uid); foreach (self::$address_list as $address) { if ($start || $address == $prev_address) { $res = self::sendToAddressAndRecv($address, $buffer); foreach (unpack('N*', $res) as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield self::addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $start = true; } } } /** * 获取客户信息 * * @param string $client 客户端 * @param integer $type 具体要获取哪些数据,默认全部获取,也可按需获取,可选参数:Xielei\Swoole\Protocol::CLIENT_INFO_UID(绑定的uid) | Xielei\Swoole\Protocol::CLIENT_INFO_SESSION(session) | Xielei\Swoole\Protocol::CLIENT_INFO_GROUP_LIST(绑定的分组列表) | Xielei\Swoole\Protocol::CLIENT_INFO_REMOTE_IP(客户ip) | Xielei\Swoole\Protocol::CLIENT_INFO_REMOTE_PORT(客户端口) | Xielei\Swoole\Protocol::CLIENT_INFO_SYSTEM(客户系统信息) * @return array|null */ public static function getClientInfo(string $client, int $type = 255): ?array { $address = self::clientToAddress($client); return GetClientInfo::result(self::sendToAddressAndRecv($address, GetClientInfo::encode($address['fd'], $type))); } /** * 获取指定分组下客户绑定的uid列表 * * @param string $group 分组名称 * @param boolean $unique 是否过滤重复值 默认过滤,若用户数过多,会占用较大内存,建议根据需要设置 * @return iterable */ public static function getUidListByGroup(string $group, bool $unique = true): iterable { $uid_list = []; $buffer = GetUidListByGroup::encode($group); foreach (self::$address_list as $address) { $res = self::sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $uid = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($uid_list[$uid])) { $uid_list[$uid] = $uid; yield $uid; } } else { yield $uid; } $res = substr($res, 1 + $tmp['len']); } } unset($uid_list); } /** * 获取所有uid列表 * * @param boolean $unique 是否过滤重复值 默认过滤,若用户数过多,会占用较大内存,建议根据需要设置 * @return iterable */ public static function getUidList(bool $unique = true): iterable { $uid_list = []; $buffer = GetUidList::encode(); foreach (self::$address_list as $address) { $res = self::sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $uid = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($uid_list[$uid])) { $uid_list[$uid] = $uid; yield $uid; } } else { yield $uid; } $res = substr($res, 1 + $tmp['len']); } } unset($uid_list); } /** * 获取绑定的uid总数(该数据只是一个近似值),一个uid可能被多个gateway下的客户端绑定,考虑性能原因,并不计算精确值,在不传百分比的情况下,系统会自动计算一个近似百分比,通过该百分比计算出近似的总uid数 * * @param float $unique_percent 唯一百分比,例如:80%。若知道的情况下请尽量填写,这样数据更加准确。 * @return integer */ public static function getUidCount(float $unique_percent = null): int { $items = []; $buffer = GetUidCount::encode($unique_percent ? false : true); foreach (self::$address_list as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = self::sendToAddressListAndRecv($items); $count = 0; $uid_list = []; foreach ($buffers as $key => $buffer) { if ($buffer) { $data = unpack('Nnum', $buffer); $count += $data['num']; $res = substr($buffer, 8); while ($res) { $tmp = unpack('Clen', $res); $uid_list[] = substr($res, 1, $tmp['len']); $res = substr($res, 1 + $tmp['len']); } } } if ($unique_percent) { return intval($count * $unique_percent); } else { if ($uid_list) { return intval($count * count(array_unique($uid_list)) / count($uid_list)); } else { return $count; } } } /** * 获取分组列表 * * @param boolean $unique 是否去除重复数据,默认去除,若分组数据较多(例如百万级别),会占用很大的内存,若能够在业务上处理,请尽量设置为false * @return iterable */ public static function getGroupList(bool $unique = true): iterable { $group_list = []; $buffer = GetGroupList::encode(); foreach (self::$address_list as $key => $address) { $res = self::sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $group = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($group_list[$group])) { $group_list[$group] = $group; yield $group; } } else { yield $group; } $res = substr($res, 1 + $tmp['len']); } } unset($group_list); } /** * 获取指定分组下的用户数 * * @param string $group 分组名称 * @return integer */ public static function getUidCountByGroup(string $group): int { return count(iterator_to_array(self::getUidListByGroup($group))); } /** * 关闭客户端 * * @param string $client 客户端 * @param boolean $force 是否强制关闭,强制关闭会立即关闭客户端,不会等到待发送数据发送完毕就立即关闭 * @return void */ public static function closeClient(string $client, bool $force = false) { $address = self::clientToAddress($client); self::sendToAddress($address, CloseClient::encode($address['fd'], $force)); } /** * 绑定uid 一个客户端只能绑定一个uid,多次绑定只以最后一个为准,客户端下线会自动解绑,无需手动解绑 * * @param string $client * @param string $uid * @return void */ public static function bindUid(string $client, string $uid) { $address = self::clientToAddress($client); self::sendToAddress($address, BindUid::encode($address['fd'], $uid)); } /** * 取消绑定uid * * @param string $client * @return void */ public static function unBindUid(string $client) { $address = self::clientToAddress($client); self::sendToAddress($address, UnBindUid::encode($address['fd'])); } /** * 客户端加入到指定分组 客户断开会自动从加入的分组移除,无需手动处理 * * @param string $client 客户端 * @param string $group 分组名称 * @return void */ public static function joinGroup(string $client, string $group) { $address = self::clientToAddress($client); self::sendToAddress($address, JoinGroup::encode($address['fd'], $group)); } /** * 将客户端从指定分组移除 * * @param string $client 客户端 * @param string $group 指定分组 * @return void */ public static function leaveGroup(string $client, string $group) { $address = self::clientToAddress($client); self::sendToAddress($address, LeaveGroup::encode($address['fd'], $group)); } /** * 解散分组 * * @param string $group 分组名称 * @return void */ public static function unGroup(string $group) { $buffer = UnGroup::encode($group); foreach (self::$address_list as $address) { self::sendToAddress($address, $buffer); } } /** * 设置session 直接替换session * * @param string $client 客户端 * @param array $session session数据 * @return void */ public static function setSession(string $client, array $session) { $address = self::clientToAddress($client); self::sendToAddress($address, SetSession::encode($address['fd'], $session)); } /** * 更新指定客户端session 区别于设置session,设置是直接替换,更新会合并旧数据 * * @param string $client * @param array $session * @return void */ public static function updateSession(string $client, array $session) { $address = self::clientToAddress($client); self::sendToAddress($address, UpdateSession::encode($address['fd'], $session)); } /** * 删除指定客户端的session * * @param string $client * @return void */ public static function deleteSession(string $client) { $address = self::clientToAddress($client); self::sendToAddress($address, DeleteSession::encode($address['fd'])); } /** * 获取指定客户端session * * @param string $client * @return array|null */ public static function getSession(string $client): ?array { $address = self::clientToAddress($client); $buffer = self::sendToAddressAndRecv($address, GetSession::encode($address['fd'])); return unserialize($buffer); } // 以下为核心基本方法 /** * 向多个地址发送数据并批量接收 * * @param array $items * @param float $timeout 超时时间 单位秒 * @return array */ public static function sendToAddressListAndRecv(array $items, float $timeout = 1): array { $barrier = Barrier::make(); $res = []; foreach ($items as $key => $item) { Coroutine::create(function () use ($barrier, $key, $item, $timeout, &$res) { $res[$key] = self::sendToAddressAndRecv($item['address'], $item['buffer'], $timeout); }); } Barrier::wait($barrier); return $res; } /** * 向指定地址发送数据后返回数据 * * @param array $address 指定地址 * @param string $buffer 发送的数据 * @param float $timeout 超时时间 单位秒 * @return string */ public static function sendToAddressAndRecv(array $address, string $buffer, float $timeout = 1): string { return Protocol::decode(self::getConnPool($address['lan_host'], $address['lan_port'])->sendAndRecv(Protocol::encode($buffer), $timeout)); } /** * 向指定地址发送数据 * * @param array $address 指定地址 * @param string $buffer 数据 * @return void */ public static function sendToAddress(array $address, string $buffer) { self::getConnPool($address['lan_host'], $address['lan_port'])->send(Protocol::encode($buffer)); } public static function getConnPool($host, $port, int $size = 64): ClientPool { static $pools = []; if (!isset($pools[$host . ':' . $port])) { $pools[$host . ':' . $port] = new ClientPool($host, $port, $size); } return $pools[$host . ':' . $port]; } public static function addressToClient(array $address): string { return bin2hex(pack('NnN', ip2long($address['lan_host']), $address['lan_port'], $address['fd'])); } public static function clientToAddress(string $client): array { $res = unpack('Nlan_host/nlan_port/Nfd', hex2bin($client)); $res['lan_host'] = long2ip($res['lan_host']); return $res; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Register.php
src/Register.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Swoole\Coroutine\Server\Connection; use Swoole\Server; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Library\SockServer; class Register extends Service { protected $inner_server; protected $register_host; protected $register_port; public function __construct(string $register_host = '127.0.0.1', int $register_port = 9327) { parent::__construct(); Config::set('init_file', __DIR__ . '/init/register.php'); $this->register_host = $register_host; $this->register_port = $register_port; $this->inner_server = new SockServer(function (Connection $conn, $data) { if (!is_array($data)) { return; } switch (array_shift($data)) { case 'status': $ret = [ 'sw_version' => SW_VERSION, ] + $this->getServer()->stats() + $this->getServer()->setting + [ 'daemonize' => $this->daemonize, 'register_host' => $this->register_host, 'register_port' => $this->register_port, 'worker_count' => count($this->globals->get('worker_fd_list', [])), 'worker_list' => (function (): string { $res = []; foreach ($this->globals->get('worker_fd_list', []) as $fd) { $res[$fd] = $this->getServer()->getClientInfo($fd); } return json_encode($res); })(), 'gateway_count' => count($this->globals->get('gateway_address_list', [])), 'gateway_list' => (function () { $res = []; foreach ($this->globals->get('gateway_address_list', []) as $fd => $value) { $tmp = unpack('Nlan_host/nlan_port', $value); $tmp['lan_host'] = long2ip($tmp['lan_host']); $res[$fd] = array_merge($this->getServer()->getClientInfo($fd), $tmp); } return json_encode($res); })(), ]; $ret['start_time'] = date(DATE_ISO8601, $ret['start_time']); SockServer::sendToConn($conn, $ret); break; case 'reload': $this->getServer()->reload(); break; default: break; } }, '/var/run/' . str_replace('/', '_', array_pop(debug_backtrace())['file']) . '.sock'); $this->addCommand('status', 'status', 'displays the running status of the service', function (array $args): int { if (!$this->isRun()) { fwrite(STDOUT, "the service is not running!\n"); return self::PANEL_LISTEN; } $res = $this->inner_server->streamWriteAndRead(['status']); foreach ($res as $key => $value) { fwrite(STDOUT, str_pad((string) $key, 25, '.', STR_PAD_RIGHT) . ' ' . $value . "\n"); } return self::PANEL_LISTEN; }); } protected function createServer(): Server { $server = new Server($this->register_host, $this->register_port, SWOOLE_PROCESS, SWOOLE_SOCK_TCP); $this->inner_server->mountTo($server); $this->set([ 'heartbeat_idle_time' => 60, 'heartbeat_check_interval' => 3, 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); return $server; } protected function broadcastGatewayAddressList(int $fd = null) { $load = pack('C', Protocol::BROADCAST_GATEWAY_LIST) . implode('', $this->globals->get('gateway_address_list', [])); $buffer = Protocol::encode($load); if ($fd) { $this->getServer()->send($fd, $buffer); } else { foreach ($this->globals->get('worker_fd_list', []) as $fd => $info) { $this->getServer()->send($fd, $buffer); } } $addresses = []; foreach ($this->globals->get('gateway_address_list', []) as $value) { $tmp = unpack('Nhost/nport', $value); $tmp['host'] = long2ip($tmp['host']); $addresses[] = $tmp; } $addresses = json_encode($addresses); if ($fd) { Service::debug("broadcastGatewayAddressList fd:{$fd} addresses:{$addresses}"); } else { Service::debug("broadcastGatewayAddressList addresses:{$addresses}"); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Gateway.php
src/Gateway.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Swoole\Coroutine; use Swoole\Coroutine\Server\Connection; use Swoole\Process; use Swoole\Server as SwooleServer; use Swoole\Timer; use Swoole\WebSocket\Server as WebSocketServer; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Library\Client; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Library\Reload; use Xielei\Swoole\Library\Server; use Xielei\Swoole\Library\SockServer; class Gateway extends Service { public $register_host = '127.0.0.1'; public $register_port = 9327; public $lan_host = '127.0.0.1'; public $lan_port = 9108; protected $inner_server; protected $process; protected $command_list = []; public $worker_list = []; public $fd_list = []; public $uid_list = []; public $group_list = []; protected $throttle_list = []; protected $listen_list = []; public function __construct() { parent::__construct(); Config::set('init_file', __DIR__ . '/init/gateway.php'); Config::set('router', function (int $fd, int $cmd, array $worker_list) { if ($worker_list) { return $worker_list[array_keys($worker_list)[$fd % count($worker_list)]]; } }); $this->inner_server = new SockServer(function (Connection $conn, $data) { if (!is_array($data)) { return; } switch (array_shift($data)) { case 'status': $ret = [ 'sw_version' => SW_VERSION, ] + $this->getServer()->stats() + $this->getServer()->setting + [ 'daemonize' => $this->daemonize, 'register_host' => $this->register_host, 'register_port' => $this->register_port, 'lan_host' => $this->lan_host, 'lan_port' => $this->lan_port, 'listen_list' => json_encode($this->listen_list), ]; $ret['start_time'] = date(DATE_ISO8601, $ret['start_time']); SockServer::sendToConn($conn, $ret); break; case 'reload': $this->getServer()->reload(); break; default: break; } }, '/var/run/' . str_replace('/', '_', array_pop(debug_backtrace())['file']) . '.sock'); $this->addCommand('status', 'status', 'displays the running status of the service', function (array $args): int { if (!$this->isRun()) { fwrite(STDOUT, "the service is not running!\n"); return self::PANEL_LISTEN; } $res = $this->inner_server->streamWriteAndRead(['status']); foreach ($res as $key => $value) { fwrite(STDOUT, str_pad((string) $key, 25, '.', STR_PAD_RIGHT) . ' ' . $value . "\n"); } return self::PANEL_LISTEN; }); } protected function createServer(): SwooleServer { $server = new WebSocketServer('127.0.0.1', 0, SWOOLE_PROCESS); foreach ($this->listen_list as $listen) { $port = $server->addListener($listen['host'], $listen['port'], $listen['sockType']); $port->set($listen['options']); if (isset($listen['options']['open_websocket_protocol']) && $listen['options']['open_websocket_protocol']) { $port->on('Connect', function () { }); $port->on('Request', function ($request, $response) { $response->status(403); $response->end("Not Supported~\n"); }); } } $this->inner_server->mountTo($server); $this->process = new Process(function ($process) use ($server) { Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); Timer::tick(1000, function () { if (Reload::check()) { Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); $this->loadCommand(); } }); $this->loadCommand(); $this->connectToRegister(); $this->startLanServer(); Coroutine::create(function () use ($process) { $socket = $process->exportSocket(); $socket->setProtocol([ 'open_length_check' => true, 'package_length_type' => 'N', 'package_length_offset' => 0, 'package_body_offset' => 0, ]); while (true) { $buffer = $socket->recv(); if (!$buffer) { continue; } $res = unserialize($buffer); switch ($res['event']) { case 'Connect': list($event) = $res['args']; $this->fd_list[$event['fd']] = [ 'uid' => '', 'session' => [], 'group_list' => [], 'ws' => 0, ]; $session_string = ''; $load = pack('CNN', Protocol::EVENT_CONNECT, $event['fd'], strlen($session_string)) . $session_string; $this->sendToWorker(Protocol::EVENT_CONNECT, $event['fd'], $load); break; case 'Receive': list($event) = $res['args']; $bind = $this->fd_list[$event['fd']]; $session_string = $bind['session'] ? serialize($bind['session']) : ''; $load = pack('CNN', Protocol::EVENT_RECEIVE, $event['fd'], strlen($session_string)) . $session_string . $event['data']; $this->sendToWorker(Protocol::EVENT_RECEIVE, $event['fd'], $load); break; case 'Close': list($event) = $res['args']; if (!isset($this->fd_list[$event['fd']])) { break; } $bind = $this->fd_list[$event['fd']]; $bind['group_list'] = array_values($bind['group_list']); $session_string = $bind['session'] ? serialize($bind['session']) : ''; unset($bind['session']); $load = pack('CNN', Protocol::EVENT_CLOSE, $event['fd'], strlen($session_string)) . $session_string . serialize($bind); $this->sendToWorker(Protocol::EVENT_CLOSE, $event['fd'], $load); if ($bind_uid = $this->fd_list[$event['fd']]['uid']) { unset($this->uid_list[$bind_uid][$event['fd']]); if (!$this->uid_list[$bind_uid]) { unset($this->uid_list[$bind_uid]); } } foreach ($this->fd_list[$event['fd']]['group_list'] as $bind_group) { unset($this->group_list[$bind_group][$event['fd']]); if (!$this->group_list[$bind_group]) { unset($this->group_list[$bind_group]); } } unset($this->fd_list[$event['fd']]); break; case 'Open': list($request) = $res['args']; $this->fd_list[$request['fd']] = [ 'uid' => '', 'session' => [], 'group_list' => [], 'ws' => 1, ]; $session_string = ''; $load = pack('CNN', Protocol::EVENT_OPEN, $request['fd'], strlen($session_string)) . $session_string . serialize($request); $this->sendToWorker(Protocol::EVENT_OPEN, $request['fd'], $load); break; case 'Message': list($frame) = $res['args']; $bind = $this->fd_list[$frame['fd']]; $session_string = $bind['session'] ? serialize($bind['session']) : ''; $load = pack('CNN', Protocol::EVENT_MESSAGE, $frame['fd'], strlen($session_string)) . $session_string . pack('CC', $frame['opcode'], $frame['flags']) . $frame['data']; $this->sendToWorker(Protocol::EVENT_MESSAGE, $frame['fd'], $load); break; default: Service::debug("undefined event. buffer:{$buffer}"); break; } } }); }, false, 2, true); $server->addProcess($this->process); return $server; } public function listen(string $host, int $port, array $options = [], int $sockType = SWOOLE_SOCK_TCP) { $this->listen_list[$host . ':' . $port] = [ 'host' => $host, 'port' => $port, 'sockType' => $sockType, 'options' => $options, ]; } protected function sendToProcess($data) { $this->process->exportSocket()->send(serialize($data)); } public function sendToClient(int $fd, string $message) { if (isset($this->fd_list[$fd]['ws']) && $this->fd_list[$fd]['ws']) { $this->getServer()->send($fd, WebSocketServer::pack($message)); } else { $this->getServer()->send($fd, $message); } } protected function sendToWorker(int $cmd, int $fd, string $load) { if ($worker = call_user_func(Config::get('router'), $fd, $cmd, $this->worker_list)) { $pool = $worker['pool']; $conn = $pool->get(); $conn->send(Protocol::encode($load)); $pool->put($conn); $buff = bin2hex(Protocol::encode($load)); Service::debug("send to worker:{$buff}"); } else { Service::debug("worker not found"); } } protected function loadCommand() { $command_list = []; foreach (glob(__DIR__ . '/Cmd/*.php') as $filename) { $cmd = __NAMESPACE__ . '\\Cmd\\' . pathinfo($filename, PATHINFO_FILENAME); if (is_a($cmd, CmdInterface::class, true)) { $command_list[$cmd::getCommandCode()] = $cmd; } } foreach (Config::get('command_extra_list', []) as $cmd) { if (is_a($cmd, CmdInterface::class, true)) { $command_list[$cmd::getCommandCode()] = $cmd; } } $this->command_list = $command_list; } protected function startLanServer() { Service::debug('start to startLanServer'); $server = new Server($this->lan_host, $this->lan_port); $server->onConnect = function (Connection $conn) { $conn->peername = $conn->exportSocket()->getpeername(); }; $server->onMessage = function (Connection $conn, string $buffer) { $load = Protocol::decode($buffer); $data = unpack("Ccmd", $load); if (isset($this->command_list[$data['cmd']])) { call_user_func([$this->command_list[$data['cmd']], 'execute'], $this, $conn, substr($load, 1)); } else { $hex_buffer = bin2hex($buffer); Service::debug("cmd:{$data['cmd']} not surport! buffer:{$hex_buffer}"); } }; $server->onClose = function (Connection $conn) { $address = implode(':', $conn->peername); if (isset($this->worker_list[$address])) { Service::debug("close worker client {$address}"); $pool = $this->worker_list[$address]['pool']; $conn = $pool->get(); $conn->close(); $pool->close(); unset($this->worker_list[$address]); } else { Service::debug("close worker connect {$address}"); } }; $server->start(); } protected function connectToRegister() { Service::debug('start to connectToRegister'); $client = new Client($this->register_host, $this->register_port); $client->onConnect = function () use ($client) { Service::debug('reg to register'); $client->send(Protocol::encode(pack('CNn', Protocol::GATEWAY_CONNECT, ip2long($this->lan_host), $this->lan_port) . Config::get('register_secret', ''))); $ping_buffer = Protocol::encode(pack('C', Protocol::PING)); $client->timer_id = Timer::tick(30000, function () use ($client, $ping_buffer) { Service::debug('ping to register'); $client->send($ping_buffer); }); }; $client->onClose = function () use ($client) { Service::debug('close by register'); if ($client->timer_id) { Timer::clear($client->timer_id); unset($client->timer_id); } Coroutine::sleep(1); Service::debug("reconnect to register"); $client->connect(); }; $client->start(); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Protocol.php
src/Protocol.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Exception; class Protocol { const PING = 0; const GATEWAY_CONNECT = 1; const WORKER_CONNECT = 2; const BROADCAST_GATEWAY_LIST = 3; const EVENT_CONNECT = 20; const EVENT_RECEIVE = 21; const EVENT_CLOSE = 22; const EVENT_OPEN = 23; const EVENT_MESSAGE = 24; const CLIENT_INFO_REMOTE_IP = 0b00000001; const CLIENT_INFO_REMOTE_PORT = 0b00000010; const CLIENT_INFO_UID = 0b00000100; const CLIENT_INFO_SESSION = 0b00001000; const CLIENT_INFO_GROUP_LIST = 0b00010000; const CLIENT_INFO_SYSTEM = 0b00100000; public static function encode(string $load = ''): string { return pack('NN', 8 + strlen($load), crc32($load)) . $load; } public static function decode(string $buffer): string { $tmp = unpack('Nlen/Ncrc', $buffer); if ($tmp['len'] !== strlen($buffer)) { $hex = bin2hex($buffer); throw new Exception("protocol decode failure! buffer:{$hex}"); } $load = substr($buffer, 8); if ($tmp['crc'] !== crc32($load)) { $hex = bin2hex($buffer); throw new Exception("protocol decode failure! buffer:{$hex}"); } return $load; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cli.php
src/Cli.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Throwable; class Cli { const PANEL_IGNORE = 0; const PANEL_START = 1; const PANEL_LISTEN = 2; const PANEL_EXIT = 99; private $cmds = []; public function __construct() { if (php_sapi_name() != 'cli') { exit("only run in cli~\n"); } $this->addCommand('help', 'help', 'display help', function (array $args): int { fwrite(STDOUT, "{$this->getHelp()}\n"); return self::PANEL_LISTEN; }); $this->addCommand('exit', 'exit', 'exit cmd panel', function (array $args): int { return self::PANEL_EXIT; }); $this->addCommand('clear', 'clear', 'clear screen', function (array $args): int { return self::PANEL_START; }); } final public function start() { global $argv; if (isset($argv[1])) { array_shift($argv); $arg_str = implode(' ', $argv); $parse = $this->parseCmd($arg_str); $this->execCommand($parse['cmd'], $parse['args']); exit; } else { fwrite(STDOUT, "\e[2J"); fwrite(STDOUT, "\e[0;0H"); fwrite(STDOUT, "{$this->getLogo()}\n\n"); fwrite(STDOUT, "Press \e[1;33m[Ctrl+C]\e[0m to exit, send \e[1;33m'help'\e[0m to show help.\n"); $this->listen(); } } private function listen() { fwrite(STDOUT, "> "); $input = trim((string) fgets(STDIN)); if (!$input) { return $this->listen(); } $parse = $this->parseCmd($input); switch ($this->execCommand($parse['cmd'], $parse['args'])) { case self::PANEL_START: return $this->start(); break; case self::PANEL_EXIT: break; case self::PANEL_LISTEN: return $this->listen(); break; default: break; } } final protected function addCommand(string $cmd, string $usage, string $help, callable $callback) { $this->cmds[$cmd] = [ 'usage' => $usage, 'help' => $help, 'callback' => $callback, ]; } final protected function execCommand(string $cmd, array $args = []): int { try { if (!isset($this->cmds[$cmd])) { fwrite(STDOUT, "Command \e[1;34m'{$cmd}'\e[0m is not supported, send \e[1;34m'help'\e[0m to view help.\n"); return self::PANEL_LISTEN; } return call_user_func($this->cmds[$cmd]['callback'], $args); } catch (Throwable $th) { $msg = "\e[1;31mFatal error: \e[0m Uncaught exception '" . get_class($th) . "' with message:\n"; $msg .= "{$th->getMessage()}\n"; $msg .= "thrown in {$th->getFile()} on line {$th->getLine()}\n"; $msg .= "Trace:\n{$th->getTraceAsString()}\n"; fwrite(STDOUT, "{$msg}"); return self::PANEL_LISTEN; } } final protected function getLogo(): string { return <<<str \e[0;34m_____ \e[0m _ \e[0;34m __ __\e[0m _ \e[0;34m/ ____|\e[0m | | \e[0;34m\ \ / /\e[0m | | \e[1;37m®\e[0m \e[0;34m| (___\e[0m__ _____ ___ | | __\e[0;34m\ \ /\ / /\e[0m__ _ __| | _____ _ __ \e[0;34m\___\e[0m \ \ /\ / / _ \ / _ \| |/ _ \e[0;34m\ \/ \/ /\e[0m _ \| '__| |/ / _ \ '__| \e[0;34m ____)\e[0m \ V V / (_) | (_) | | __/\e[0;34m\ /\ /\e[0m (_) | | | < __/ | \e[0;34m|_____/\e[0m \_/\_/ \___/ \___/|_|\___| \e[0;34m\/ \/\e[0m \___/|_| |_|\_\___|_| ================================================= SwooleWorker is a distributed long connection development framework based on Swoole. [HomePage] https://swoole.plus ================================================= str; } protected function getHelp(): string { $str = ''; $str .= "**************************** HELP ****************************\n"; $str .= "*\e[0;36m cmd description...\e[0m\n"; foreach ($this->cmds as $cmd => $opt) { $str .= '* ' . str_pad($opt['usage'], 30, ' ', STR_PAD_RIGHT) . $opt['help'] . "\n"; } $str .= "****************************************************************"; return $str; } private function parseCmd(string $input): array { $tmp = explode(' ', $input); $cmd = []; $args = []; while (true) { if (!$tmp) { break; } $value = (string) array_shift($tmp); if (strpos($value, '--') === 0) { $key = substr($value, 2); $v = []; while (true) { if (!$tmp) { break; } $t = (string) array_shift($tmp); if (strpos($t, '-') === 0) { array_unshift($tmp, $t); break; } $v[] = $t; } $args[$key] = implode(' ', $v); } elseif (strpos($value, '-') === 0) { $keys = str_split(str_replace('-', '', $value)); $v = []; while (true) { if (!$tmp) { break; } $t = (string) array_shift($tmp); if (strpos($t, '-') === 0) { array_unshift($tmp, $t); break; } $v[] = $t; } foreach ($keys as $key) { $args[$key] = implode(' ', $v); } } else { if (!in_array($value, [''])) { $cmd[] = $value; } } } return [ 'cmd' => implode(' ', $cmd), 'args' => $args, ]; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Service.php
src/Service.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Swoole\Process; use Swoole\Server as SwooleServer; use Swoole\Timer; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Library\Globals; use Xielei\Swoole\Library\Reload; define('SW_VERSION', '2.0.0'); /** * @property Globals $globals */ abstract class Service extends Cli { public $config_file; protected $pid_file; protected $daemonize = false; protected $server; protected $globals; protected $events; protected $config = []; public function __construct() { parent::__construct(); if (!defined('SWOOLE_VERSION')) { fwrite(STDOUT, $this->getLogo()); exit("\n\033[1;31mError: Please install Swoole~\033[0m\n\033[1;36m[Swoole](https://www.swoole.com/)\033[0m\n"); } if (!version_compare(SWOOLE_VERSION, '4.6.0', '>=')) { fwrite(STDOUT, $this->getLogo()); exit("\n\033[1;31mError: Swoole >= 4.6.0, current version:" . SWOOLE_VERSION . "\033[0m\n\033[1;36m[Swoole](https://www.swoole.com/)\033[0m\n"); } $this->pid_file = __DIR__ . '/../' . str_replace('/', '_', array_pop(debug_backtrace())['file']) . '.pid'; $this->addCommand('start', 'start [-d]', 'start the service,\'-d\' daemonize mode', function (array $args): int { if ($this->isRun()) { fwrite(STDOUT, "the service is running, please run restart if you want to restart service.\n"); return self::PANEL_LISTEN; } if (isset($args['d'])) { $this->daemonize = true; } else { $this->daemonize = false; } if ($this->daemonize) { fwrite(STDOUT, "the service is running with daemonize\n"); if (function_exists('pcntl_fork')) { $child_pid = pcntl_fork(); if ($child_pid === -1) { fwrite(STDOUT, "pcntl_fork error\n"); return self::PANEL_LISTEN; } else if ($child_pid === 0) { $this->startServer(); exit(); } else { return self::PANEL_LISTEN; } } else { fwrite(STDOUT, "please abli function pcntl_fork.\n"); $this->startServer(); } } else { fwrite(STDOUT, "the service is running\n"); $this->startServer(); } return self::PANEL_IGNORE; }); $this->addCommand('restart', 'restart [-d]', 'restart the service,\'-d\' daemonize mode', function (array $args): int { if ($this->isRun()) { $this->execCommand('stop', $args); } return $this->execCommand('start', $args); }); $this->addCommand('reload', 'reload', 'reload worker and task', function (array $args): int { if (!$this->isRun()) { fwrite(STDOUT, "the service is not running!\n"); return self::PANEL_LISTEN; } $pid = (int) file_get_contents($this->pid_file); $sig = SIGUSR1; Process::kill($pid, $sig); fwrite(STDOUT, "the service reload command sent successfully!\n"); fwrite(STDOUT, "you can view the results through the log file.\n"); return self::PANEL_LISTEN; }); $this->addCommand('stop', 'stop [-f]', 'stop the service,\'-f\' force stop', function (array $args): int { if (!$this->isRun()) { fwrite(STDOUT, "the service is not running!\n"); return self::PANEL_LISTEN; } if (!file_exists($this->pid_file)) { fwrite(STDOUT, "PID file '{$this->pid_file}' missing, please find the main process PID and kill!\n"); return self::PANEL_LISTEN; } $pid = (int) file_get_contents($this->pid_file); if (!Process::kill($pid, 0)) { fwrite(STDOUT, "process does not exist!\n"); return self::PANEL_LISTEN; } if (isset($args['f'])) { $sig = SIGKILL; } else { $sig = SIGTERM; } Process::kill($pid, $sig); fwrite(STDOUT, "the service stopping...\n"); $time = time(); while (true) { sleep(1); if (!Process::kill($pid, 0)) { if (is_file($this->pid_file)) { unlink($this->pid_file); fwrite(STDOUT, "unlink the pid file success.\n"); } fwrite(STDOUT, "the service stopped.\n"); break; } else { if (time() - $time > 5) { fwrite(STDOUT, "stop the service fail, please try again!\n"); break; } } } return self::PANEL_LISTEN; }); } private function startServer() { cli_set_process_title(str_replace('/', '_', array_pop(debug_backtrace())['file'])); $server = $this->createServer(); $this->globals = new Globals(); $this->globals->mountTo($server); $server->addProcess(new Process(function () use ($server) { Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); Timer::tick(1000, function () use ($server) { if (Reload::check()) { $server->reload(); Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); } }); }, false, 2, true)); $server->on('WorkerStart', function (...$args) { Config::load($this->config_file); if (Config::isset('init_file')) { include Config::get('init_file'); } $this->emit('WorkerStart', ...$args); }); foreach (['WorkerExit', 'WorkerStop', 'PipeMessage', 'Task', 'Finish', 'Connect', 'Receive', 'Close', 'Open', 'Message', 'Request', 'Packet'] as $event) { $server->on($event, function (...$args) use ($event) { $this->emit($event, ...$args); }); } $server->set(array_merge($this->config, [ 'pid_file' => $this->pid_file, 'daemonize' => $this->daemonize, 'event_object' => true, 'task_object' => true, 'reload_async' => true, 'max_wait_time' => 60, 'enable_coroutine' => true, 'task_enable_coroutine' => true, ])); $this->server = $server; $server->start(); } abstract protected function createServer(): SwooleServer; public function set(array $config = []) { $this->config = array_merge($this->config, $config); } protected function emit(string $event, ...$args) { $event = strtolower('on' . $event); Service::debug("emit {$event}"); call_user_func($this->events[$event] ?? function () { }, ...$args); } protected function on(string $event, callable $callback) { $event = strtolower('on' . $event); $this->events[$event] = $callback; } public function getServer(): SwooleServer { return $this->server; } /** * @deprecated Please use redis or other. The next version will be deprecated */ public function getGlobals(): Globals { return $this->globals; } public static function debug(string $info) { if (Config::get('debug', false)) { fwrite(STDOUT, '[' . date(DATE_ISO8601) . ']' . " {$info}\n"); } } protected function isRun(): bool { if (file_exists($this->pid_file)) { $pid = (int) file_get_contents($this->pid_file); if (Process::kill($pid, 0)) { return true; } return false; } return false; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Worker.php
src/Worker.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Swoole\Coroutine; use Swoole\Process; use Swoole\Server as SwooleServer; use Swoole\Timer; use Xielei\Swoole\Cmd\Ping; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Cmd\RegisterWorker; use Xielei\Swoole\Library\Client; use Xielei\Swoole\Library\Config; use Xielei\Swoole\Library\Reload; use Xielei\Swoole\Library\SockServer; class Worker extends Service { public $register_host = '127.0.0.1'; public $register_port = 9327; protected $process; protected $inner_server; protected $gateway_address_list = []; protected $gateway_conn_list = []; public function __construct() { parent::__construct(); $this->set([ 'task_worker_num' => swoole_cpu_num() ]); Config::set('init_file', __DIR__ . '/init/worker.php'); $this->inner_server = new SockServer(function (Connection $conn, $data) { if (!is_array($data)) { return; } switch (array_shift($data)) { case 'status': $ret = [ 'sw_version' => SW_VERSION, ] + $this->getServer()->stats() + $this->getServer()->setting + [ 'daemonize' => $this->daemonize, 'register_host' => $this->register_host, 'register_port' => $this->register_port, 'gateway_address_list' => json_encode($this->globals->get('gateway_address_list')), ]; $ret['start_time'] = date(DATE_ISO8601, $ret['start_time']); SockServer::sendToConn($conn, $ret); break; case 'reload': $this->getServer()->reload(); break; default: break; } }, '/var/run/' . str_replace('/', '_', array_pop(debug_backtrace())['file']) . '.sock'); $this->addCommand('status', 'status', 'displays the running status of the service', function (array $args): int { if (!$this->isRun()) { fwrite(STDOUT, "the service is not running!\n"); return self::PANEL_LISTEN; } $res = $this->inner_server->streamWriteAndRead(['status']); foreach ($res as $key => $value) { fwrite(STDOUT, str_pad((string) $key, 25, '.', STR_PAD_RIGHT) . ' ' . $value . "\n"); } return self::PANEL_LISTEN; }); } protected function createServer(): SwooleServer { $server = new SwooleServer('127.0.0.1', 0, SWOOLE_PROCESS, SWOOLE_SOCK_TCP); $this->inner_server->mountTo($server); $this->process = new Process(function ($process) { Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); Timer::tick(1000, function () { if (Reload::check()) { Config::load($this->config_file); $watch = Config::get('reload_watch', []); $watch[] = $this->config_file; Reload::init($watch); } }); $this->connectToRegister(); $socket = $process->exportSocket(); while (true) { $msg = $socket->recv(); if (!$msg) { continue; } $res = unserialize($msg); switch ($res['event']) { case 'gateway_address_list': $this->getServer()->sendMessage(serialize([ 'event' => 'gateway_address_list', 'gateway_address_list' => $this->gateway_address_list, ]), $res['worker_id']); break; } Coroutine::sleep(1); } }, false, 2, true); $server->addProcess($this->process); $this->set([ 'task_enable_coroutine' => true, ]); return $server; } protected function sendToProcess($data) { $this->process->exportSocket()->send(serialize($data)); } protected function connectToRegister() { $client = new Client($this->register_host, $this->register_port); $client->onConnect = function () use ($client) { Service::debug("connect to register"); $client->send(Protocol::encode(pack('C', Protocol::WORKER_CONNECT) . Config::get('register_secret', ''))); $ping_buffer = Protocol::encode(pack('C', Protocol::PING)); $client->timer_id = Timer::tick(30000, function () use ($client, $ping_buffer) { Service::debug("send ping to register"); $client->send($ping_buffer); }); }; $client->onMessage = function (string $buffer) { Service::debug("receive message from register"); $data = unpack('Ccmd/A*load', Protocol::decode($buffer)); switch ($data['cmd']) { case Protocol::BROADCAST_GATEWAY_LIST: $addresses = []; if ($data['load'] && (strlen($data['load']) % 6 === 0)) { foreach (str_split($data['load'], 6) as $value) { $address = unpack('Nlan_host/nlan_port', $value); $address['lan_host'] = long2ip($address['lan_host']); $addresses[$address['lan_host'] . ':' . $address['lan_port']] = $address; } } $this->globals->set('gateway_address_list', $addresses); $this->gateway_address_list = $addresses; for ($i = 0; $i < $this->getServer()->setting['worker_num'] + $this->getServer()->setting['task_worker_num']; $i++) { $this->getServer()->sendMessage(serialize([ 'event' => 'gateway_address_list', 'gateway_address_list' => $this->gateway_address_list, ]), $i); } $this->refreshGatewayConn(); break; default: break; } }; $client->onClose = function () use ($client) { Service::debug("closed by register"); if (isset($client->timer_id)) { Timer::clear($client->timer_id); unset($client->timer_id); } Coroutine::sleep(1); Service::debug("reconnect to register"); $client->connect(); }; $client->start(); } protected function refreshGatewayConn() { $new_address_list = array_diff_key($this->gateway_address_list, $this->gateway_conn_list); foreach ($new_address_list as $key => $address) { $client = new Client($address['lan_host'], $address['lan_port']); $client->onConnect = function () use ($client, $address) { Service::debug("connect to gateway {$address['lan_host']}:{$address['lan_port']} 成功"); $client->send(Protocol::encode(RegisterWorker::encode(Config::get('tag_list', [])))); $ping_buffer = Protocol::encode(pack('C', Ping::getCommandCode())); $client->timer_id = Timer::tick(30000, function () use ($client, $ping_buffer, $address) { Service::debug("send ping to gateway {$address['lan_host']}:{$address['lan_port']}"); $client->send($ping_buffer); }); }; $client->onMessage = function (string $buffer) use ($address) { $this->getServer()->sendMessage(serialize([ 'event' => 'gateway_event', 'buffer' => $buffer, 'address' => $address, ]), $address['lan_port'] % $this->getServer()->setting['worker_num']); }; $client->onClose = function () use ($client, $address) { if (isset($client->timer_id)) { Timer::clear($client->timer_id); unset($client->timer_id); } Coroutine::sleep(1); Service::debug("reconnect to gateway {$address['lan_host']}:{$address['lan_port']}"); $client->connect(); }; $client->start(); $this->gateway_conn_list[$key] = $client; } $off_address_list = array_diff_key($this->gateway_conn_list, $this->gateway_address_list); foreach ($off_address_list as $key => $client) { $client->stop(); unset($this->gateway_conn_list[$key]); } } protected function dispatch(string $event, ...$args) { Service::debug("dispatch {$event}"); call_user_func([$this->event, $event], ...$args); } protected function onGatewayMessage($buffer, $address) { $data = unpack('Ccmd/Nfd/Nsession_len/A*data', Protocol::decode($buffer)); $session = $data['session_len'] ? unserialize(substr($data['data'], 0, $data['session_len'])) : []; $extra = substr($data['data'], $data['session_len']); $client = bin2hex(pack('NnN', ip2long($address['lan_host']), $address['lan_port'], $data['fd'])); switch ($data['cmd']) { case Protocol::EVENT_CONNECT: $this->dispatch('onConnect', $client, $session); break; case Protocol::EVENT_RECEIVE: $this->dispatch('onReceive', $client, $session, $extra); break; case Protocol::EVENT_CLOSE: $this->dispatch('onClose', $client, $session, unserialize($extra)); break; case Protocol::EVENT_OPEN: $this->dispatch('onOpen', $client, $session, unserialize($extra)); break; case Protocol::EVENT_MESSAGE: $frame = unpack('Copcode/Cflags', $extra); $frame['data'] = substr($extra, 2); $this->dispatch('onMessage', $client, $session, $frame); break; default: Service::debug("undefined cmd from gateway! cmdcode:{$data['cmd']}"); break; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/HttpApi.php
src/HttpApi.php
<?php declare(strict_types=1); namespace Xielei\Swoole; use Exception; use Xielei\Swoole\Cmd\BindUid; use Xielei\Swoole\Cmd\CloseClient; use Xielei\Swoole\Cmd\DeleteSession; use Xielei\Swoole\Cmd\GetClientCount; use Xielei\Swoole\Cmd\GetClientCountByGroup; use Xielei\Swoole\Cmd\GetClientInfo; use Xielei\Swoole\Cmd\GetClientList; use Xielei\Swoole\Cmd\GetClientListByGroup; use Xielei\Swoole\Cmd\GetClientListByUid; use Xielei\Swoole\Cmd\GetGroupList; use Xielei\Swoole\Cmd\GetSession; use Xielei\Swoole\Cmd\GetUidCount; use Xielei\Swoole\Cmd\GetUidList; use Xielei\Swoole\Cmd\GetUidListByGroup; use Xielei\Swoole\Cmd\IsOnline; use Xielei\Swoole\Cmd\JoinGroup; use Xielei\Swoole\Cmd\LeaveGroup; use Xielei\Swoole\Cmd\SendToAll; use Xielei\Swoole\Cmd\SendToClient; use Xielei\Swoole\Cmd\SendToGroup; use Xielei\Swoole\Cmd\SetSession; use Xielei\Swoole\Cmd\UnBindUid; use Xielei\Swoole\Cmd\UnGroup; use Xielei\Swoole\Cmd\UpdateSession; class HttpApi { private $register_host = '127.0.0.1'; private $register_port = 9327; private $register_secret_key = ''; public function __construct(string $register_host = '127.0.0.1', int $register_port = 9327, string $register_secret_key = '') { $this->register_host = $register_host; $this->register_port = $register_port; $this->register_secret_key = $register_secret_key; } /** * 给客户端发消息 * * @param string $client 客户端 * @param string $message 消息内容 * @return void */ public function sendToClient(string $client, string $message) { $address = $this->clientToAddress($client); $this->sendToAddress($address, SendToClient::encode($address['fd'], $message)); } /** * 给绑定了指定uid的客户端发消息 * * @param string $uid uid * @param string $message 消息内容 * @param array $without_client_list 要排除的客户端列表 * @return void */ public function sendToUid(string $uid, string $message, array $without_client_list = []) { foreach ($this->getClientListByUid($uid) as $client) { if (!in_array($client, $without_client_list)) { $this->sendToClient($client, $message); } } } /** * 给指定分组下的所有客户端发消息 * * @param string $group 组名称 * @param string $message 消息内容 * @param array $without_client_list 要排除的客户端 * @return void */ public function sendToGroup(string $group, string $message, array $without_client_list = []) { foreach ($this->getAddressList() as $address) { $this->sendToAddress($address, SendToGroup::encode($group, $message, (function () use ($address, $without_client_list): array { $res = []; foreach ($without_client_list as $client) { $tmp = $this->clientToAddress($client); if ($tmp['lan_host'] == $address['lan_host'] && $tmp['lan_port'] == $address['lan_port']) { $res[] = $tmp['fd']; } } return $res; })())); } } /** * 给所有客户端发消息 * * @param string $message 发送的内容 * @param array $without_client_list 要排除的客户端 * @return void */ public function sendToAll(string $message, array $without_client_list = []) { foreach ($this->getAddressList() as $address) { $this->sendToAddress($address, SendToAll::encode($message, (function () use ($address, $without_client_list): array { $res = []; foreach ($without_client_list as $client) { $tmp = $this->clientToAddress($client); if ($tmp['lan_host'] == $address['lan_host'] && $tmp['lan_port'] == $address['lan_port']) { $res[] = $tmp['fd']; } } return $res; })())); } } /** * 判断指定客户端是否在线 * * @param string $client * @return boolean */ public function isOnline(string $client): bool { $address = $this->clientToAddress($client); return isOnline::result($this->sendToAddressAndRecv($address, IsOnline::encode($address['fd']))); } /** * 判断指定uid是否在线 * * @param string $uid * @return boolean */ public function isUidOnline(string $uid): bool { foreach ($this->getClientListByUid($uid) as $value) { return true; } return false; } /** * 获取指定分组下的客户列表 * * @param string $group 分组名称 * @param string $prev_client 从该客户端开始读取 * @return iterable */ public function getClientListByGroup(string $group, string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = $this->clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } $buffer = GetClientListByGroup::encode($group); foreach ($this->getAddressList() as $address) { if ($start || $address == $prev_address) { $res = $this->sendToAddressAndRecv($address, $buffer); foreach (unpack('N*', $res) as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield $this->addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $start = true; } } } /** * 获取所有客户端数量 * * @return integer */ public function getClientCount(): int { $items = []; $buffer = GetClientCount::encode(); foreach ($this->getAddressList() as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = $this->sendToAddressListAndRecv($items); $count = 0; foreach ($buffers as $key => $buffer) { $data = unpack('Nnum', $buffer); $count += $data['num']; } return $count; } /** * 获取指定分组下的客户端数量 * * @param string $group * @return integer */ public function getClientCountByGroup(string $group): int { $items = []; $buffer = GetClientCountByGroup::encode($group); foreach ($this->getAddressList() as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = $this->sendToAddressListAndRecv($items); $count = 0; foreach ($buffers as $key => $buffer) { $data = unpack('Ncount', $buffer); $count += $data['count']; } return $count; } /** * 获取客户端列表 * * @param string $prev_client 从该客户端开始读取 * @return iterable */ public function getClientList(string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = $this->clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } foreach ($this->getAddressList() as $address) { if ($start || $address == $prev_address) { $tmp_prev_fd = 0; while ($fd_list = unpack('N*', $this->sendToAddressAndRecv($address, GetClientList::encode(10000, $tmp_prev_fd)))) { foreach ($fd_list as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield $this->addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $tmp_prev_fd = $fd; } $start = true; } } } /** * 获取某个uid下绑定的客户端列表 * * @param string $uid * @param string $prev_client 从该客户但开始读取 * @return iterable */ public function getClientListByUid(string $uid, string $prev_client = null): iterable { $start = $prev_client ? false : true; if (!$start) { $tmp = $this->clientToAddress($prev_client); $prev_address = [ 'lan_host' => $tmp['lan_host'], 'lan_port' => $tmp['lan_port'], ]; $prev_fd = $tmp['fd']; } $buffer = GetClientListByUid::encode($uid); foreach ($this->getAddressList() as $address) { if ($start || $address == $prev_address) { $res = $this->sendToAddressAndRecv($address, $buffer); foreach (unpack('N*', $res) as $fd) { if ($start || $fd > $prev_fd) { $start = true; yield $this->addressToClient([ 'lan_host' => $address['lan_host'], 'lan_port' => $address['lan_port'], 'fd' => $fd, ]); } } $start = true; } } } /** * 获取客户信息 * * @param string $client 客户端 * @param integer $type 具体要获取哪些数据,默认全部获取,也可按需获取,可选参数:Xielei\Swoole\Protocol::CLIENT_INFO_UID(绑定的uid) | Xielei\Swoole\Protocol::CLIENT_INFO_SESSION(session) | Xielei\Swoole\Protocol::CLIENT_INFO_GROUP_LIST(绑定的分组列表) | Xielei\Swoole\Protocol::CLIENT_INFO_REMOTE_IP(客户ip) | Xielei\Swoole\Protocol::CLIENT_INFO_REMOTE_PORT(客户端口) | Xielei\Swoole\Protocol::CLIENT_INFO_SYSTEM(客户系统信息) * @return array|null */ public function getClientInfo(string $client, int $type = 255): ?array { $address = $this->clientToAddress($client); return GetClientInfo::result($this->sendToAddressAndRecv($address, GetClientInfo::encode($address['fd'], $type))); } /** * 获取指定分组下客户绑定的uid列表 * * @param string $group 分组名称 * @param boolean $unique 是否过滤重复值 默认过滤,若用户数过多,会占用较大内存,建议根据需要设置 * @return iterable */ public function getUidListByGroup(string $group, bool $unique = true): iterable { $uid_list = []; $buffer = GetUidListByGroup::encode($group); foreach ($this->getAddressList() as $address) { $res = $this->sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $uid = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($uid_list[$uid])) { $uid_list[$uid] = $uid; yield $uid; } } else { yield $uid; } $res = substr($res, 1 + $tmp['len']); } } unset($uid_list); } /** * 获取所有uid列表 * * @param boolean $unique 是否过滤重复值 默认过滤,若用户数过多,会占用较大内存,建议根据需要设置 * @return iterable */ public function getUidList(bool $unique = true): iterable { $uid_list = []; $buffer = GetUidList::encode(); foreach ($this->getAddressList() as $address) { $res = $this->sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $uid = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($uid_list[$uid])) { $uid_list[$uid] = $uid; yield $uid; } } else { yield $uid; } $res = substr($res, 1 + $tmp['len']); } } unset($uid_list); } /** * 获取绑定的uid总数(该数据只是一个近似值),一个uid可能被多个gateway下的客户端绑定,考虑性能原因,并不计算精确值,在不传百分比的情况下,系统会自动计算一个近似百分比,通过该百分比计算出近似的总uid数 * * @param float $unique_percent 唯一百分比,例如:80%。若知道的情况下请尽量填写,这样数据更加准确。 * @return integer */ public function getUidCount(float $unique_percent = null): int { $items = []; $buffer = GetUidCount::encode($unique_percent ? false : true); foreach ($this->getAddressList() as $key => $address) { $items[$key] = [ 'address' => $address, 'buffer' => $buffer, ]; } $buffers = $this->sendToAddressListAndRecv($items); $count = 0; $uid_list = []; foreach ($buffers as $key => $buffer) { if ($buffer) { $data = unpack('Nnum', $buffer); $count += $data['num']; $res = substr($buffer, 8); while ($res) { $tmp = unpack('Clen', $res); $uid_list[] = substr($res, 1, $tmp['len']); $res = substr($res, 1 + $tmp['len']); } } } if ($unique_percent) { return intval($count * $unique_percent); } else { if ($uid_list) { return intval($count * count(array_unique($uid_list)) / count($uid_list)); } else { return $count; } } } /** * 获取分组列表 * * @param boolean $unique 是否去除重复数据,默认去除,若分组数据较多(例如百万级别),会占用很大的内存,若能够在业务上处理,请尽量设置为false * @return iterable */ public function getGroupList(bool $unique = true): iterable { $group_list = []; $buffer = GetGroupList::encode(); foreach ($this->getAddressList() as $key => $address) { $res = $this->sendToAddressAndRecv($address, $buffer); while ($res) { $tmp = unpack('Clen', $res); $group = substr($res, 1, $tmp['len']); if ($unique) { if (!isset($group_list[$group])) { $group_list[$group] = $group; yield $group; } } else { yield $group; } $res = substr($res, 1 + $tmp['len']); } } unset($group_list); } /** * 获取指定分组下的用户数 * * @param string $group 分组名称 * @return integer */ public function getUidCountByGroup(string $group): int { return count(iterator_to_array($this->getUidListByGroup($group))); } /** * 关闭客户端 * * @param string $client 客户端 * @param boolean $force 是否强制关闭,强制关闭会立即关闭客户端,不会等到待发送数据发送完毕就立即关闭 * @return void */ public function closeClient(string $client, bool $force = false) { $address = $this->clientToAddress($client); $this->sendToAddress($address, CloseClient::encode($address['fd'], $force)); } /** * 绑定uid 一个客户端只能绑定一个uid,多次绑定只以最后一个为准,客户端下线会自动解绑,无需手动解绑 * * @param string $client * @param string $uid * @return void */ public function bindUid(string $client, string $uid) { $address = $this->clientToAddress($client); $this->sendToAddress($address, BindUid::encode($address['fd'], $uid)); } /** * 取消绑定uid * * @param string $client * @return void */ public function unBindUid(string $client) { $address = $this->clientToAddress($client); $this->sendToAddress($address, UnBindUid::encode($address['fd'])); } /** * 客户端加入到指定分组 客户断开会自动从加入的分组移除,无需手动处理 * * @param string $client 客户端 * @param string $group 分组名称 * @return void */ public function joinGroup(string $client, string $group) { $address = $this->clientToAddress($client); $this->sendToAddress($address, JoinGroup::encode($address['fd'], $group)); } /** * 将客户端从指定分组移除 * * @param string $client 客户端 * @param string $group 指定分组 * @return void */ public function leaveGroup(string $client, string $group) { $address = $this->clientToAddress($client); $this->sendToAddress($address, LeaveGroup::encode($address['fd'], $group)); } /** * 解散分组 * * @param string $group 分组名称 * @return void */ public function unGroup(string $group) { $buffer = UnGroup::encode($group); foreach ($this->getAddressList() as $address) { $this->sendToAddress($address, $buffer); } } /** * 设置session 直接替换session * * @param string $client 客户端 * @param array $session session数据 * @return void */ public function setSession(string $client, array $session) { $address = $this->clientToAddress($client); $this->sendToAddress($address, SetSession::encode($address['fd'], $session)); } /** * 更新指定客户端session 区别于设置session,设置是直接替换,更新会合并旧数据 * * @param string $client * @param array $session * @return void */ public function updateSession(string $client, array $session) { $address = $this->clientToAddress($client); $this->sendToAddress($address, UpdateSession::encode($address['fd'], $session)); } /** * 删除指定客户端的session * * @param string $client * @return void */ public function deleteSession(string $client) { $address = $this->clientToAddress($client); $this->sendToAddress($address, DeleteSession::encode($address['fd'])); } /** * 获取指定客户端session * * @param string $client * @return array|null */ public function getSession(string $client): ?array { $address = $this->clientToAddress($client); $buffer = $this->sendToAddressAndRecv($address, GetSession::encode($address['fd'])); return unserialize($buffer); } /** * 根据地址生成客户端编号 * * @param array $address * @return string */ public function addressToClient(array $address): string { return bin2hex(pack('NnN', ip2long($address['lan_host']), $address['lan_port'], $address['fd'])); } /** * 根据客户端编号获取客户端通信地址 * * @param string $client * @return array */ public function clientToAddress(string $client): array { $res = unpack('Nlan_host/nlan_port/Nfd', hex2bin($client)); $res['lan_host'] = long2ip($res['lan_host']); return $res; } /** * 获取网关地址列表 * * @return array */ public function getAddressList(): array { static $last_time = 0; static $addresses = []; $now_time = time(); if ($now_time - $last_time > 1) { $last_time = $now_time; $client = stream_socket_client('tcp://' . $this->register_host . ':' . $this->register_port, $errno, $errmsg, 5, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT); fwrite($client, Protocol::encode(pack('C', Protocol::WORKER_CONNECT) . $this->register_secret_key)); stream_set_timeout($client, 5); $data = unpack('Ccmd/A*load', Protocol::decode(stream_socket_recvfrom($client, 655350))); if ($data['cmd'] !== Protocol::BROADCAST_GATEWAY_LIST) { throw new Exception("get gateway address list failure!"); } else { $addresses = []; if ($data['load'] && (strlen($data['load']) % 6 === 0)) { foreach (str_split($data['load'], 6) as $value) { $address = unpack('Nlan_host/nlan_port', $value); $address['lan_host'] = long2ip($address['lan_host']); $addresses[$address['lan_host'] . ':' . $address['lan_port']] = $address; } } } } return $addresses; } /** * 向多个地址发送数据并批量接收 * * @param array $items * @param float $timeout 超时时间 单位秒 * @return array */ public function sendToAddressListAndRecv(array $items, float $timeout = 1): array { $res = []; foreach ($items as $key => $item) { $res[$key] = $this->sendToAddressAndRecv($item['address'], $item['buffer'], $timeout); } return $res; } /** * 向指定地址发送数据后返回数据 * * @param array $address 指定地址 * @param string $buffer 发送的数据 * @param float $timeout 超时时间 单位秒 * @return string */ public function sendToAddressAndRecv(array $address, string $buffer, float $timeout = 1): string { $buffer = Protocol::encode($buffer); static $clients = []; $client_key = $address['lan_host'] . ':' . $address['lan_port']; if (!isset($clients[$client_key])) { $client = stream_socket_client("tcp://{$client_key}", $errno, $errmsg, $timeout, STREAM_CLIENT_PERSISTENT | STREAM_CLIENT_CONNECT); if (!$client) { throw new Exception("connect to tcp://{$client_key} failure! errmsg:{$errmsg}"); } $clients[$client_key] = $client; } if (strlen($buffer) !== stream_socket_sendto($clients[$client_key], $buffer)) { throw new Exception("send to tcp://{$client_key} failure!"); } stream_set_blocking($clients[$client_key], true); stream_set_timeout($clients[$client_key], 1); $recv_buf = ''; $time_start = microtime(true); $pack_len = 0; while (true) { $buf = stream_socket_recvfrom($clients[$client_key], 655350); if ($buf !== '' && $buf !== false) { $recv_buf .= $buf; } else { if (feof($clients[$client_key])) { throw new Exception("connection closed! tcp://$address"); } elseif (microtime(true) - $time_start > $timeout) { break; } continue; } $recv_len = strlen($recv_buf); if (!$pack_len && $recv_len >= 4) { $pack_len = current(unpack('N', $recv_buf)); } if (($pack_len && $recv_len >= $pack_len) || microtime(true) - $time_start > $timeout) { break; } } return Protocol::decode(substr($recv_buf, 0, $pack_len)); } /** * 向指定地址发送数据 * * @param array $address 指定地址 * @param string $buffer 数据 * @return void */ public function sendToAddress(array $address, string $buffer) { static $clients = []; $client_key = $address['lan_host'] . ':' . $address['lan_port']; if (!isset($clients[$client_key])) { $client = stream_socket_client("tcp://{$client_key}", $errno, $errmsg, 5, STREAM_CLIENT_PERSISTENT | STREAM_CLIENT_CONNECT); if (!$client) { throw new Exception("connect to tcp://{$client_key} failure! errmsg:{$errmsg}"); } $clients[$client_key] = $client; } $buffer = Protocol::encode($buffer); stream_socket_sendto($clients[$client_key], $buffer); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Interfaces/WorkerEventInterface.php
src/Interfaces/WorkerEventInterface.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Interfaces; use Swoole\Server\PipeMessage; use Swoole\Server\TaskResult; interface WorkerEventInterface { /** * worker start * * @return void */ public function onWorkerStart(); /** * worker stop * * @return void */ public function onWorkerStop(); /** * worker exit * * @return void */ public function onWorkerExit(); /** * pipe message * * @param PipeMessage $pipeMessage * @return void */ public function onPipeMessage(PipeMessage $pipeMessage); /** * task finish * * @param TaskResult $taskResult * @return void */ public function onFinish(TaskResult $taskResult); /** * tcp connect * * @param string $client * @param array $session * @return void */ public function onConnect(string $client, array $session); /** * tcp receive * * @param string $client * @param array $session * @param string $data * @return void */ public function onReceive(string $client, array $session, string $data); /** * websocket open * * @param string $client * @param array $session * @param array $request * @return void */ public function onOpen(string $client, array $session, array $request); /** * websocket message * * @param string $client * @param array $session * @param array $frame * @return void */ public function onMessage(string $client, array $session, array $frame); /** * tcp close * * @param string $client * @param array $session * @param array $bind * @return void */ public function onClose(string $client, array $session, array $bind); }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Interfaces/TaskEventInterface.php
src/Interfaces/TaskEventInterface.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Interfaces; use Swoole\Server\PipeMessage; use Swoole\Server\Task; interface TaskEventInterface { /** * worker start * * @return void */ public function onWorkerStart(); /** * worker stop * * @return void */ public function onWorkerStop(); /** * worker exit * * @return void */ public function onWorkerExit(); /** * pipe message * * @param PipeMessage $pipeMessage * @return void */ public function onPipeMessage(PipeMessage $pipeMessage); /** * task * * @param Task $task * @return void */ public function onTask(Task $task); }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Interfaces/CmdInterface.php
src/Interfaces/CmdInterface.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Interfaces; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Gateway; interface CmdInterface { /** * get command code * * @return integer */ public static function getCommandCode(): int; /** * execute command * * @param Gateway $gateway * @param Connection $connection * @param string $buffer * @return void */ public static function execute(Gateway $gateway, Connection $connection, string $buffer); }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/RegisterWorker.php
src/Cmd/RegisterWorker.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\ConnectionPool; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class RegisterWorker implements CmdInterface { public static function getCommandCode(): int { return 19; } public static function encode(array $tag_list = []): string { return pack('C', self::getCommandCode()) . json_encode(array_values($tag_list)); } public static function decode(string $buffer): array { return [ 'tag_list' => json_decode($buffer, true), ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $res = self::decode($buffer); $address = implode(':', $conn->exportSocket()->getpeername()); if (isset($gateway->worker_list[$address])) { $gateway->worker_list[$address]['tag_list'] = $res['tag_list']; } else { $gateway->worker_list[$address] = [ 'tag_list' => $res['tag_list'], 'pool' => new ConnectionPool(function () use ($conn) { return $conn; }, 1), ]; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/JoinGroup.php
src/Cmd/JoinGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class JoinGroup implements CmdInterface { public static function getCommandCode(): int { return 17; } public static function encode(int $fd, string $group): string { return pack('CN', self::getCommandCode(), $fd) . $group; } public static function decode(string $buffer): array { $res = unpack('Nfd', $buffer); $res['group'] = substr($buffer, 4); return $res; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { if (!isset($gateway->group_list[$data['group']])) { $gateway->group_list[$data['group']] = []; } $gateway->group_list[$data['group']][$data['fd']] = $data['fd']; $gateway->fd_list[$data['fd']]['group_list'][$data['group']] = $data['group']; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/SendToAll.php
src/Cmd/SendToAll.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class SendToAll implements CmdInterface { public static function getCommandCode(): int { return 20; } public static function encode(string $message, array $without_fd_list = []): string { return pack('Cn', self::getCommandCode(), count($without_fd_list)) . ($without_fd_list ? pack('N*', ...$without_fd_list) : '') . $message; } public static function decode(string $buffer): array { $tmp = unpack('ncount', $buffer); return [ 'without_fd_list' => unpack('N*', substr($buffer, 2, $tmp['count'] * 4)), 'message' => substr($buffer, 2 + $tmp['count'] * 4), ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); foreach ($gateway->fd_list as $fd => $info) { if (!in_array($fd, $data['without_fd_list'])) { $gateway->sendToClient($fd, $data['message']); } } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/SendToClient.php
src/Cmd/SendToClient.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class SendToClient implements CmdInterface { public static function getCommandCode(): int { return 21; } public static function encode(int $fd, string $message): string { return pack('CN', self::getCommandCode(), $fd) . $message; } public static function decode(string $buffer): array { $res = unpack('Nfd', $buffer); $res['message'] = substr($buffer, 4); return $res; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $gateway->sendToClient($data['fd'], $data['message']); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/UnBindUid.php
src/Cmd/UnBindUid.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class UnBindUid implements CmdInterface { public static function getCommandCode(): int { return 24; } public static function encode(int $fd): string { return pack('CN', self::getCommandCode(), $fd); } public static function decode(string $buffer): array { return unpack('Nfd', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { if ($bind_uid = $gateway->fd_list[$data['fd']]['uid']) { unset($gateway->uid_list[$bind_uid][$data['fd']]); if (isset($gateway->uid_list[$bind_uid]) && !$gateway->uid_list[$bind_uid]) { unset($gateway->uid_list[$bind_uid]); } } $gateway->fd_list[$data['fd']]['uid'] = ''; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientList.php
src/Cmd/GetClientList.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientList implements CmdInterface { public static function getCommandCode(): int { return 8; } public static function encode(int $limit = 100, int $prev_fd = 0): string { return pack('CNN', self::getCommandCode(), $limit, $prev_fd); } public static function decode(string $buffer): array { return unpack('Nlimit/Nprev_fd', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (!$fd_list = $gateway->getServer()->getClientList($data['prev_fd'], $data['limit'])) { $fd_list = []; } $conn->send(Protocol::encode(pack('N*', ...array_values($fd_list)))); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientCount.php
src/Cmd/GetClientCount.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientCount implements CmdInterface { public static function getCommandCode(): int { return 4; } public static function encode(): string { return pack('C', self::getCommandCode()); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $count = $gateway->getServer()->stats()['connection_num']; $conn->send(Protocol::encode(pack('N', $count))); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/UnGroup.php
src/Cmd/UnGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class UnGroup implements CmdInterface { public static function getCommandCode(): int { return 25; } public static function encode(string $group): string { return pack('C', self::getCommandCode()) . $group; } public static function decode(string $buffer): array { return [ 'group' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->group_list[$data['group']])) { foreach ($gateway->group_list[$data['group']] as $fd) { unset($gateway->fd_list[$fd]['group_list'][$data['group']]); } unset($gateway->group_list[$data['group']]); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetUidList.php
src/Cmd/GetUidList.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetUidList implements CmdInterface { public static function getCommandCode(): int { return 14; } public static function encode(): string { return pack('C', self::getCommandCode()); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $buffer = ''; foreach ($gateway->uid_list as $uid => $fd_list) { $buffer .= pack('C', strlen((string) $uid)) . $uid; } $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientInfo.php
src/Cmd/GetClientInfo.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientInfo implements CmdInterface { public static function getCommandCode(): int { return 7; } public static function encode(int $fd = 0, int $type = 0): string { return pack('CNC', self::getCommandCode(), $fd, $type); } public static function decode(string $buffer): array { return unpack('Nfd/Ctype', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { $load = self::encodeClientBuffer($gateway, $data['fd'], $data['type']); } else { $load = ''; } $conn->send(Protocol::encode(pack('C', $data['type']) . $load)); } public static function result(string $buffer): ?array { $data = unpack('Ctype', $buffer); $load = substr($buffer, 1); if ($load) { return self::decodeClientBuffer($load, $data['type']); } else { return null; } } public static function encodeClientBuffer(Gateway $gateway, int $fd, int $type): string { $load = ''; if (Protocol::CLIENT_INFO_UID & $type) { $uid = $gateway->fd_list[$fd]['uid']; $load .= pack('n', strlen((string) $uid)) . $uid; } if (Protocol::CLIENT_INFO_SESSION & $type) { $session = serialize($gateway->fd_list[$fd]['session']); $load .= pack('N', strlen($session)) . $session; } if (Protocol::CLIENT_INFO_GROUP_LIST & $type) { $load .= pack('n', count($gateway->fd_list[$fd]['group_list'])); foreach ($gateway->fd_list[$fd]['group_list'] as $value) { $load .= pack('n', strlen((string) $value)) . $value; } } if (Protocol::CLIENT_INFO_REMOTE_IP & $type) { $load .= pack('N', ip2long($gateway->getServer()->getClientInfo($fd)['remote_ip'])); } if (Protocol::CLIENT_INFO_REMOTE_PORT & $type) { $load .= pack('n', $gateway->getServer()->getClientInfo($fd)['remote_port']); } if (Protocol::CLIENT_INFO_SYSTEM & $type) { $info = serialize($gateway->getServer()->getClientInfo($fd)); $load .= pack('N', strlen($info)) . $info; } return $load; } public static function decodeClientBuffer(string &$buffer, int $type): array { $res = []; if ($type & Protocol::CLIENT_INFO_UID) { $t = unpack('nlen', $buffer); $buffer = substr($buffer, 2); $res['uid'] = substr($buffer, 0, $t['len']); $buffer = substr($buffer, $t['len']); } if ($type & Protocol::CLIENT_INFO_SESSION) { $t = unpack('Nlen', $buffer); $buffer = substr($buffer, 4); $res['session'] = unserialize(substr($buffer, 0, $t['len'])); $buffer = substr($buffer, $t['len']); } if ($type & Protocol::CLIENT_INFO_GROUP_LIST) { $t = unpack('ncount', $buffer); $buffer = substr($buffer, 2); $group_list = []; for ($i = 0; $i < $t['count']; $i++) { $q = unpack('nlen', $buffer); $buffer = substr($buffer, 2); $group_list[] = substr($buffer, 0, $q['len']); $buffer = substr($buffer, $q['len']); } $res['group_list'] = $group_list; } if ($type & Protocol::CLIENT_INFO_REMOTE_IP) { $res += unpack('Nremote_ip', $buffer); $res['remote_ip'] = long2ip($res['remote_ip']); $buffer = substr($buffer, 4); } if ($type & Protocol::CLIENT_INFO_REMOTE_PORT) { $res += unpack('nremote_port', $buffer); $buffer = substr($buffer, 2); } if ($type & Protocol::CLIENT_INFO_SYSTEM) { $t = unpack('Nlen', $buffer); $res['system'] = unserialize(substr($buffer, 4, $t['len'])); $buffer = substr($buffer, 4 + $t['len']); } return $res; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientListByGroup.php
src/Cmd/GetClientListByGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientListByGroup implements CmdInterface { public static function getCommandCode(): int { return 9; } public static function encode(string $group): string { return pack('C', self::getCommandCode()) . $group; } public static function decode(string $buffer): array { return [ 'group' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $fd_list = $gateway->group_list[$data['group']] ?? []; $conn->send(Protocol::encode(pack('N*', ...$fd_list))); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/IsOnline.php
src/Cmd/IsOnline.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class IsOnline implements CmdInterface { public static function getCommandCode(): int { return 16; } public static function encode(int $fd): string { return pack('CN', self::getCommandCode(), $fd); } public static function decode(string $buffer): array { return unpack('Nfd', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $is_online = $gateway->getServer()->exist($data['fd']); $buffer = pack('C', $is_online); $conn->send(Protocol::encode($buffer)); } public static function result(string $buffer): bool { return unpack('Cis_online', $buffer)['is_online'] ? true : false; } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetUidCount.php
src/Cmd/GetUidCount.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetUidCount implements CmdInterface { public static function getCommandCode(): int { return 13; } public static function encode(bool $read_uid_list = true): string { return pack('CC', self::getCommandCode(), $read_uid_list); } public static function decode($buffer) { return unpack('Cread_uid_list', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $param = self::decode($buffer); $count = count($gateway->uid_list); if ($param['read_uid_list']) { if ($count > 100) { $uid_list = array_slice($gateway->uid_list, random_int(0, $count - 100), 100); } else { $uid_list = $gateway->uid_list; } } else { $uid_list = []; } $buffer = ''; foreach (array_keys($uid_list) as $uid) { $buffer .= pack('C', strlen((string) $uid)) . $uid; } $conn->send(Protocol::encode(pack('N', $count) . $buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/DeleteSession.php
src/Cmd/DeleteSession.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class DeleteSession implements CmdInterface { public static function getCommandCode(): int { return 3; } public static function encode(int $fd): string { return pack('CN', self::getCommandCode(), $fd); } public static function decode(string $buffer): array { return unpack('Nfd', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { $gateway->fd_list[$data['fd']]['session'] = []; } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientCountByGroup.php
src/Cmd/GetClientCountByGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientCountByGroup implements CmdInterface { public static function getCommandCode(): int { return 5; } public static function encode(string $group): string { return pack('C', self::getCommandCode()) . $group; } public static function decode(string $buffer): array { return [ 'group' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $buffer = pack('N', count($gateway->group_list[$data['group']] ?? [])); $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetClientListByUid.php
src/Cmd/GetClientListByUid.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetClientListByUid implements CmdInterface { public static function getCommandCode(): int { return 10; } public static function encode(string $uid): string { return pack('C', self::getCommandCode()) . $uid; } public static function decode(string $buffer): array { return [ 'uid' => $buffer, ]; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $fd_list = $gateway->uid_list[$data['uid']] ?? []; $conn->send(Protocol::encode(pack('N*', ...$fd_list))); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/CloseClient.php
src/Cmd/CloseClient.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class CloseClient implements CmdInterface { public static function getCommandCode(): int { return 2; } public static function encode(int $fd, bool $force = false): string { return pack('CNC', self::getCommandCode(), $fd, $force); } public static function decode(string $buffer): array { return unpack('Nfd/Cforce', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if ($gateway->getServer()->exist($data['fd'])) { $gateway->getServer()->close($data['fd'], (bool)$data['force']); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/Ping.php
src/Cmd/Ping.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class Ping implements CmdInterface { public static function getCommandCode(): int { return 0; } public static function encode(): string { return pack('C', self::getCommandCode()); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetGroupList.php
src/Cmd/GetGroupList.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetGroupList implements CmdInterface { public static function getCommandCode(): int { return 11; } public static function encode(): string { return pack('C', self::getCommandCode()); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $buffer = ''; foreach (array_keys($gateway->group_list) as $group) { $buffer .= pack('C', strlen((string)$group)) . $group; } $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/GetSession.php
src/Cmd/GetSession.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; use Xielei\Swoole\Protocol; class GetSession implements CmdInterface { public static function getCommandCode(): int { return 12; } public static function encode(int $fd): string { return pack('CN', self::getCommandCode(), $fd); } public static function decode(string $buffer): array { return unpack('Nfd', $buffer); } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); $buffer = serialize($gateway->fd_list[$data['fd']]['session'] ?? null); $conn->send(Protocol::encode($buffer)); } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false
xielei/swoole-worker
https://github.com/xielei/swoole-worker/blob/f7a5b731d86f62c9040056f08a3a513fd3f90e28/src/Cmd/LeaveGroup.php
src/Cmd/LeaveGroup.php
<?php declare(strict_types=1); namespace Xielei\Swoole\Cmd; use Swoole\Coroutine\Server\Connection; use Xielei\Swoole\Interfaces\CmdInterface; use Xielei\Swoole\Gateway; class LeaveGroup implements CmdInterface { public static function getCommandCode(): int { return 18; } public static function encode(int $fd, string $group): string { return pack('CN', self::getCommandCode(), $fd) . $group; } public static function decode(string $buffer): array { $res = unpack('Nfd', $buffer); $res['group'] = substr($buffer, 4); return $res; } public static function execute(Gateway $gateway, Connection $conn, string $buffer) { $data = self::decode($buffer); if (isset($gateway->fd_list[$data['fd']])) { unset($gateway->group_list[$data['group']][$data['fd']]); if (isset($gateway->group_list[$data['group']]) && !$gateway->group_list[$data['group']]) { unset($gateway->group_list[$data['group']]); } unset($gateway->fd_list[$data['fd']]['group_list'][$data['group']]); } } }
php
Apache-2.0
f7a5b731d86f62c9040056f08a3a513fd3f90e28
2026-01-05T04:57:25.551053Z
false