diff --git a/.gitignore b/.gitignore index 915ed72..b47acaa 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ vendor composer.lock composer.phar .phpunit.result.cache +.php-cs-fixer.cache diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..7be6873 --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,104 @@ + true, // Enforce PER 2.0 + 'array_indentation' => true, // Indent arrays by one + 'array_syntax' => true, // Replace array() with [] + 'binary_operator_spaces' => [ + 'default' => 'single_space', // Use single space around operators + 'operators' => [ + '=>' => 'align_single_space_minimal', // Align => inside array + ], + ], + 'cast_spaces' => [ + 'space' => 'none', // Remove spaces between cast and value + ], + 'combine_consecutive_issets' => true, // Combine isset() into one call + 'dir_constant' => true, // Replace dirname(__FILE__) with __DIR__ + 'echo_tag_syntax' => ['format' => 'short'], // Replace true, // Convert vars in strings from "$foo" to "{$foo}" + 'function_declaration' => [ + 'closure_function_spacing' => 'none', // No space between function keyword and parameter list + 'closure_fn_spacing' => 'none', // No space between fn keyword and parameter list + ], + 'heredoc_indentation' => true, // Indent heredocs by one + 'include' => true, // Use single space after include/require, remove brackets + 'is_null' => true, // Replace is_null() with $foo === null + 'list_syntax' => true, // Replace list() with [] + 'magic_constant_casing' => true, // Use uppercase for magic constants + 'magic_method_casing' => true, // Use camelCase for magic methods + 'method_chaining_indentation' => true, // Indent method chains by one + 'method_argument_space' => [ + 'on_multiline' => 'ignore', // Do not force all function arguments to be on separate lines + ], + 'multiline_whitespace_before_semicolons' => true, // Place semicolon on same line as last chained method + 'native_function_casing' => true, // Use lowercase for native functions + 'native_type_declaration_casing' => true, // Use lowercase for native type hints + 'new_with_parentheses' => false, // Do not enforce empty parentheses for constructors + 'no_blank_lines_after_phpdoc' => true, // Remove whitespace between docblock and element + 'no_empty_statement' => true, // Remove useless statements/semicolons + 'no_singleline_whitespace_before_semicolons' => true, // Remove whitespace between statement and semicolon + 'no_spaces_around_offset' => true, // Remove spaces around array offset + 'no_trailing_comma_in_singleline' => [ + 'elements' => ['arguments', 'array', 'group_import'] // Remove trailing commas in singleline arrays, function calls, and group imports + ], + 'no_unneeded_control_parentheses' => [ + 'statements' => ['return'], // Remove parentheses around return statements + ], + 'no_unused_imports' => true, // Remove unused imports + 'no_useless_return' => true, // Remove empty return at end of function + 'no_whitespace_before_comma_in_array' => true, // Remove whitespace before commas in arrays + 'not_operator_with_successor_space' => false, // Remove space around NOT operator + 'nullable_type_declaration_for_default_null_value' => true, // Add ? before typehint for nullable default values + 'operator_linebreak' => true, // Place multiline operators at the start of a line + 'ordered_imports' => [ + 'sort_algorithm' => 'alpha', // Sort imports alphabetically + ], + 'phpdoc_indent' => true, // Align PHPDoc with element + 'php_unit_construct' => true, // Replace assertEquals(true, $foo) with assertTrue($foo) + 'semicolon_after_instruction' => false, // Use semicolon after instruction (disabled to avoid true, // Convert vars in strings from ${foo} to {$foo} + 'simplified_if_return' => true, // Simplify return inside if statement to boolean type cast + 'single_line_comment_style' => [ + 'comment_types' => ['hash'], // Use // for # comments + ], + 'single_space_around_construct' => true, // Use single space around constructs + 'standardize_not_equals' => true, // Replace <> with != + 'ternary_to_null_coalescing' => true, // Replace isset($foo) ? $foo : $bar with $foo ?? $bar + 'trailing_comma_in_multiline' => true, // Use trailing comma in multiline arrays + 'trim_array_spaces' => true, // Remove leading/trailing spaces in arrays + 'type_declaration_spaces' => true, // Use single space between typehints and fn argument/object property name + 'visibility_required' => [ + 'elements' => ['property', 'method'], // Require visibility to be declared on properties and methods + ], + 'whitespace_after_comma_in_array' => true, // Use whitespace after every comma in arrays + 'yoda_style' => [ // Enforces non-yoda style + 'equal' => false, + 'identical' => false, + 'less_and_greater' => false, + ], +]; + +$excludes = [ + 'vendor', + 'node_modules', +]; + +return (new PhpCsFixer\Config()) + ->setRiskyAllowed(true) + ->setRules($rules) + ->setFinder( + PhpCsFixer\Finder::create() + ->exclude($excludes) + ->notName('*.js') + ->notName('*.css') + ->notName('*.md') + ->notName('*.xml') + ->notName('*.yml') + ->notName('*.tpl.php') + ); diff --git a/.php_cs b/.php_cs deleted file mode 100644 index cc92932..0000000 --- a/.php_cs +++ /dev/null @@ -1,82 +0,0 @@ -in(__DIR__ . '/src') - ->in(__DIR__ . '/tests') -; - -return Symfony\CS\Config\Config::create() - ->fixers([ - 'psr0', - 'encoding', - 'short_tag', - 'braces', - 'elseif', - 'eof_ending', - 'function_call_space', - 'function_declaration', - 'indentation', - 'line_after_namespace', - 'linefeed', - 'lowercase_constants', - 'lowercase_keywords', - 'method_argument_space', - 'multiple_use', - 'parenthesis', - 'php_closing_tag', - 'single_line_after_imports', - 'trailing_spaces', - 'visibility', - 'double_arrow_multiline_whitespaces', - 'duplicate_semicolon', - 'empty_return', - 'extra_empty_lines', - 'include', - 'join_function', - 'list_commas', - 'multiline_array_trailing_comma', - 'namespace_no_leading_whitespace', - 'new_with_braces', - 'no_blank_lines_after_class_opening', - 'no_empty_lines_after_phpdocs', - 'object_operator', - 'operators_spaces', - 'phpdoc_indent', - 'phpdoc_inline_tag', - 'phpdoc_no_access', - 'phpdoc_no_empty_return', - 'phpdoc_no_package', - 'phpdoc_scalar', - 'phpdoc_to_comment', - 'phpdoc_trim', - 'phpdoc_type_to_var', - 'phpdoc_var_without_name', - 'pre_increment', - 'remove_leading_slash_use', - 'remove_lines_between_uses', - 'return', - 'self_accessor', - 'single_quote', - 'spaces_before_semicolon', - 'spaces_cast', - 'standardize_not_equal', - 'ternary_spaces', - 'trim_array_spaces', - 'unalign_double_arrow', - 'unalign_equals', - 'unary_operators_spaces', - 'unused_use', - 'whitespacy_lines', - 'concat_with_spaces', - 'ereg_to_preg', - 'newline_after_open_tag', - 'no_blank_lines_before_namespace', - 'ordered_use', - 'php4_constructor', - 'php_unit_construct', - 'phpdoc_order', - 'long_array_syntax', - 'short_echo_tag', - ]) - ->finder($finder) -; diff --git a/composer.json b/composer.json index 754b39b..dc200e5 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,6 @@ "homepage": "http://pear.php.net/user/till" }, { - "name": "Brian L. Moon", "homepage": "http://pear.php.net/user/brianlmoon" }, @@ -27,19 +26,19 @@ } ], "require": { - "php": ">=7.3.0", + "php": ">=8.0", "ext-sockets": "*", "ext-json": "*" }, "require-dev": { "phpunit/phpunit": "^9.5.18", - "friendsofphp/php-cs-fixer": "^v2.19.3", + "friendsofphp/php-cs-fixer": "^v3.59.3", "symfony/process": "^v5.0.0" }, "autoload": { "psr-4": { "Vectorface\\Gearman\\": "src/" } }, "autoload-dev": { - "psr-4": { "Vectorface\\Gearman\\tests": "tests/" } + "psr-4": { "Vectorface\\Gearman\\tests\\": "tests/" } } } diff --git a/src/Client.php b/src/Client.php index 6078ca5..84f41ba 100644 --- a/src/Client.php +++ b/src/Client.php @@ -45,39 +45,31 @@ */ class Client implements ServerSetting { - /** - * Our randomly selected connection. - * - * @var resource[] An array of open socket to Gearman - */ - protected $conn = []; + /** Our randomly selected connection to Gearman */ + protected array $conn = []; - /** - * @var string[] List of gearman servers - */ - protected $servers = []; + /** List of gearman servers */ + protected array $servers = []; - /** - * @var int The timeout for Gearman connections - */ - protected $timeout = 1000; + /**The timeout for Gearman connections */ + protected int $timeout = 1000; /** * @param int $timeout Timeout in microseconds * - * @see \Vectorface\Gearman\Connection + * @see Connection */ - public function __construct($timeout = 1000) + public function __construct(int $timeout = 1000) { $this->timeout = $timeout; } - public function getServers() + public function getServers(): array { return array_keys($this->servers); } - public function addServers($servers) + public function addServers($servers): self { if (!is_array($servers)) { $servers = explode(',', $servers); @@ -93,26 +85,25 @@ public function addServers($servers) return $this; } - public function addServer($host = 'localhost', $port = null) + public function addServer(string $host = 'localhost', ?int $port = null): self { $host = trim($host); if (empty($host)) { - throw new InvalidArgumentException("Invalid host '$host' given"); + throw new InvalidArgumentException("Invalid host '{$host}' given"); } - if (null === $port) { + if ($port === null) { $port = $this->getDefaultPort(); } else { - $port = (int) $port; if (!$port > 0) { - throw new InvalidArgumentException("Invalid port '$port' given"); + throw new InvalidArgumentException("Invalid port '{$port}' given"); } } $server = $host . ':' . $port; if (isset($this->servers[$server])) { - throw new InvalidArgumentException("Server '$server' is already registered"); + throw new InvalidArgumentException("Server '{$server}' is already registered"); } $this->servers[$server] = true; @@ -275,22 +266,21 @@ public function doEpoch($functionName, $workload, $epoch, $unique = null) } /** - * @param string $functionName - * @param string $workload - * @param string $unique - * @param int $type Type of job to run task as * @param int $epoch Time of job to run at (unix timestamp) - * - * @return Set * @throws Exception */ - private function createSet($functionName, $workload, $unique = null, $type = Task::JOB_NORMAL, $epoch = 0) - { - if (null === $unique) { + private function createSet( + string $functionName, + string $workload, + ?string $unique = null, + int $type = Task::JOB_NORMAL, + int $epoch = 0 + ): Set { + if ($unique === null) { $unique = $this->generateUniqueId(); } - $task = new Task($functionName, $workload, $unique, $type, $epoch); + $task = new Task($functionName, [$workload], $unique, $type, $epoch); $task->type = $type; $set = new Set(); $set->addTask($task); @@ -298,10 +288,7 @@ private function createSet($functionName, $workload, $unique = null, $type = Tas return $set; } - /** - * @return string - */ - protected function generateUniqueId() + protected function generateUniqueId(): string { return getmypid() . '_' . uniqid(); } @@ -309,36 +296,20 @@ protected function generateUniqueId() /** * Submit a task to Gearman. * - * @param Task $task Task to submit to Gearman - * * @throws Exception * @see Task, Client::runSet() */ - protected function submitTask(Task $task) + protected function submitTask(Task $task): void { - switch ($task->type) { - case Task::JOB_LOW: - $type = 'submit_job_low'; - break; - case Task::JOB_LOW_BACKGROUND: - $type = 'submit_job_low_bg'; - break; - case Task::JOB_HIGH_BACKGROUND: - $type = 'submit_job_high_bg'; - break; - case Task::JOB_BACKGROUND: - $type = 'submit_job_bg'; - break; - case Task::JOB_EPOCH: - $type = 'submit_job_epoch'; - break; - case Task::JOB_HIGH: - $type = 'submit_job_high'; - break; - default: - $type = 'submit_job'; - break; - } + $type = match ($task->type) { + Task::JOB_LOW => 'submit_job_low', + Task::JOB_LOW_BACKGROUND => 'submit_job_low_bg', + Task::JOB_HIGH_BACKGROUND => 'submit_job_high_bg', + Task::JOB_BACKGROUND => 'submit_job_bg', + Task::JOB_EPOCH => 'submit_job_epoch', + Task::JOB_HIGH => 'submit_job_high', + default => 'submit_job', + }; $arg = $task->arg; @@ -365,14 +336,11 @@ protected function submitTask(Task $task) /** * Run a set of tasks. - * - * @param Set $set A set of tasks to run - * @param int $timeout Time in seconds for the socket timeout. Max is 10 seconds - * + * @param int|null $timeout Time in seconds for the socket timeout. Max is 10 seconds * @throws Exception - * @see Set, \Vectorface\Gearman\Task + * @see Set, Task */ - public function runSet(Set $set, $timeout = null) + public function runSet(Set $set, ?int $timeout = null) { foreach ($this->getServers() as $server) { $conn = Connection::connect($server, $timeout); @@ -414,10 +382,10 @@ public function runSet(Set $set, $timeout = null) $set->tasks[$k]->type == Task::JOB_LOW_BACKGROUND || $set->tasks[$k]->type == Task::JOB_EPOCH) { $set->tasks[$k]->finished = true; - --$set->tasksCount; + $set->tasksCount--; } - ++$t; + $t++; } $write = null; @@ -436,13 +404,13 @@ public function runSet(Set $set, $timeout = null) /** * Handle the response read in. * - * @param array $resp The raw array response - * @param resource $s The socket - * @param Set $tasks The tasks being run + * @param array $resp The raw array response + * @param resource $socket The socket + * @param Set $tasks The tasks being run * * @throws Exception */ - protected function handleResponse($resp, $s, Set $tasks) + protected function handleResponse(array $resp, $socket, Set $tasks) { $task = null; if (isset($resp['data']['handle']) && $resp['function'] != 'job_created') { @@ -464,7 +432,7 @@ protected function handleResponse($resp, $s, Set $tasks) $task->fail(); break; case 'job_created': - $key = is_object($s) ? spl_object_id($s) : intval($s); + $key = is_object($socket) ? spl_object_id($socket) : intval($socket); $task = array_shift(Connection::$waiting[$key]); $task->handle = $resp['data']['handle']; if ($task->type == Task::JOB_BACKGROUND) { @@ -493,9 +461,6 @@ public function disconnect() } } - /** - * Destructor. - */ public function __destruct() { $this->disconnect(); diff --git a/src/Connection.php b/src/Connection.php index de97a94..47839d1 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -2,6 +2,9 @@ namespace Vectorface\Gearman; +use Socket; +use Vectorface\Gearman\Exception\CouldNotConnectException; + /** * Interface for Danga's Gearman job scheduling system. * @@ -22,8 +25,6 @@ * @link http://pear.php.net/package/Net_Gearman * @link http://www.danga.com/gearman/ */ -use Socket; -use Vectorface\Gearman\Exception\CouldNotConnectException; /** * The base connection class. @@ -47,12 +48,9 @@ class Connection * integer type (first key in second array) used in the binary header, and * the arguments / order of arguments to send/receive. * - * @var array - * - * @see \Vectorface\Gearman\Connection::$magic - * @see \Vectorface\Gearman\Connection::connect() + * @see Connection::connect */ - protected static $commands = [ + protected static array $commands = [ 'can_do' => [1, ['func']], 'can_do_timeout' => [23, ['func', 'timeout']], 'cant_do' => [2, ['func']], @@ -90,12 +88,9 @@ class Connection * This is the same as the \Vectorface\Gearman\Connection::$commands array only * it's keyed by the magic (integer value) value of the command. * - * @var array - * - * @see \Vectorface\Gearman\Connection::$commands - * @see \Vectorface\Gearman\Connection::connect() + * @see Connection::connect */ - protected static $magic = []; + protected static array $magic = []; /** * Tasks waiting for a handle. @@ -103,25 +98,14 @@ class Connection * Tasks are popped onto this queue as they're submitted so that they can * later be popped off of the queue once a handle has been assigned via * the job_created command. - * - * @var array - * @static */ - public static $waiting = []; + public static array $waiting = []; - /** - * Is PHP's multibyte overload turned on? - * - * @var int - */ - protected static $multiByteSupport = null; + /** Is PHP's multibyte overload turned on? */ + protected static ?int $multiByteSupport = null; - /** - * Constructor. - */ final private function __construct() { - // Don't allow this class to be instantiated } /** @@ -130,18 +114,15 @@ final private function __construct() * Opens the socket to the Gearman Job server. It throws an exception if * a socket error occurs. Also populates \Vectorface\Gearman\Connection::$magic. * - * @param string $host e.g. 127.0.0.1 or 127.0.0.1:7003 - * @param int $timeout Timeout in milliseconds + * @param string $host e.g. 127.0.0.1 or 127.0.0.1:7003 + * @param int|null $timeout Timeout in milliseconds * * @return resource|Socket A connection to a Gearman server * - * @throws Exception when it can't connect to server - * - * @see \Vectorface\Gearman\Connection::$waiting - * @see \Vectorface\Gearman\Connection::$magic - * @see \Vectorface\Gearman\Connection::$commands + * @throws CouldNotConnectException + * @see Connection */ - public static function connect($host = 'localhost', $timeout = 2000) + public static function connect(string $host = 'localhost', ?int $timeout = 2000) { if (!count(self::$magic)) { foreach (self::$commands as $cmd => $i) { @@ -168,9 +149,9 @@ public static function connect($host = 'localhost', $timeout = 2000) if (!$socket_connected) { $errno = socket_last_error($socket); - $errstr = socket_strerror($errno); + $errStr = socket_strerror($errno); throw new CouldNotConnectException( - "Can't connect to server ($errno: $errstr)" + "Can't connect to server ({$errno}: {$errStr})" ); } @@ -194,8 +175,7 @@ public static function connect($host = 'localhost', $timeout = 2000) * * @throws Exception on invalid command or unable to write * - * @see \Vectorface\Gearman\Connection::$commands, \Vectorface\Gearman\Connection::$socket - * + * @see Connection */ public static function send($socket, $command, array $params = []) { @@ -243,9 +223,9 @@ public static function send($socket, $command, array $params = []) if ($error === true) { $errno = socket_last_error($socket); - $errstr = socket_strerror($errno); + $errStr = socket_strerror($errno); throw new Exception( - "Could not write command to socket ($errno: $errstr)" + "Could not write command to socket ({$errno}: {$errStr})" ); } } @@ -256,12 +236,11 @@ public static function send($socket, $command, array $params = []) * @param resource|Socket $socket The socket to read from * * @return array Result read back from Gearman - *@throws Exception connection issues or invalid responses - * - * @see \Vectorface\Gearman\Connection::$magic + * @throws Exception connection issues or invalid responses * + * @see Connection */ - public static function read($socket) + public static function read($socket): array { $header = ''; do { @@ -273,7 +252,7 @@ public static function read($socket) throw new Exception('Connection was reset'); } - if (self::stringLength($header) == 0) { + if (self::stringLength($header) === 0) { return []; } $resp = @unpack('a4magic/Ntype/Nlen', $header); @@ -321,11 +300,9 @@ public static function read($socket) * @param resource|Socket $socket The socket to read from * @param float $timeout The timeout for the read * - * @return array - *@throws Exception on timeouts - * + * @throws Exception on timeouts */ - public static function blockingRead($socket, $timeout = 500.0) + public static function blockingRead($socket, float $timeout = 500.0): array { static $cmds = []; @@ -367,34 +344,28 @@ public static function close($socket) * Are we connected? * * @param resource|Socket $socket The socket to check - * - * @return bool False if we aren't connected */ - public static function isConnected($socket) + public static function isConnected($socket): bool { return $socket !== false; } /** - * Determine if we should use mb_strlen or stock strlen. + * Use mb_strlen or stock strlen depending on support. * * @param string $value The string value to check * - * @return int Size of string - * - * @see \Vectorface\Gearman\Connection::$multiByteSupport + * @see Connection */ - public static function stringLength($value) + public static function stringLength(string $value): int { - if (is_null(self::$multiByteSupport)) { - self::$multiByteSupport = intval(ini_get('mbstring.func_overload')); + if (self::$multiByteSupport === null) { + self::$multiByteSupport = (int)ini_get('mbstring.func_overload'); } - if (self::$multiByteSupport & 2) { return mb_strlen($value, '8bit'); - } else { - return strlen($value); } + return strlen($value); } /** @@ -406,16 +377,15 @@ public static function stringLength($value) * * @return string Portion of $str specified by $start and $length * - * @see \Vectorface\Gearman\Connection::$multiByteSupport + * @see Connection * @link http://us3.php.net/mb_substr * @link http://us3.php.net/substr */ - public static function subString($str, $start, $length) + public static function subString(string $str, int $start, int $length): string { - if (is_null(self::$multiByteSupport)) { - self::$multiByteSupport = intval(ini_get('mbstring.func_overload')); + if (self::$multiByteSupport === null) { + self::$multiByteSupport = (int)ini_get('mbstring.func_overload'); } - if (self::$multiByteSupport & 2) { return mb_substr($str, $start, $length, '8bit'); } diff --git a/src/Manager.php b/src/Manager.php index 0b2ee12..07c46dd 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -55,8 +55,8 @@ class Manager * * @var resource Connection to Gearman server * - * @see \Vectorface\Gearman\Manager::sendCommand() - * @see \Vectorface\Gearman\Manager::recvCommand() + * @see Manager::sendCommand + * @see Manager::recvCommand */ protected $conn = null; @@ -66,34 +66,23 @@ class Manager * We obviously can't send more commands to a server after it's been shut * down. This is set to true in \Vectorface\Gearman\Manager::shutdown() and then * checked in \Vectorface\Gearman\Manager::sendCommand(). - * - * @var bool */ - protected $shutdown = false; + protected bool $shutdown = false; - /** - * Last error code - * @var int - */ - private $errorCode = 0; + /** Last error code */ + private int $errorCode = 0; - /** - * Last error message - * @var null|string - */ - private $errorMessage = null; + /** Last error message */ + private ?string $errorMessage = null; /** - * Constructor. - * - * @param string $server Host and port (e.g. 'localhost:7003') - * @param int $timeout Connection timeout + * @param string $server Host and port (e.g. 'localhost:7003') + * @param int|null $timeout Connection timeout * * @throws Exception - * - * @see \Vectorface\Gearman\Manager::$conn + * @see Manager */ - public function __construct($server, $timeout = self::CONNECT_TIMEOUT) + public function __construct(string $server, ?int $timeout = self::CONNECT_TIMEOUT) { if (strpos($server, ':')) { [$host, $port] = explode(':', $server); @@ -119,8 +108,8 @@ public function __construct($server, $timeout = self::CONNECT_TIMEOUT) * @return string * * @throws Exception - * @see \Vectorface\Gearman\Manager::checkForError() - * @see \Vectorface\Gearman\Manager::sendCommand() + * @see Manager::checkForError + * @see Manager::sendCommand */ public function version() { @@ -136,14 +125,11 @@ public function version() * * @param bool $graceful Whether it should be a graceful shutdown * - * @return bool - * * @throws Exception - * @see \Vectorface\Gearman\Manager::checkForError() - * @see \Vectorface\Gearman\Manager::$shutdown - * @see \Vectorface\Gearman\Manager::sendCommand() + * @see Manager::checkForError + * @see Manager::sendCommand */ - public function shutdown($graceful = false) + public function shutdown(bool $graceful = false): bool { $cmd = ($graceful) ? 'shutdown graceful' : 'shutdown'; $this->sendCommand($cmd); @@ -335,7 +321,7 @@ protected function checkForError($data) /** * Disconnect from server. * - * @see \Vectorface\Gearman\Manager::$conn + * @see Manager */ public function disconnect() { diff --git a/src/ServerSetting.php b/src/ServerSetting.php index 74cbe8c..a03ed45 100644 --- a/src/ServerSetting.php +++ b/src/ServerSetting.php @@ -9,24 +9,17 @@ interface ServerSetting /** * @return string[] */ - public function getServers(); + public function getServers(): array; /** - * @param string $host - * @param int $port - * * @throws InvalidArgumentException - * - * @return self */ - public function addServer($host = 'localhost', $port = null); + public function addServer(string $host = 'localhost', ?int $port = null): self; /** * @param string|array $servers Servers separated with comma, or array of servers * * @throws InvalidArgumentException - * - * @return self */ - public function addServers($servers); + public function addServers($servers): self; } diff --git a/src/Set.php b/src/Set.php index 0c31fdf..244386d 100644 --- a/src/Set.php +++ b/src/Set.php @@ -72,44 +72,25 @@ * @version Release: @package_version@ * * @link http://www.danga.com/gearman/ - * @see \Vectorface\Gearman\Job\CommonJob, \Vectorface\Gearman\Worker + * @see \Vectorface\Gearman\Job\CommonJob, Worker */ class Set implements IteratorAggregate, Countable { - /** - * Tasks count. - * - * @var int - */ - public $tasksCount = 0; + /** Tasks count */ + public int $tasksCount = 0; - /** - * Tasks to run. - * - * @var Task[] - */ - public $tasks = []; + /** @var Task[] Tasks to run */ + public array $tasks = []; - /** - * Handle to task mapping. - * - * @var array - */ - public $handles = []; + /** Handle to task mapping */ + public array $handles = []; - /** - * Callback registered for set. - * - * @var mixed - */ - protected $callback = null; + /** Callback registered for set */ + protected mixed $callback = null; /** - * Constructor. - * * @param array $tasks Array of tasks to run - * - * @see \Vectorface\Gearman\Task + * @see Task */ public function __construct(array $tasks = []) { @@ -120,29 +101,22 @@ public function __construct(array $tasks = []) /** * Add a task to the set. - * - * @param Task $task Task to add to the set - * - * @see \Vectorface\Gearman\Task, \Vectorface\Gearman\Set::$tasks + * @see Task, Set */ public function addTask(Task $task) { if (!isset($this->tasks[$task->uniq])) { $this->tasks[$task->uniq] = $task; - ++$this->tasksCount; + $this->tasksCount++; } } /** * Get a task. * - * @param string $handle Handle of task to get - * - * @return object Instance of task - *@throws Exception - * + * @throws Exception */ - public function getTask($handle) + public function getTask(string $handle): Task { if (!isset($this->handles[$handle])) { throw new Exception('Unknown handle'); @@ -161,12 +135,10 @@ public function getTask($handle) * This function will return true if all the tasks in the set have * finished running. If they have we also run the set callbacks if * there is one. - * - * @return bool */ - public function finished() + public function finished(): bool { - if ($this->tasksCount != 0) { + if ($this->tasksCount !== 0) { return false; } @@ -185,25 +157,20 @@ public function finished() /** * Attach a callback to this set. * - * @param callback $callback A valid PHP callback - * * @throws Exception */ - public function attachCallback($callback) + public function attachCallback(callable $callback) { if (!is_callable($callback)) { throw new Exception('Invalid callback specified'); } - $this->callback = $callback; } /** * Get the iterator. - * - * @return ArrayIterator Tasks */ - public function getIterator() + public function getIterator(): ArrayIterator { return new ArrayIterator($this->tasks); } @@ -211,11 +178,9 @@ public function getIterator() /** * Get the task count. * - * @return int Number of tasks in the set - * - * @see {@link Countable::count()} + * @see Countable::count() */ - public function count() + public function count(): int { return $this->tasksCount; } diff --git a/src/Task.php b/src/Task.php index 7bbf236..52004cc 100644 --- a/src/Task.php +++ b/src/Task.php @@ -41,19 +41,11 @@ */ class Task { - /** - * The function/job to run. - * - * @var string - */ - public $func = ''; + /** The function/job to run */ + public string $func = ''; - /** - * Arguments to pass to function/job. - * - * @var array - */ - public $arg = []; + /** Arguments to pass to function/job */ + public array $arg = []; /** * Type of job. @@ -62,8 +54,6 @@ class Task * background jobs are "fire and forget" and DO NOT return results to the * job server in a manner that you can actually retrieve. * - * @var int - * * @see Task::JOB_NORMAL * @see Task::JOB_BACKGROUND * @see Task::JOB_EPOCH @@ -72,16 +62,10 @@ class Task * @see Task::JOB_LOW * @see Task::JOB_LOW_BACKGROUND */ - public $type = self::JOB_NORMAL; + public int $type = self::JOB_NORMAL; - /** - * Handle returned from job server. - * - * @var string - * - * @see Client - */ - public $handle = ''; + /** Handle returned from job server, @see Client */ + public string $handle = ''; /** * The unique identifier for this job. @@ -94,10 +78,8 @@ class Task * that job only once. If you send the job Sum with args 1, 2, 3 to the * server 10 times in a second Gearman will only run that job once and then * return the result 10 times. - * - * @var string */ - public $uniq = ''; + public string $uniq = ''; /** * Is this task finished? @@ -108,36 +90,30 @@ class Task * @see Task::complete() * @see Task::fail() */ - public $finished = false; + public bool $finished = false; /** * The result returned from the worker. - * - * @var object */ - public $result = ''; + public string|object $result = ''; /** * Unix timestamp. * * This allows you to schedule a background job to run at * a specific moment in time - * - * @var int */ - public $epoch = 0; + public int $epoch = 0; /** * Callbacks registered for each state. * - * @var array - * * @see Task::attachCallback() * @see Task::complete() * @see Task::status() * @see Task::fail() */ - protected $callback = [ + protected array $callback = [ self::TASK_COMPLETE => [], self::TASK_FAIL => [], self::TASK_STATUS => [], @@ -149,8 +125,6 @@ class Task * Normal jobs are run against a worker with the result being returned * all in the same thread (e.g. Your page will sit there waiting for the * job to finish and return its result). - * - * @var int JOB_NORMAL */ const JOB_NORMAL = 1; @@ -159,36 +133,26 @@ class Task * * Background jobs in Gearman are "fire and forget". You can check a job's * status periodically, but you can't get a result back from it. - * - * @var int JOB_BACKGROUND */ const JOB_BACKGROUND = 2; /** * High priority job. - * - * @var int JOB_HIGH */ const JOB_HIGH = 3; /** * High priority, background job. - * - * @var int JOB_HIGH */ const JOB_HIGH_BACKGROUND = 4; /** * LOW priority job. - * - * @var int JOB_LOW */ const JOB_LOW = 5; /** * Low priority, background job. - * - * @var int JOB_LOW_BACKGROUND */ const JOB_LOW_BACKGROUND = 6; @@ -197,8 +161,6 @@ class Task * * Background jobs in Gearman are "fire and forget". You can check a job's * status periodically, but you can't get a result back from it. - * - * @var int JOB_EPOCH */ const JOB_EPOCH = 7; @@ -208,8 +170,6 @@ class Task * The callback provided should be run when the task has been completed. It * will be handed the result of the task as its only argument. * - * @var int TASK_COMPLETE - * * @see Task::complete() */ const TASK_COMPLETE = 1; @@ -220,8 +180,6 @@ class Task * The callback provided should be run when the task has been reported to * have failed by Gearman. No arguments are provided. * - * @var int TASK_FAIL - * * @see Task::fail() */ const TASK_FAIL = 2; @@ -233,37 +191,38 @@ class Task * been updated. The numerator and denominator are passed as the only * two arguments. * - * @var int TASK_STATUS - * * @see Task::status() */ const TASK_STATUS = 3; /** - * Constructor. - * - * @param string $func Name of job to run - * @param mixed $arg List of arguments for job - * @param string $uniq The unique id of the job - * @param int $type Type of job to run task as + * @param string $func Name of job to run + * @param mixed $arg List of arguments for job + * @param string|null $unique_id The unique id of the job + * @param int|null $type Type of job to run task as * @param int $epoch Time of job to run at (unix timestamp) * * @throws Exception */ - public function __construct($func, $arg, $uniq = null, $type = self::JOB_NORMAL, $epoch = 0) - { + public function __construct( + string $func, + array $arg, + ?string $unique_id = null, + ?int $type = self::JOB_NORMAL, + int $epoch = 0 + ) { $this->func = $func; $this->arg = $arg; - if (is_null($uniq)) { + if ($unique_id === null) { $this->uniq = md5($func . serialize($arg) . $type); } else { - $this->uniq = $uniq; + $this->uniq = $unique_id; } $type = (int) $type; - if ($type == self::JOB_EPOCH) { + if ($type === self::JOB_EPOCH) { $this->epoch = $epoch; } @@ -371,10 +330,10 @@ public function status($numerator, $denominator) foreach ($this->callback[self::TASK_STATUS] as $callback) { call_user_func( $callback, - $this->func, - $this->handle, - $numerator, - $denominator + $this->func, + $this->handle, + $numerator, + $denominator ); } } diff --git a/src/Worker.php b/src/Worker.php index 53ef2cf..ea7dc36 100644 --- a/src/Worker.php +++ b/src/Worker.php @@ -43,45 +43,33 @@ * @version Release: @package_version@ * * @link http://www.danga.com/gearman/ - * @see \Vectorface\Gearman\Job, \Vectorface\Gearman\Connection + * @see Job, Connection */ class Worker implements ServerSetting { - /** - * @var string Unique id for this worker - */ - protected $id; + /**Unique id for this worker */ + protected ?string $id = null; - /** - * @var array Pool of connections to Gearman servers - */ - protected $connection = []; + /**Pool of connections to Gearman servers */ + protected array $connection = []; - /** - * @var array Pool of retry connections - */ - protected $retryConn = []; + /** Pool of retry connections */ + protected array $retryConn = []; - /** - * @var string[] - */ - protected $functions = []; + /** @var string[] */ + protected array $functions = []; - /** - * @var string[] List of gearman servers - */ - protected $servers = []; + /** @var string[] List of gearman servers */ + protected array $servers = []; /** * Callbacks registered for this worker. * - * @var array - * - * @see \Vectorface\Gearman\Worker::JOB_START - * @see \Vectorface\Gearman\Worker::JOB_COMPLETE - * @see \Vectorface\Gearman\Worker::JOB_FAIL + * @see Worker::JOB_START + * @see Worker::JOB_COMPLETE + * @see Worker::JOB_FAIL */ - protected $callback = [ + protected array $callback = [ self::JOB_START => [], self::JOB_COMPLETE => [], self::JOB_FAIL => [], @@ -103,19 +91,19 @@ class Worker implements ServerSetting */ public function __construct($id = null) { - if (null === $id) { + if ($id === null) { $id = 'pid_' . getmypid() . '_' . uniqid(); } $this->id = $id; } - public function getServers() + public function getServers(): array { return array_keys($this->servers); } - public function addServers($servers) + public function addServers($servers): self { if (!is_array($servers)) { $servers = explode(',', $servers); @@ -131,26 +119,25 @@ public function addServers($servers) return $this; } - public function addServer($host = 'localhost', $port = null) + public function addServer(string $host = 'localhost', ?int $port = null) : ServerSetting { $host = trim($host); if (empty($host)) { - throw new InvalidArgumentException("Invalid host '$host' given"); + throw new InvalidArgumentException("Invalid host '{$host}' given"); } - if (null === $port) { + if ($port === null) { $port = $this->getDefaultPort(); } else { - $port = (int) $port; if (!$port > 0) { - throw new InvalidArgumentException("Invalid port '$port' given"); + throw new InvalidArgumentException("Invalid port '{$port}' given"); } } $server = $host . ':' . $port; if (isset($this->servers[$server])) { - throw new InvalidArgumentException("Server '$server' is already registered"); + throw new InvalidArgumentException("Server '{$server}' is already registered"); } $this->servers[$server] = true; @@ -186,11 +173,11 @@ public function getFunctions() public function addFunction($functionName, $callback, $timeout = null) { if (isset($this->functions[$functionName])) { - throw new InvalidArgumentException("Function $functionName is already registered"); + throw new InvalidArgumentException("Function {$functionName} is already registered"); } $this->functions[$functionName] = ['callback' => $callback]; - if (null !== $timeout) { + if ($timeout !== null) { $this->functions[$functionName]['timeout'] = $timeout; } @@ -198,16 +185,12 @@ public function addFunction($functionName, $callback, $timeout = null) } /** - * @param string - * * @throws InvalidArgumentException - * - * @return self */ - public function unregister($functionName) + public function unregister(string $functionName): self { if (!isset($this->functions[$functionName])) { - throw new InvalidArgumentException("Function $functionName is not registered"); + throw new InvalidArgumentException("Function {$functionName} is not registered"); } unset($this->functions[$functionName]); @@ -251,7 +234,7 @@ public function work($monitor = null) $worked = false; try { $worked = $this->doWork($socket); - } catch (\Exception $e) { + } catch (\Exception) { unset($this->connection[$server]); $this->retryConn[$server] = $currentTime; } @@ -281,7 +264,7 @@ public function work($monitor = null) $retryChange = true; unset($this->retryConn[$s]); Connection::send($conn, 'set_client_id', ['client_id' => $this->id]); - } catch (Exception $e) { + } catch (Exception) { $this->retryConn[$s] = $currentTime; } } @@ -296,7 +279,7 @@ public function work($monitor = null) $this->registerFunctionsToOpenedConnections(); } - if (call_user_func($monitor, $idle, $lastJob) == true) { + if (call_user_func($monitor, $idle, $lastJob)) { $working = false; } } @@ -312,7 +295,7 @@ private function connectToAllServers() $connection = Connection::connect($server); Connection::send($connection, 'set_client_id', ['client_id' => $this->id]); $this->connection[$server] = $connection; - } catch (\Exception $exception) { + } catch (\Exception) { $this->retryConn[$server] = time(); } } @@ -408,7 +391,7 @@ protected function doWork($socket) * @param int $denominator The denominator (e.g. 100) * * @throws Exception - * @see \Vectorface\Gearman\Connection::send() + * @see Connection::send */ public function jobStatus($socket, $handle, $numerator, $denominator) { @@ -427,7 +410,7 @@ public function jobStatus($socket, $handle, $numerator, $denominator) * @param array $result Result of your job * * @throws Exception - * @see \Vectorface\Gearman\Connection::send() + * @see Connection::send */ private function jobComplete($socket, $handle, $result) { @@ -448,7 +431,7 @@ private function jobComplete($socket, $handle, $result) * @param string $handle * * @throws Exception - * @see \Vectorface\Gearman\Connection::send() + * @see Connection::send */ private function jobFail($socket, $handle) { @@ -524,10 +507,8 @@ public function endWork() /** * Should we stop work? - * - * @return bool */ - public function stopWork() + public function stopWork(): bool { return false; }