repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
thephpleague/uri-schemes
src/Uri.php
Uri.formatPort
private function formatPort($port = null): ?int { if (null === $port || '' === $port) { return null; } if (!is_int($port) && !(is_string($port) && 1 === preg_match('/^\d*$/', $port))) { throw new SyntaxError(sprintf('The port `%s` is invalid', $port)); } $port = (int) $port; if (0 > $port) { throw new SyntaxError(sprintf('The port `%s` is invalid', $port)); } $defaultPort = self::SCHEME_DEFAULT_PORT[$this->scheme] ?? null; if ($defaultPort === $port) { return null; } return $port; }
php
private function formatPort($port = null): ?int { if (null === $port || '' === $port) { return null; } if (!is_int($port) && !(is_string($port) && 1 === preg_match('/^\d*$/', $port))) { throw new SyntaxError(sprintf('The port `%s` is invalid', $port)); } $port = (int) $port; if (0 > $port) { throw new SyntaxError(sprintf('The port `%s` is invalid', $port)); } $defaultPort = self::SCHEME_DEFAULT_PORT[$this->scheme] ?? null; if ($defaultPort === $port) { return null; } return $port; }
[ "private", "function", "formatPort", "(", "$", "port", "=", "null", ")", ":", "?", "int", "{", "if", "(", "null", "===", "$", "port", "||", "''", "===", "$", "port", ")", "{", "return", "null", ";", "}", "if", "(", "!", "is_int", "(", "$", "por...
Format the Port component. @param null|mixed $port
[ "Format", "the", "Port", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L487-L508
thephpleague/uri-schemes
src/Uri.php
Uri.create
public static function create($uri, $base_uri = null): UriInterface { if (!$uri instanceof UriInterface) { $uri = self::createFromString($uri); } if (null === $base_uri) { if (null === $uri->getScheme()) { throw new SyntaxError(sprintf('the URI `%s` must be absolute', (string) $uri)); } if (null === $uri->getAuthority()) { return $uri; } return UriResolver::resolve($uri, $uri->withFragment(null)->withQuery(null)->withPath('')); } if (!$base_uri instanceof UriInterface) { $base_uri = self::createFromString($base_uri); } if (null === $base_uri->getScheme()) { throw new SyntaxError(sprintf('the base URI `%s` must be absolute', (string) $base_uri)); } return UriResolver::resolve($uri, $base_uri); }
php
public static function create($uri, $base_uri = null): UriInterface { if (!$uri instanceof UriInterface) { $uri = self::createFromString($uri); } if (null === $base_uri) { if (null === $uri->getScheme()) { throw new SyntaxError(sprintf('the URI `%s` must be absolute', (string) $uri)); } if (null === $uri->getAuthority()) { return $uri; } return UriResolver::resolve($uri, $uri->withFragment(null)->withQuery(null)->withPath('')); } if (!$base_uri instanceof UriInterface) { $base_uri = self::createFromString($base_uri); } if (null === $base_uri->getScheme()) { throw new SyntaxError(sprintf('the base URI `%s` must be absolute', (string) $base_uri)); } return UriResolver::resolve($uri, $base_uri); }
[ "public", "static", "function", "create", "(", "$", "uri", ",", "$", "base_uri", "=", "null", ")", ":", "UriInterface", "{", "if", "(", "!", "$", "uri", "instanceof", "UriInterface", ")", "{", "$", "uri", "=", "self", "::", "createFromString", "(", "$"...
Create a new instance from a URI and a Base URI. The returned URI must be absolute. @param mixed $uri the input URI to create @param mixed $base_uri the base URI used for reference
[ "Create", "a", "new", "instance", "from", "a", "URI", "and", "a", "Base", "URI", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L541-L568
thephpleague/uri-schemes
src/Uri.php
Uri.createFromString
public static function createFromString($uri = ''): self { $components = UriString::parse($uri); return new self( $components['scheme'], $components['user'], $components['pass'], $components['host'], $components['port'], $components['path'], $components['query'], $components['fragment'] ); }
php
public static function createFromString($uri = ''): self { $components = UriString::parse($uri); return new self( $components['scheme'], $components['user'], $components['pass'], $components['host'], $components['port'], $components['path'], $components['query'], $components['fragment'] ); }
[ "public", "static", "function", "createFromString", "(", "$", "uri", "=", "''", ")", ":", "self", "{", "$", "components", "=", "UriString", "::", "parse", "(", "$", "uri", ")", ";", "return", "new", "self", "(", "$", "components", "[", "'scheme'", "]",...
Create a new instance from a string. @param string|mixed $uri
[ "Create", "a", "new", "instance", "from", "a", "string", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L575-L589
thephpleague/uri-schemes
src/Uri.php
Uri.createFromComponents
public static function createFromComponents(array $components = []): self { $components += [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => null, 'path' => '', 'query' => null, 'fragment' => null, ]; return new self( $components['scheme'], $components['user'], $components['pass'], $components['host'], $components['port'], $components['path'], $components['query'], $components['fragment'] ); }
php
public static function createFromComponents(array $components = []): self { $components += [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => null, 'path' => '', 'query' => null, 'fragment' => null, ]; return new self( $components['scheme'], $components['user'], $components['pass'], $components['host'], $components['port'], $components['path'], $components['query'], $components['fragment'] ); }
[ "public", "static", "function", "createFromComponents", "(", "array", "$", "components", "=", "[", "]", ")", ":", "self", "{", "$", "components", "+=", "[", "'scheme'", "=>", "null", ",", "'user'", "=>", "null", ",", "'pass'", "=>", "null", ",", "'host'"...
Create a new instance from a hash of parse_url parts. Create an new instance from a hash representation of the URI similar to PHP parse_url function result
[ "Create", "a", "new", "instance", "from", "a", "hash", "of", "parse_url", "parts", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L597-L614
thephpleague/uri-schemes
src/Uri.php
Uri.createFromDataPath
public static function createFromDataPath(string $path, $context = null): self { $file_args = [$path, false]; $mime_args = [$path, FILEINFO_MIME]; if (null !== $context) { $file_args[] = $context; $mime_args[] = $context; } $raw = @file_get_contents(...$file_args); if (false === $raw) { throw new SyntaxError(sprintf('The file `%s` does not exist or is not readable', $path)); } return Uri::createFromComponents([ 'scheme' => 'data', 'path' => str_replace(' ', '', (new finfo(FILEINFO_MIME))->file(...$mime_args)).';base64,'.base64_encode($raw), ]); }
php
public static function createFromDataPath(string $path, $context = null): self { $file_args = [$path, false]; $mime_args = [$path, FILEINFO_MIME]; if (null !== $context) { $file_args[] = $context; $mime_args[] = $context; } $raw = @file_get_contents(...$file_args); if (false === $raw) { throw new SyntaxError(sprintf('The file `%s` does not exist or is not readable', $path)); } return Uri::createFromComponents([ 'scheme' => 'data', 'path' => str_replace(' ', '', (new finfo(FILEINFO_MIME))->file(...$mime_args)).';base64,'.base64_encode($raw), ]); }
[ "public", "static", "function", "createFromDataPath", "(", "string", "$", "path", ",", "$", "context", "=", "null", ")", ":", "self", "{", "$", "file_args", "=", "[", "$", "path", ",", "false", "]", ";", "$", "mime_args", "=", "[", "$", "path", ",", ...
Create a new instance from a data file path. @param resource|null $context @throws SyntaxError If the file does not exist or is not readable
[ "Create", "a", "new", "instance", "from", "a", "data", "file", "path", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L623-L641
thephpleague/uri-schemes
src/Uri.php
Uri.createFromUnixPath
public static function createFromUnixPath(string $uri = ''): self { $uri = implode('/', array_map('rawurlencode', explode('/', $uri))); if ('/' !== ($uri[0] ?? '')) { return Uri::createFromComponents(['path' => $uri]); } return Uri::createFromComponents(['path' => $uri, 'scheme' => 'file', 'host' => '']); }
php
public static function createFromUnixPath(string $uri = ''): self { $uri = implode('/', array_map('rawurlencode', explode('/', $uri))); if ('/' !== ($uri[0] ?? '')) { return Uri::createFromComponents(['path' => $uri]); } return Uri::createFromComponents(['path' => $uri, 'scheme' => 'file', 'host' => '']); }
[ "public", "static", "function", "createFromUnixPath", "(", "string", "$", "uri", "=", "''", ")", ":", "self", "{", "$", "uri", "=", "implode", "(", "'/'", ",", "array_map", "(", "'rawurlencode'", ",", "explode", "(", "'/'", ",", "$", "uri", ")", ")", ...
Create a new instance from a Unix path string.
[ "Create", "a", "new", "instance", "from", "a", "Unix", "path", "string", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L646-L654
thephpleague/uri-schemes
src/Uri.php
Uri.createFromWindowsPath
public static function createFromWindowsPath(string $uri = ''): self { $root = ''; if (1 === preg_match(self::REGEXP_WINDOW_PATH, $uri, $matches)) { $root = substr($matches['root'], 0, -1).':'; $uri = substr($uri, strlen($root)); } $uri = str_replace('\\', '/', $uri); $uri = implode('/', array_map('rawurlencode', explode('/', $uri))); //Local Windows absolute path if ('' !== $root) { return Uri::createFromComponents(['path' => '/'.$root.$uri, 'scheme' => 'file', 'host' => '']); } //UNC Windows Path if ('//' !== substr($uri, 0, 2)) { return Uri::createFromComponents(['path' => $uri]); } $parts = explode('/', substr($uri, 2), 2) + [1 => null]; return Uri::createFromComponents(['host' => $parts[0], 'path' => '/'.$parts[1], 'scheme' => 'file']); }
php
public static function createFromWindowsPath(string $uri = ''): self { $root = ''; if (1 === preg_match(self::REGEXP_WINDOW_PATH, $uri, $matches)) { $root = substr($matches['root'], 0, -1).':'; $uri = substr($uri, strlen($root)); } $uri = str_replace('\\', '/', $uri); $uri = implode('/', array_map('rawurlencode', explode('/', $uri))); //Local Windows absolute path if ('' !== $root) { return Uri::createFromComponents(['path' => '/'.$root.$uri, 'scheme' => 'file', 'host' => '']); } //UNC Windows Path if ('//' !== substr($uri, 0, 2)) { return Uri::createFromComponents(['path' => $uri]); } $parts = explode('/', substr($uri, 2), 2) + [1 => null]; return Uri::createFromComponents(['host' => $parts[0], 'path' => '/'.$parts[1], 'scheme' => 'file']); }
[ "public", "static", "function", "createFromWindowsPath", "(", "string", "$", "uri", "=", "''", ")", ":", "self", "{", "$", "root", "=", "''", ";", "if", "(", "1", "===", "preg_match", "(", "self", "::", "REGEXP_WINDOW_PATH", ",", "$", "uri", ",", "$", ...
Create a new instance from a local Windows path string.
[ "Create", "a", "new", "instance", "from", "a", "local", "Windows", "path", "string", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L659-L682
thephpleague/uri-schemes
src/Uri.php
Uri.createFromPsr7
public static function createFromPsr7(Psr7UriInterface $uri): self { $components = [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => $uri->getPort(), 'path' => $uri->getPath(), 'query' => null, 'fragment' => null, ]; $scheme = $uri->getScheme(); if ('' !== $scheme) { $components['scheme'] = $scheme; } $fragment = $uri->getFragment(); if ('' !== $fragment) { $components['fragment'] = $fragment; } $query = $uri->getQuery(); if ('' !== $query) { $components['query'] = $query; } $host = $uri->getHost(); if ('' !== $host) { $components['host'] = $host; } $user_info = $uri->getUserInfo(); if (null !== $user_info) { [$components['user'], $components['pass']] = explode(':', $user_info, 2) + [1 => null]; } return Uri::createFromComponents($components); }
php
public static function createFromPsr7(Psr7UriInterface $uri): self { $components = [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => $uri->getPort(), 'path' => $uri->getPath(), 'query' => null, 'fragment' => null, ]; $scheme = $uri->getScheme(); if ('' !== $scheme) { $components['scheme'] = $scheme; } $fragment = $uri->getFragment(); if ('' !== $fragment) { $components['fragment'] = $fragment; } $query = $uri->getQuery(); if ('' !== $query) { $components['query'] = $query; } $host = $uri->getHost(); if ('' !== $host) { $components['host'] = $host; } $user_info = $uri->getUserInfo(); if (null !== $user_info) { [$components['user'], $components['pass']] = explode(':', $user_info, 2) + [1 => null]; } return Uri::createFromComponents($components); }
[ "public", "static", "function", "createFromPsr7", "(", "Psr7UriInterface", "$", "uri", ")", ":", "self", "{", "$", "components", "=", "[", "'scheme'", "=>", "null", ",", "'user'", "=>", "null", ",", "'pass'", "=>", "null", ",", "'host'", "=>", "null", ",...
Create a new instance from a PSR7 UriInterface object.
[ "Create", "a", "new", "instance", "from", "a", "PSR7", "UriInterface", "object", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L687-L726
thephpleague/uri-schemes
src/Uri.php
Uri.createFromEnvironment
public static function createFromEnvironment(array $server): self { [$user, $pass] = self::fetchUserInfo($server); [$host, $port] = self::fetchHostname($server); [$path, $query] = self::fetchRequestUri($server); return Uri::createFromComponents([ 'scheme' => self::fetchScheme($server), 'user' => $user, 'pass' => $pass, 'host' => $host, 'port' => $port, 'path' => $path, 'query' => $query, ]); }
php
public static function createFromEnvironment(array $server): self { [$user, $pass] = self::fetchUserInfo($server); [$host, $port] = self::fetchHostname($server); [$path, $query] = self::fetchRequestUri($server); return Uri::createFromComponents([ 'scheme' => self::fetchScheme($server), 'user' => $user, 'pass' => $pass, 'host' => $host, 'port' => $port, 'path' => $path, 'query' => $query, ]); }
[ "public", "static", "function", "createFromEnvironment", "(", "array", "$", "server", ")", ":", "self", "{", "[", "$", "user", ",", "$", "pass", "]", "=", "self", "::", "fetchUserInfo", "(", "$", "server", ")", ";", "[", "$", "host", ",", "$", "port"...
Create a new instance from the environment.
[ "Create", "a", "new", "instance", "from", "the", "environment", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L731-L746
thephpleague/uri-schemes
src/Uri.php
Uri.fetchScheme
private static function fetchScheme(array $server): string { $server += ['HTTPS' => '']; $res = filter_var($server['HTTPS'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); return $res !== false ? 'https' : 'http'; }
php
private static function fetchScheme(array $server): string { $server += ['HTTPS' => '']; $res = filter_var($server['HTTPS'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); return $res !== false ? 'https' : 'http'; }
[ "private", "static", "function", "fetchScheme", "(", "array", "$", "server", ")", ":", "string", "{", "$", "server", "+=", "[", "'HTTPS'", "=>", "''", "]", ";", "$", "res", "=", "filter_var", "(", "$", "server", "[", "'HTTPS'", "]", ",", "FILTER_VALIDA...
Returns the environment scheme.
[ "Returns", "the", "environment", "scheme", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L751-L757
thephpleague/uri-schemes
src/Uri.php
Uri.fetchUserInfo
private static function fetchUserInfo(array $server): array { $server += ['PHP_AUTH_USER' => null, 'PHP_AUTH_PW' => null, 'HTTP_AUTHORIZATION' => '']; $user = $server['PHP_AUTH_USER']; $pass = $server['PHP_AUTH_PW']; if (0 === strpos(strtolower($server['HTTP_AUTHORIZATION']), 'basic')) { $userinfo = base64_decode(substr($server['HTTP_AUTHORIZATION'], 6), true); if (false === $userinfo) { throw new SyntaxError('The user info could not be detected'); } [$user, $pass] = explode(':', $userinfo, 2) + [1 => null]; } if (null !== $user) { $user = rawurlencode($user); } if (null !== $pass) { $pass = rawurlencode($pass); } return [$user, $pass]; }
php
private static function fetchUserInfo(array $server): array { $server += ['PHP_AUTH_USER' => null, 'PHP_AUTH_PW' => null, 'HTTP_AUTHORIZATION' => '']; $user = $server['PHP_AUTH_USER']; $pass = $server['PHP_AUTH_PW']; if (0 === strpos(strtolower($server['HTTP_AUTHORIZATION']), 'basic')) { $userinfo = base64_decode(substr($server['HTTP_AUTHORIZATION'], 6), true); if (false === $userinfo) { throw new SyntaxError('The user info could not be detected'); } [$user, $pass] = explode(':', $userinfo, 2) + [1 => null]; } if (null !== $user) { $user = rawurlencode($user); } if (null !== $pass) { $pass = rawurlencode($pass); } return [$user, $pass]; }
[ "private", "static", "function", "fetchUserInfo", "(", "array", "$", "server", ")", ":", "array", "{", "$", "server", "+=", "[", "'PHP_AUTH_USER'", "=>", "null", ",", "'PHP_AUTH_PW'", "=>", "null", ",", "'HTTP_AUTHORIZATION'", "=>", "''", "]", ";", "$", "u...
Returns the environment user info.
[ "Returns", "the", "environment", "user", "info", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L762-L784
thephpleague/uri-schemes
src/Uri.php
Uri.fetchHostname
private static function fetchHostname(array $server): array { $server += ['SERVER_PORT' => null]; if (null !== $server['SERVER_PORT']) { $server['SERVER_PORT'] = (int) $server['SERVER_PORT']; } if (isset($server['HTTP_HOST'])) { preg_match(',^(?<host>(\[.*\]|[^:])*)(\:(?<port>[^/?\#]*))?$,x', $server['HTTP_HOST'], $matches); return [ $matches['host'], isset($matches['port']) ? (int) $matches['port'] : $server['SERVER_PORT'], ]; } if (!isset($server['SERVER_ADDR'])) { throw new SyntaxError('The host could not be detected'); } if (false === filter_var($server['SERVER_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $server['SERVER_ADDR'] = '['.$server['SERVER_ADDR'].']'; } return [$server['SERVER_ADDR'], $server['SERVER_PORT']]; }
php
private static function fetchHostname(array $server): array { $server += ['SERVER_PORT' => null]; if (null !== $server['SERVER_PORT']) { $server['SERVER_PORT'] = (int) $server['SERVER_PORT']; } if (isset($server['HTTP_HOST'])) { preg_match(',^(?<host>(\[.*\]|[^:])*)(\:(?<port>[^/?\#]*))?$,x', $server['HTTP_HOST'], $matches); return [ $matches['host'], isset($matches['port']) ? (int) $matches['port'] : $server['SERVER_PORT'], ]; } if (!isset($server['SERVER_ADDR'])) { throw new SyntaxError('The host could not be detected'); } if (false === filter_var($server['SERVER_ADDR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $server['SERVER_ADDR'] = '['.$server['SERVER_ADDR'].']'; } return [$server['SERVER_ADDR'], $server['SERVER_PORT']]; }
[ "private", "static", "function", "fetchHostname", "(", "array", "$", "server", ")", ":", "array", "{", "$", "server", "+=", "[", "'SERVER_PORT'", "=>", "null", "]", ";", "if", "(", "null", "!==", "$", "server", "[", "'SERVER_PORT'", "]", ")", "{", "$",...
Returns the environment host. @throws SyntaxError If the host can not be detected
[ "Returns", "the", "environment", "host", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L791-L816
thephpleague/uri-schemes
src/Uri.php
Uri.fetchRequestUri
private static function fetchRequestUri(array $server): array { $server += ['IIS_WasUrlRewritten' => null, 'UNENCODED_URL' => '', 'PHP_SELF' => '', 'QUERY_STRING' => null]; if ('1' === $server['IIS_WasUrlRewritten'] && '' !== $server['UNENCODED_URL']) { return explode('?', $server['UNENCODED_URL'], 2) + [1 => null]; } if (isset($server['REQUEST_URI'])) { [$path, ] = explode('?', $server['REQUEST_URI'], 2); $query = ('' !== $server['QUERY_STRING']) ? $server['QUERY_STRING'] : null; return [$path, $query]; } return [$server['PHP_SELF'], $server['QUERY_STRING']]; }
php
private static function fetchRequestUri(array $server): array { $server += ['IIS_WasUrlRewritten' => null, 'UNENCODED_URL' => '', 'PHP_SELF' => '', 'QUERY_STRING' => null]; if ('1' === $server['IIS_WasUrlRewritten'] && '' !== $server['UNENCODED_URL']) { return explode('?', $server['UNENCODED_URL'], 2) + [1 => null]; } if (isset($server['REQUEST_URI'])) { [$path, ] = explode('?', $server['REQUEST_URI'], 2); $query = ('' !== $server['QUERY_STRING']) ? $server['QUERY_STRING'] : null; return [$path, $query]; } return [$server['PHP_SELF'], $server['QUERY_STRING']]; }
[ "private", "static", "function", "fetchRequestUri", "(", "array", "$", "server", ")", ":", "array", "{", "$", "server", "+=", "[", "'IIS_WasUrlRewritten'", "=>", "null", ",", "'UNENCODED_URL'", "=>", "''", ",", "'PHP_SELF'", "=>", "''", ",", "'QUERY_STRING'", ...
Returns the environment path.
[ "Returns", "the", "environment", "path", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L821-L836
thephpleague/uri-schemes
src/Uri.php
Uri.setAuthority
private function setAuthority(): ?string { $authority = null; if (null !== $this->user_info) { $authority = $this->user_info.'@'; } if (null !== $this->host) { $authority .= $this->host; } if (null !== $this->port) { $authority .= ':'.$this->port; } return $authority; }
php
private function setAuthority(): ?string { $authority = null; if (null !== $this->user_info) { $authority = $this->user_info.'@'; } if (null !== $this->host) { $authority .= $this->host; } if (null !== $this->port) { $authority .= ':'.$this->port; } return $authority; }
[ "private", "function", "setAuthority", "(", ")", ":", "?", "string", "{", "$", "authority", "=", "null", ";", "if", "(", "null", "!==", "$", "this", "->", "user_info", ")", "{", "$", "authority", "=", "$", "this", "->", "user_info", ".", "'@'", ";", ...
Generate the URI authority part.
[ "Generate", "the", "URI", "authority", "part", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L842-L858
thephpleague/uri-schemes
src/Uri.php
Uri.formatPath
private function formatPath(string $path): string { $path = $this->formatDataPath($path); static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/}{]++\|%(?![A-Fa-f0-9]{2}))/'; $path = (string) preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $path); return $this->formatFilePath($path); }
php
private function formatPath(string $path): string { $path = $this->formatDataPath($path); static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/}{]++\|%(?![A-Fa-f0-9]{2}))/'; $path = (string) preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $path); return $this->formatFilePath($path); }
[ "private", "function", "formatPath", "(", "string", "$", "path", ")", ":", "string", "{", "$", "path", "=", "$", "this", "->", "formatDataPath", "(", "$", "path", ")", ";", "static", "$", "pattern", "=", "'/(?:[^'", ".", "self", "::", "REGEXP_CHARS_UNRES...
Format the Path component.
[ "Format", "the", "Path", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L863-L872
thephpleague/uri-schemes
src/Uri.php
Uri.formatDataPath
private function formatDataPath(string $path): string { if ('data' !== $this->scheme) { return $path; } if ('' == $path) { return 'text/plain;charset=us-ascii,'; } if (false === mb_detect_encoding($path, 'US-ASCII', true) || false === strpos($path, ',')) { throw new SyntaxError(sprintf('The path `%s` is invalid according to RFC2937', $path)); } $parts = explode(',', $path, 2) + [1 => null]; $mediatype = explode(';', (string) $parts[0], 2) + [1 => null]; $data = (string) $parts[1]; $mimetype = $mediatype[0]; if (null === $mimetype || '' === $mimetype) { $mimetype = 'text/plain'; } $parameters = $mediatype[1]; if (null === $parameters || '' === $parameters) { $parameters = 'charset=us-ascii'; } $this->assertValidPath($mimetype, $parameters, $data); return $mimetype.';'.$parameters.','.$data; }
php
private function formatDataPath(string $path): string { if ('data' !== $this->scheme) { return $path; } if ('' == $path) { return 'text/plain;charset=us-ascii,'; } if (false === mb_detect_encoding($path, 'US-ASCII', true) || false === strpos($path, ',')) { throw new SyntaxError(sprintf('The path `%s` is invalid according to RFC2937', $path)); } $parts = explode(',', $path, 2) + [1 => null]; $mediatype = explode(';', (string) $parts[0], 2) + [1 => null]; $data = (string) $parts[1]; $mimetype = $mediatype[0]; if (null === $mimetype || '' === $mimetype) { $mimetype = 'text/plain'; } $parameters = $mediatype[1]; if (null === $parameters || '' === $parameters) { $parameters = 'charset=us-ascii'; } $this->assertValidPath($mimetype, $parameters, $data); return $mimetype.';'.$parameters.','.$data; }
[ "private", "function", "formatDataPath", "(", "string", "$", "path", ")", ":", "string", "{", "if", "(", "'data'", "!==", "$", "this", "->", "scheme", ")", "{", "return", "$", "path", ";", "}", "if", "(", "''", "==", "$", "path", ")", "{", "return"...
Filter the Path component. @see https://tools.ietf.org/html/rfc2397 @throws SyntaxError If the path is not compliant with RFC2397
[ "Filter", "the", "Path", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L881-L911
thephpleague/uri-schemes
src/Uri.php
Uri.assertValidPath
private function assertValidPath(string $mimetype, string $parameters, string $data): void { if (1 !== preg_match(self::REGEXP_MIMETYPE, $mimetype)) { throw new SyntaxError(sprintf('The path mimetype `%s` is invalid', $mimetype)); } $is_binary = 1 === preg_match(self::REGEXP_BINARY, $parameters, $matches); if ($is_binary) { $parameters = substr($parameters, 0, - strlen($matches[0])); } $res = array_filter(array_filter(explode(';', $parameters), [$this, 'validateParameter'])); if ([] !== $res) { throw new SyntaxError(sprintf('The path paremeters `%s` is invalid', $parameters)); } if (!$is_binary) { return; } $res = base64_decode($data, true); if (false === $res || $data !== base64_encode($res)) { throw new SyntaxError(sprintf('The path data `%s` is invalid', $data)); } }
php
private function assertValidPath(string $mimetype, string $parameters, string $data): void { if (1 !== preg_match(self::REGEXP_MIMETYPE, $mimetype)) { throw new SyntaxError(sprintf('The path mimetype `%s` is invalid', $mimetype)); } $is_binary = 1 === preg_match(self::REGEXP_BINARY, $parameters, $matches); if ($is_binary) { $parameters = substr($parameters, 0, - strlen($matches[0])); } $res = array_filter(array_filter(explode(';', $parameters), [$this, 'validateParameter'])); if ([] !== $res) { throw new SyntaxError(sprintf('The path paremeters `%s` is invalid', $parameters)); } if (!$is_binary) { return; } $res = base64_decode($data, true); if (false === $res || $data !== base64_encode($res)) { throw new SyntaxError(sprintf('The path data `%s` is invalid', $data)); } }
[ "private", "function", "assertValidPath", "(", "string", "$", "mimetype", ",", "string", "$", "parameters", ",", "string", "$", "data", ")", ":", "void", "{", "if", "(", "1", "!==", "preg_match", "(", "self", "::", "REGEXP_MIMETYPE", ",", "$", "mimetype", ...
Assert the path is a compliant with RFC2397. @see https://tools.ietf.org/html/rfc2397 @throws SyntaxError If the mediatype or the data are not compliant with the RFC2397
[ "Assert", "the", "path", "is", "a", "compliant", "with", "RFC2397", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L920-L944
thephpleague/uri-schemes
src/Uri.php
Uri.formatQueryAndFragment
private function formatQueryAndFragment(?string $component): ?string { if (null === $component || '' === $component) { return $component; } static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/'; return preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $component); }
php
private function formatQueryAndFragment(?string $component): ?string { if (null === $component || '' === $component) { return $component; } static $pattern = '/(?:[^'.self::REGEXP_CHARS_UNRESERVED.self::REGEXP_CHARS_SUBDELIM.'%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/'; return preg_replace_callback($pattern, [Uri::class, 'urlEncodeMatch'], $component); }
[ "private", "function", "formatQueryAndFragment", "(", "?", "string", "$", "component", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "component", "||", "''", "===", "$", "component", ")", "{", "return", "$", "component", ";", "}", "static"...
Format the Query or the Fragment component. Returns a array containing: <ul> <li> the formatted component (a string or null)</li> <li> a boolean flag telling wether the delimiter is to be added to the component when building the URI string representation</li> </ul> @param ?string $component
[ "Format", "the", "Query", "or", "the", "Fragment", "component", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L981-L989
thephpleague/uri-schemes
src/Uri.php
Uri.assertValidState
private function assertValidState(): void { if (null !== $this->authority && ('' !== $this->path && '/' !== $this->path[0])) { throw new SyntaxError('If an authority is present the path must be empty or start with a `/`'); } if (null === $this->authority && 0 === strpos($this->path, '//')) { throw new SyntaxError(sprintf('If there is no authority the path `%s` can not start with a `//`', $this->path)); } $pos = strpos($this->path, ':'); if (null === $this->authority && null === $this->scheme && false !== $pos && false === strpos(substr($this->path, 0, $pos), '/') ) { throw new SyntaxError('In absence of a scheme and an authority the first path segment cannot contain a colon (":") character.'); } $validationMethod = self::SCHEME_VALIDATION_METHOD[$this->scheme] ?? null; if (null === $validationMethod || true === $this->$validationMethod()) { $this->uri = null; return; } throw new SyntaxError(sprintf('The uri `%s` is invalid for the data scheme', (string) $this)); }
php
private function assertValidState(): void { if (null !== $this->authority && ('' !== $this->path && '/' !== $this->path[0])) { throw new SyntaxError('If an authority is present the path must be empty or start with a `/`'); } if (null === $this->authority && 0 === strpos($this->path, '//')) { throw new SyntaxError(sprintf('If there is no authority the path `%s` can not start with a `//`', $this->path)); } $pos = strpos($this->path, ':'); if (null === $this->authority && null === $this->scheme && false !== $pos && false === strpos(substr($this->path, 0, $pos), '/') ) { throw new SyntaxError('In absence of a scheme and an authority the first path segment cannot contain a colon (":") character.'); } $validationMethod = self::SCHEME_VALIDATION_METHOD[$this->scheme] ?? null; if (null === $validationMethod || true === $this->$validationMethod()) { $this->uri = null; return; } throw new SyntaxError(sprintf('The uri `%s` is invalid for the data scheme', (string) $this)); }
[ "private", "function", "assertValidState", "(", ")", ":", "void", "{", "if", "(", "null", "!==", "$", "this", "->", "authority", "&&", "(", "''", "!==", "$", "this", "->", "path", "&&", "'/'", "!==", "$", "this", "->", "path", "[", "0", "]", ")", ...
assert the URI internal state is valid. @see https://tools.ietf.org/html/rfc3986#section-3 @see https://tools.ietf.org/html/rfc3986#section-3.3 @throws SyntaxError if the URI is in an invalid state according to RFC3986 @throws SyntaxError if the URI is in an invalid state according to scheme specific rules
[ "assert", "the", "URI", "internal", "state", "is", "valid", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1000-L1027
thephpleague/uri-schemes
src/Uri.php
Uri.isUriWithSchemeAndPathOnly
private function isUriWithSchemeAndPathOnly() { return null === $this->authority && null === $this->query && null === $this->fragment; }
php
private function isUriWithSchemeAndPathOnly() { return null === $this->authority && null === $this->query && null === $this->fragment; }
[ "private", "function", "isUriWithSchemeAndPathOnly", "(", ")", "{", "return", "null", "===", "$", "this", "->", "authority", "&&", "null", "===", "$", "this", "->", "query", "&&", "null", "===", "$", "this", "->", "fragment", ";", "}" ]
URI validation for URI schemes which allows only scheme and path components.
[ "URI", "validation", "for", "URI", "schemes", "which", "allows", "only", "scheme", "and", "path", "components", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1032-L1037
thephpleague/uri-schemes
src/Uri.php
Uri.isUriWithSchemeHostAndPathOnly
private function isUriWithSchemeHostAndPathOnly() { return null === $this->user_info && null === $this->port && null === $this->query && null === $this->fragment && !('' != $this->scheme && null === $this->host); }
php
private function isUriWithSchemeHostAndPathOnly() { return null === $this->user_info && null === $this->port && null === $this->query && null === $this->fragment && !('' != $this->scheme && null === $this->host); }
[ "private", "function", "isUriWithSchemeHostAndPathOnly", "(", ")", "{", "return", "null", "===", "$", "this", "->", "user_info", "&&", "null", "===", "$", "this", "->", "port", "&&", "null", "===", "$", "this", "->", "query", "&&", "null", "===", "$", "t...
URI validation for URI schemes which allows only scheme, host and path components.
[ "URI", "validation", "for", "URI", "schemes", "which", "allows", "only", "scheme", "host", "and", "path", "components", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1042-L1049
thephpleague/uri-schemes
src/Uri.php
Uri.getUriString
private function getUriString( ?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment ): string { if (null !== $scheme) { $scheme = $scheme.':'; } if (null !== $authority) { $authority = '//'.$authority; } if (null !== $query) { $query = '?'.$query; } if (null !== $fragment) { $fragment = '#'.$fragment; } return $scheme.$authority.$path.$query.$fragment; }
php
private function getUriString( ?string $scheme, ?string $authority, string $path, ?string $query, ?string $fragment ): string { if (null !== $scheme) { $scheme = $scheme.':'; } if (null !== $authority) { $authority = '//'.$authority; } if (null !== $query) { $query = '?'.$query; } if (null !== $fragment) { $fragment = '#'.$fragment; } return $scheme.$authority.$path.$query.$fragment; }
[ "private", "function", "getUriString", "(", "?", "string", "$", "scheme", ",", "?", "string", "$", "authority", ",", "string", "$", "path", ",", "?", "string", "$", "query", ",", "?", "string", "$", "fragment", ")", ":", "string", "{", "if", "(", "nu...
Generate the URI string representation from its components. @see https://tools.ietf.org/html/rfc3986#section-5.3 @param ?string $scheme @param ?string $authority @param ?string $query @param ?string $fragment
[ "Generate", "the", "URI", "string", "representation", "from", "its", "components", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1087-L1111
thephpleague/uri-schemes
src/Uri.php
Uri.getUser
public function getUser(): ?string { if (null === $this->user_info) { return null; } [$user, ] = explode(':', $this->user_info, 2); return $user; }
php
public function getUser(): ?string { if (null === $this->user_info) { return null; } [$user, ] = explode(':', $this->user_info, 2); return $user; }
[ "public", "function", "getUser", "(", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "this", "->", "user_info", ")", "{", "return", "null", ";", "}", "[", "$", "user", ",", "]", "=", "explode", "(", "':'", ",", "$", "this", "->", ...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1180-L1189
thephpleague/uri-schemes
src/Uri.php
Uri.getPass
public function getPass(): ?string { if (null === $this->user_info) { return null; } [$user, $pass] = explode(':', $this->user_info, 2) + [1 => null]; return $pass; }
php
public function getPass(): ?string { if (null === $this->user_info) { return null; } [$user, $pass] = explode(':', $this->user_info, 2) + [1 => null]; return $pass; }
[ "public", "function", "getPass", "(", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "this", "->", "user_info", ")", "{", "return", "null", ";", "}", "[", "$", "user", ",", "$", "pass", "]", "=", "explode", "(", "':'", ",", "$", "...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1194-L1203
thephpleague/uri-schemes
src/Uri.php
Uri.withScheme
public function withScheme($scheme): self { $scheme = $this->formatScheme($this->filterString($scheme)); if ($scheme === $this->scheme) { return $this; } $clone = clone $this; $clone->scheme = $scheme; $clone->port = $clone->formatPort($clone->port); $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
php
public function withScheme($scheme): self { $scheme = $this->formatScheme($this->filterString($scheme)); if ($scheme === $this->scheme) { return $this; } $clone = clone $this; $clone->scheme = $scheme; $clone->port = $clone->formatPort($clone->port); $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
[ "public", "function", "withScheme", "(", "$", "scheme", ")", ":", "self", "{", "$", "scheme", "=", "$", "this", "->", "formatScheme", "(", "$", "this", "->", "filterString", "(", "$", "scheme", ")", ")", ";", "if", "(", "$", "scheme", "===", "$", "...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1248-L1262
thephpleague/uri-schemes
src/Uri.php
Uri.filterString
private function filterString($str): ?string { if (null === $str) { return $str; } if (!is_scalar($str) && !method_exists($str, '__toString')) { throw new TypeError(sprintf('The component must be a string, a scalar or a stringable object %s given', gettype($str))); } $str = (string) $str; if (1 !== preg_match(self::REGEXP_INVALID_CHARS, $str)) { return $str; } throw new SyntaxError(sprintf('The component `%s` contains invalid characters', $str)); }
php
private function filterString($str): ?string { if (null === $str) { return $str; } if (!is_scalar($str) && !method_exists($str, '__toString')) { throw new TypeError(sprintf('The component must be a string, a scalar or a stringable object %s given', gettype($str))); } $str = (string) $str; if (1 !== preg_match(self::REGEXP_INVALID_CHARS, $str)) { return $str; } throw new SyntaxError(sprintf('The component `%s` contains invalid characters', $str)); }
[ "private", "function", "filterString", "(", "$", "str", ")", ":", "?", "string", "{", "if", "(", "null", "===", "$", "str", ")", "{", "return", "$", "str", ";", "}", "if", "(", "!", "is_scalar", "(", "$", "str", ")", "&&", "!", "method_exists", "...
Filter a string. @param mixed $str the value to evaluate as a string @throws SyntaxError if the submitted data can not be converted to string
[ "Filter", "a", "string", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1271-L1287
thephpleague/uri-schemes
src/Uri.php
Uri.withUserInfo
public function withUserInfo($user, $password = null): self { $user_info = null; $user = $this->filterString($user); if (null !== $password) { $password = $this->filterString($password); } if ('' !== $user) { $user_info = $this->formatUserInfo($user, $password); } if ($user_info === $this->user_info) { return $this; } $clone = clone $this; $clone->user_info = $user_info; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
php
public function withUserInfo($user, $password = null): self { $user_info = null; $user = $this->filterString($user); if (null !== $password) { $password = $this->filterString($password); } if ('' !== $user) { $user_info = $this->formatUserInfo($user, $password); } if ($user_info === $this->user_info) { return $this; } $clone = clone $this; $clone->user_info = $user_info; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
[ "public", "function", "withUserInfo", "(", "$", "user", ",", "$", "password", "=", "null", ")", ":", "self", "{", "$", "user_info", "=", "null", ";", "$", "user", "=", "$", "this", "->", "filterString", "(", "$", "user", ")", ";", "if", "(", "null"...
{@inhertidoc}. @param null|mixed $password
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1293-L1315
thephpleague/uri-schemes
src/Uri.php
Uri.withHost
public function withHost($host): self { $host = $this->formatHost($this->filterString($host)); if ($host === $this->host) { return $this; } $clone = clone $this; $clone->host = $host; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
php
public function withHost($host): self { $host = $this->formatHost($this->filterString($host)); if ($host === $this->host) { return $this; } $clone = clone $this; $clone->host = $host; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
[ "public", "function", "withHost", "(", "$", "host", ")", ":", "self", "{", "$", "host", "=", "$", "this", "->", "formatHost", "(", "$", "this", "->", "filterString", "(", "$", "host", ")", ")", ";", "if", "(", "$", "host", "===", "$", "this", "->...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1320-L1333
thephpleague/uri-schemes
src/Uri.php
Uri.withPort
public function withPort($port): self { $port = $this->formatPort($port); if ($port === $this->port) { return $this; } $clone = clone $this; $clone->port = $port; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
php
public function withPort($port): self { $port = $this->formatPort($port); if ($port === $this->port) { return $this; } $clone = clone $this; $clone->port = $port; $clone->authority = $clone->setAuthority(); $clone->assertValidState(); return $clone; }
[ "public", "function", "withPort", "(", "$", "port", ")", ":", "self", "{", "$", "port", "=", "$", "this", "->", "formatPort", "(", "$", "port", ")", ";", "if", "(", "$", "port", "===", "$", "this", "->", "port", ")", "{", "return", "$", "this", ...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1338-L1351
thephpleague/uri-schemes
src/Uri.php
Uri.withPath
public function withPath($path): self { $path = $this->filterString($path); if (null === $path) { throw new TypeError('A path must be a string NULL given'); } $path = $this->formatPath($path); if ($path === $this->path) { return $this; } $clone = clone $this; $clone->path = $path; $clone->assertValidState(); return $clone; }
php
public function withPath($path): self { $path = $this->filterString($path); if (null === $path) { throw new TypeError('A path must be a string NULL given'); } $path = $this->formatPath($path); if ($path === $this->path) { return $this; } $clone = clone $this; $clone->path = $path; $clone->assertValidState(); return $clone; }
[ "public", "function", "withPath", "(", "$", "path", ")", ":", "self", "{", "$", "path", "=", "$", "this", "->", "filterString", "(", "$", "path", ")", ";", "if", "(", "null", "===", "$", "path", ")", "{", "throw", "new", "TypeError", "(", "'A path ...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1356-L1373
thephpleague/uri-schemes
src/Uri.php
Uri.withQuery
public function withQuery($query): self { $query = $this->formatQueryAndFragment($this->filterString($query)); if ($query === $this->query) { return $this; } $clone = clone $this; $clone->query = $query; $clone->assertValidState(); return $clone; }
php
public function withQuery($query): self { $query = $this->formatQueryAndFragment($this->filterString($query)); if ($query === $this->query) { return $this; } $clone = clone $this; $clone->query = $query; $clone->assertValidState(); return $clone; }
[ "public", "function", "withQuery", "(", "$", "query", ")", ":", "self", "{", "$", "query", "=", "$", "this", "->", "formatQueryAndFragment", "(", "$", "this", "->", "filterString", "(", "$", "query", ")", ")", ";", "if", "(", "$", "query", "===", "$"...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1378-L1390
thephpleague/uri-schemes
src/Uri.php
Uri.withFragment
public function withFragment($fragment): self { $fragment = $this->formatQueryAndFragment($this->filterString($fragment)); if ($fragment === $this->fragment) { return $this; } $clone = clone $this; $clone->fragment = $fragment; $clone->assertValidState(); return $clone; }
php
public function withFragment($fragment): self { $fragment = $this->formatQueryAndFragment($this->filterString($fragment)); if ($fragment === $this->fragment) { return $this; } $clone = clone $this; $clone->fragment = $fragment; $clone->assertValidState(); return $clone; }
[ "public", "function", "withFragment", "(", "$", "fragment", ")", ":", "self", "{", "$", "fragment", "=", "$", "this", "->", "formatQueryAndFragment", "(", "$", "this", "->", "filterString", "(", "$", "fragment", ")", ")", ";", "if", "(", "$", "fragment",...
{@inhertidoc}.
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Uri.php#L1395-L1407
thephpleague/uri-schemes
src/Http.php
Http.validate
private function validate(UriInterface $uri): void { $scheme = $uri->getScheme(); if (null === $scheme && '' === $uri->getHost()) { throw new SyntaxError(sprintf('an URI without scheme can not contains a empty host string according to PSR-7: %s', (string) $uri)); } $port = $uri->getPort(); if (null !== $port && ($port < 0 || $port > 65535)) { throw new SyntaxError(sprintf('The URI port is outside the established TCP and UDP port ranges: %s', (string) $uri->getPort())); } }
php
private function validate(UriInterface $uri): void { $scheme = $uri->getScheme(); if (null === $scheme && '' === $uri->getHost()) { throw new SyntaxError(sprintf('an URI without scheme can not contains a empty host string according to PSR-7: %s', (string) $uri)); } $port = $uri->getPort(); if (null !== $port && ($port < 0 || $port > 65535)) { throw new SyntaxError(sprintf('The URI port is outside the established TCP and UDP port ranges: %s', (string) $uri->getPort())); } }
[ "private", "function", "validate", "(", "UriInterface", "$", "uri", ")", ":", "void", "{", "$", "scheme", "=", "$", "uri", "->", "getScheme", "(", ")", ";", "if", "(", "null", "===", "$", "scheme", "&&", "''", "===", "$", "uri", "->", "getHost", "(...
Validate the submitted uri against PSR-7 UriInterface. @throws SyntaxError if the given URI does not follow PSR-7 UriInterface rules
[ "Validate", "the", "submitted", "uri", "against", "PSR", "-", "7", "UriInterface", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L45-L56
thephpleague/uri-schemes
src/Http.php
Http.create
public static function create($uri, $base_uri = null): self { return new self(Uri::create($uri, $base_uri)); }
php
public static function create($uri, $base_uri = null): self { return new self(Uri::create($uri, $base_uri)); }
[ "public", "static", "function", "create", "(", "$", "uri", ",", "$", "base_uri", "=", "null", ")", ":", "self", "{", "return", "new", "self", "(", "Uri", "::", "create", "(", "$", "uri", ",", "$", "base_uri", ")", ")", ";", "}" ]
Create a new instance from a URI and a Base URI. The returned URI must be absolute. @param mixed $uri the input URI to create @param mixed $base_uri the base URI used for reference
[ "Create", "a", "new", "instance", "from", "a", "URI", "and", "a", "Base", "URI", "." ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L97-L100
thephpleague/uri-schemes
src/Http.php
Http.withScheme
public function withScheme($scheme): self { $scheme = $this->filterInput($scheme); if ('' === $scheme) { $scheme = null; } $uri = $this->uri->withScheme($scheme); if ($uri->getScheme() === $this->uri->getScheme()) { return $this; } return new self($uri); }
php
public function withScheme($scheme): self { $scheme = $this->filterInput($scheme); if ('' === $scheme) { $scheme = null; } $uri = $this->uri->withScheme($scheme); if ($uri->getScheme() === $this->uri->getScheme()) { return $this; } return new self($uri); }
[ "public", "function", "withScheme", "(", "$", "scheme", ")", ":", "self", "{", "$", "scheme", "=", "$", "this", "->", "filterInput", "(", "$", "scheme", ")", ";", "if", "(", "''", "===", "$", "scheme", ")", "{", "$", "scheme", "=", "null", ";", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L169-L182
thephpleague/uri-schemes
src/Http.php
Http.withUserInfo
public function withUserInfo($user, $password = null): self { $user = $this->filterInput($user); if ('' === $user) { $user = null; } $uri = $this->uri->withUserInfo($user, $password); if ($uri->getUserInfo() === $this->uri->getUserInfo()) { return $this; } return new self($uri); }
php
public function withUserInfo($user, $password = null): self { $user = $this->filterInput($user); if ('' === $user) { $user = null; } $uri = $this->uri->withUserInfo($user, $password); if ($uri->getUserInfo() === $this->uri->getUserInfo()) { return $this; } return new self($uri); }
[ "public", "function", "withUserInfo", "(", "$", "user", ",", "$", "password", "=", "null", ")", ":", "self", "{", "$", "user", "=", "$", "this", "->", "filterInput", "(", "$", "user", ")", ";", "if", "(", "''", "===", "$", "user", ")", "{", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L205-L218
thephpleague/uri-schemes
src/Http.php
Http.withHost
public function withHost($host): self { $host = $this->filterInput($host); if ('' === $host) { $host = null; } $uri = $this->uri->withHost($host); if ($uri->getHost() === $this->uri->getHost()) { return $this; } return new self($uri); }
php
public function withHost($host): self { $host = $this->filterInput($host); if ('' === $host) { $host = null; } $uri = $this->uri->withHost($host); if ($uri->getHost() === $this->uri->getHost()) { return $this; } return new self($uri); }
[ "public", "function", "withHost", "(", "$", "host", ")", ":", "self", "{", "$", "host", "=", "$", "this", "->", "filterInput", "(", "$", "host", ")", ";", "if", "(", "''", "===", "$", "host", ")", "{", "$", "host", "=", "null", ";", "}", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L223-L236
thephpleague/uri-schemes
src/Http.php
Http.withPort
public function withPort($port): self { $uri = $this->uri->withPort($port); if ($uri->getPort() === $this->uri->getPort()) { return $this; } return new self($uri); }
php
public function withPort($port): self { $uri = $this->uri->withPort($port); if ($uri->getPort() === $this->uri->getPort()) { return $this; } return new self($uri); }
[ "public", "function", "withPort", "(", "$", "port", ")", ":", "self", "{", "$", "uri", "=", "$", "this", "->", "uri", "->", "withPort", "(", "$", "port", ")", ";", "if", "(", "$", "uri", "->", "getPort", "(", ")", "===", "$", "this", "->", "uri...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L241-L249
thephpleague/uri-schemes
src/Http.php
Http.withPath
public function withPath($path): self { $uri = $this->uri->withPath($path); if ($uri->getPath() === $this->uri->getPath()) { return $this; } return new self($uri); }
php
public function withPath($path): self { $uri = $this->uri->withPath($path); if ($uri->getPath() === $this->uri->getPath()) { return $this; } return new self($uri); }
[ "public", "function", "withPath", "(", "$", "path", ")", ":", "self", "{", "$", "uri", "=", "$", "this", "->", "uri", "->", "withPath", "(", "$", "path", ")", ";", "if", "(", "$", "uri", "->", "getPath", "(", ")", "===", "$", "this", "->", "uri...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L254-L262
thephpleague/uri-schemes
src/Http.php
Http.withQuery
public function withQuery($query): self { $query = $this->filterInput($query); if ('' === $query) { $query = null; } $uri = $this->uri->withQuery($query); if ($uri->getQuery() === $this->uri->getQuery()) { return $this; } return new self($uri); }
php
public function withQuery($query): self { $query = $this->filterInput($query); if ('' === $query) { $query = null; } $uri = $this->uri->withQuery($query); if ($uri->getQuery() === $this->uri->getQuery()) { return $this; } return new self($uri); }
[ "public", "function", "withQuery", "(", "$", "query", ")", ":", "self", "{", "$", "query", "=", "$", "this", "->", "filterInput", "(", "$", "query", ")", ";", "if", "(", "''", "===", "$", "query", ")", "{", "$", "query", "=", "null", ";", "}", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L267-L280
thephpleague/uri-schemes
src/Http.php
Http.withFragment
public function withFragment($fragment): self { $fragment = $this->filterInput($fragment); if ('' === $fragment) { $fragment = null; } $uri = $this->uri->withFragment($fragment); if ($uri->getFragment() === $this->uri->getFragment()) { return $this; } return new self($uri); }
php
public function withFragment($fragment): self { $fragment = $this->filterInput($fragment); if ('' === $fragment) { $fragment = null; } $uri = $this->uri->withFragment($fragment); if ($uri->getFragment() === $this->uri->getFragment()) { return $this; } return new self($uri); }
[ "public", "function", "withFragment", "(", "$", "fragment", ")", ":", "self", "{", "$", "fragment", "=", "$", "this", "->", "filterInput", "(", "$", "fragment", ")", ";", "if", "(", "''", "===", "$", "fragment", ")", "{", "$", "fragment", "=", "null"...
{@inheritdoc}
[ "{" ]
train
https://github.com/thephpleague/uri-schemes/blob/149ffe2dea12bbeac93db8494a6b7f5f9eed21e0/src/Http.php#L285-L298
stil/curl-easy
src/RequestsQueue.php
RequestsQueue.read
protected function read() { $n = 0; while ($info = curl_multi_info_read($this->mh)) { $n++; $request = $this->queue[(int)$info['handle']]; $result = $info['result']; curl_multi_remove_handle($this->mh, $request->getHandle()); unset($this->running[$request->getUID()]); $this->detach($request); $event = new Event(); $event->request = $request; $event->response = new Response($request, curl_multi_getcontent($request->getHandle())); if ($result !== CURLE_OK) { $event->response->setError(new Error(curl_error($request->getHandle()), $result)); } $event->queue = $this; $this->dispatch('complete', $event); $request->dispatch('complete', $event); } return $n; }
php
protected function read() { $n = 0; while ($info = curl_multi_info_read($this->mh)) { $n++; $request = $this->queue[(int)$info['handle']]; $result = $info['result']; curl_multi_remove_handle($this->mh, $request->getHandle()); unset($this->running[$request->getUID()]); $this->detach($request); $event = new Event(); $event->request = $request; $event->response = new Response($request, curl_multi_getcontent($request->getHandle())); if ($result !== CURLE_OK) { $event->response->setError(new Error(curl_error($request->getHandle()), $result)); } $event->queue = $this; $this->dispatch('complete', $event); $request->dispatch('complete', $event); } return $n; }
[ "protected", "function", "read", "(", ")", "{", "$", "n", "=", "0", ";", "while", "(", "$", "info", "=", "curl_multi_info_read", "(", "$", "this", "->", "mh", ")", ")", "{", "$", "n", "++", ";", "$", "request", "=", "$", "this", "->", "queue", ...
Processes handles which are ready and removes them from pool. @return int Amount of requests completed
[ "Processes", "handles", "which", "are", "ready", "and", "removes", "them", "from", "pool", "." ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/RequestsQueue.php#L112-L136
stil/curl-easy
src/RequestsQueue.php
RequestsQueue.getRequestsNotRunning
protected function getRequestsNotRunning() { $map = $this->queue; foreach ($this->running as $k => $v) unset($map[$k]); return $map; }
php
protected function getRequestsNotRunning() { $map = $this->queue; foreach ($this->running as $k => $v) unset($map[$k]); return $map; }
[ "protected", "function", "getRequestsNotRunning", "(", ")", "{", "$", "map", "=", "$", "this", "->", "queue", ";", "foreach", "(", "$", "this", "->", "running", "as", "$", "k", "=>", "$", "v", ")", "unset", "(", "$", "map", "[", "$", "k", "]", ")...
Returns requests present in $queue but not in $running @return Request[] Array of requests
[ "Returns", "requests", "present", "in", "$queue", "but", "not", "in", "$running" ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/RequestsQueue.php#L165-L170
stil/curl-easy
src/RequestsQueue.php
RequestsQueue.socketPerform
public function socketPerform() { if ($this->count() == 0) { throw new Exception('Cannot perform if there are no requests in queue.'); } $notRunning = $this->getRequestsNotRunning(); do { /** * Apply cURL options to new requests */ foreach ($notRunning as $request) { $this->getDefaultOptions()->applyTo($request); $request->getOptions()->applyTo($request); curl_multi_add_handle($this->mh, $request->getHandle()); $this->running[$request->getUID()] = $request; } $runningHandles = null; do { // http://curl.haxx.se/libcurl/c/curl_multi_perform.html // If an added handle fails very quickly, it may never be counted as a running_handle. $mrc = curl_multi_exec($this->mh, $runningHandles); } while ($mrc === CURLM_CALL_MULTI_PERFORM); if ($runningHandles < count($this->running)) { $this->read(); } $notRunning = $this->getRequestsNotRunning(); } while (count($notRunning) > 0); // Why the loop? New requests might be added at runtime on 'complete' event. // So we need to attach them to curl_multi handle immediately. return $this->count() > 0; }
php
public function socketPerform() { if ($this->count() == 0) { throw new Exception('Cannot perform if there are no requests in queue.'); } $notRunning = $this->getRequestsNotRunning(); do { /** * Apply cURL options to new requests */ foreach ($notRunning as $request) { $this->getDefaultOptions()->applyTo($request); $request->getOptions()->applyTo($request); curl_multi_add_handle($this->mh, $request->getHandle()); $this->running[$request->getUID()] = $request; } $runningHandles = null; do { // http://curl.haxx.se/libcurl/c/curl_multi_perform.html // If an added handle fails very quickly, it may never be counted as a running_handle. $mrc = curl_multi_exec($this->mh, $runningHandles); } while ($mrc === CURLM_CALL_MULTI_PERFORM); if ($runningHandles < count($this->running)) { $this->read(); } $notRunning = $this->getRequestsNotRunning(); } while (count($notRunning) > 0); // Why the loop? New requests might be added at runtime on 'complete' event. // So we need to attach them to curl_multi handle immediately. return $this->count() > 0; }
[ "public", "function", "socketPerform", "(", ")", "{", "if", "(", "$", "this", "->", "count", "(", ")", "==", "0", ")", "{", "throw", "new", "Exception", "(", "'Cannot perform if there are no requests in queue.'", ")", ";", "}", "$", "notRunning", "=", "$", ...
Download available data on socket. @throws Exception @return bool TRUE when there are any requests on queue, FALSE when finished
[ "Download", "available", "data", "on", "socket", "." ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/RequestsQueue.php#L178-L213
stil/curl-easy
src/Response.php
Response.getInfo
public function getInfo($key = null) { return $key === null ? curl_getinfo($this->ch) : curl_getinfo($this->ch, $key); }
php
public function getInfo($key = null) { return $key === null ? curl_getinfo($this->ch) : curl_getinfo($this->ch, $key); }
[ "public", "function", "getInfo", "(", "$", "key", "=", "null", ")", "{", "return", "$", "key", "===", "null", "?", "curl_getinfo", "(", "$", "this", "->", "ch", ")", ":", "curl_getinfo", "(", "$", "this", "->", "ch", ",", "$", "key", ")", ";", "}...
Get information regarding a current transfer If opt is given, returns its value as a string Otherwise, returns an associative array with the following elements (which correspond to opt), or FALSE on failure. @param int $key One of the CURLINFO_* constants @return mixed
[ "Get", "information", "regarding", "a", "current", "transfer", "If", "opt", "is", "given", "returns", "its", "value", "as", "a", "string", "Otherwise", "returns", "an", "associative", "array", "with", "the", "following", "elements", "(", "which", "correspond", ...
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/Response.php#L35-L38
stil/curl-easy
src/Options.php
Options.applyTo
public function applyTo(Request $request) { if (!empty($this->data)) { curl_setopt_array($request->getHandle(), $this->data); } return $this; }
php
public function applyTo(Request $request) { if (!empty($this->data)) { curl_setopt_array($request->getHandle(), $this->data); } return $this; }
[ "public", "function", "applyTo", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "data", ")", ")", "{", "curl_setopt_array", "(", "$", "request", "->", "getHandle", "(", ")", ",", "$", "this", "->", "data", ...
Applies options to Request object @param Request $request @return self
[ "Applies", "options", "to", "Request", "object" ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/Options.php#L13-L20
stil/curl-easy
src/Request.php
Request.send
public function send() { if ($this->options instanceof Options) { $this->options->applyTo($this); } $content = curl_exec($this->ch); $response = new Response($this, $content); $errorCode = curl_errno($this->ch); if ($errorCode !== CURLE_OK) { $response->setError(new Error(curl_error($this->ch), $errorCode)); } return $response; }
php
public function send() { if ($this->options instanceof Options) { $this->options->applyTo($this); } $content = curl_exec($this->ch); $response = new Response($this, $content); $errorCode = curl_errno($this->ch); if ($errorCode !== CURLE_OK) { $response->setError(new Error(curl_error($this->ch), $errorCode)); } return $response; }
[ "public", "function", "send", "(", ")", "{", "if", "(", "$", "this", "->", "options", "instanceof", "Options", ")", "{", "$", "this", "->", "options", "->", "applyTo", "(", "$", "this", ")", ";", "}", "$", "content", "=", "curl_exec", "(", "$", "th...
Perform a cURL session. Equivalent to curl_exec(). This function should be called after initializing a cURL session and all the options for the session are set. Warning: it doesn't fire 'complete' event. @return Response
[ "Perform", "a", "cURL", "session", ".", "Equivalent", "to", "curl_exec", "()", ".", "This", "function", "should", "be", "called", "after", "initializing", "a", "cURL", "session", "and", "all", "the", "options", "for", "the", "session", "are", "set", "." ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/Request.php#L105-L118
stil/curl-easy
src/Request.php
Request.socketPerform
public function socketPerform() { if (!isset($this->queue)) { $this->queue = new RequestsQueue(); $this->queue->attach($this); } return $this->queue->socketPerform(); }
php
public function socketPerform() { if (!isset($this->queue)) { $this->queue = new RequestsQueue(); $this->queue->attach($this); } return $this->queue->socketPerform(); }
[ "public", "function", "socketPerform", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "queue", ")", ")", "{", "$", "this", "->", "queue", "=", "new", "RequestsQueue", "(", ")", ";", "$", "this", "->", "queue", "->", "attach", "(", ...
Creates new RequestsQueue with single Request attached to it and calls RequestsQueue::socketPerform() method. @see RequestsQueue::socketPerform()
[ "Creates", "new", "RequestsQueue", "with", "single", "Request", "attached", "to", "it", "and", "calls", "RequestsQueue", "::", "socketPerform", "()", "method", "." ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/Request.php#L126-L133
stil/curl-easy
src/Request.php
Request.socketSelect
public function socketSelect($timeout = 1) { if (!isset($this->queue)) { throw new Exception('You need to call socketPerform() before.'); } return $this->queue->socketSelect($timeout); }
php
public function socketSelect($timeout = 1) { if (!isset($this->queue)) { throw new Exception('You need to call socketPerform() before.'); } return $this->queue->socketSelect($timeout); }
[ "public", "function", "socketSelect", "(", "$", "timeout", "=", "1", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "queue", ")", ")", "{", "throw", "new", "Exception", "(", "'You need to call socketPerform() before.'", ")", ";", "}", "return",...
Calls socketSelect() on previously created RequestsQueue @see RequestsQueue::socketSelect()
[ "Calls", "socketSelect", "()", "on", "previously", "created", "RequestsQueue" ]
train
https://github.com/stil/curl-easy/blob/3f5528adff22e5d483ee581315ebc5020c5c6da0/src/Request.php#L140-L146
mjphaynes/php-resque
src/Resque/Socket/Client.php
Client.getHostname
public function getHostname() { if (is_null($this->hostname)) { $this->hostname = gethostbyaddr($this->ip); } return $this->hostname; }
php
public function getHostname() { if (is_null($this->hostname)) { $this->hostname = gethostbyaddr($this->ip); } return $this->hostname; }
[ "public", "function", "getHostname", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "hostname", ")", ")", "{", "$", "this", "->", "hostname", "=", "gethostbyaddr", "(", "$", "this", "->", "ip", ")", ";", "}", "return", "$", "this", "-...
Gets the IP hostname @return string
[ "Gets", "the", "IP", "hostname" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Socket/Client.php#L96-L103
mjphaynes/php-resque
src/Resque/Job.php
Job.redisKey
public static function redisKey($job, $suffix = null) { $id = $job instanceof Job ? $job->id : $job; return 'job:'.$id.($suffix ? ':'.$suffix : ''); }
php
public static function redisKey($job, $suffix = null) { $id = $job instanceof Job ? $job->id : $job; return 'job:'.$id.($suffix ? ':'.$suffix : ''); }
[ "public", "static", "function", "redisKey", "(", "$", "job", ",", "$", "suffix", "=", "null", ")", "{", "$", "id", "=", "$", "job", "instanceof", "Job", "?", "$", "job", "->", "id", ":", "$", "job", ";", "return", "'job:'", ".", "$", "id", ".", ...
Get the Redis key @param Job $job the job to get the key for @param string $suffix to be appended to key @return string
[ "Get", "the", "Redis", "key" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L99-L103
mjphaynes/php-resque
src/Resque/Job.php
Job.create
public static function create($queue, $class, array $data = null, $run_at = 0) { $id = static::createId($queue, $class, $data, $run_at); $job = new static($queue, $id, $class, $data); if ($run_at > 0) { if (!$job->delay($run_at)) { return false; } } elseif (!$job->queue()) { return false; } Stats::incr('total', 1); Stats::incr('total', 1, Queue::redisKey($queue, 'stats')); return $job; }
php
public static function create($queue, $class, array $data = null, $run_at = 0) { $id = static::createId($queue, $class, $data, $run_at); $job = new static($queue, $id, $class, $data); if ($run_at > 0) { if (!$job->delay($run_at)) { return false; } } elseif (!$job->queue()) { return false; } Stats::incr('total', 1); Stats::incr('total', 1, Queue::redisKey($queue, 'stats')); return $job; }
[ "public", "static", "function", "create", "(", "$", "queue", ",", "$", "class", ",", "array", "$", "data", "=", "null", ",", "$", "run_at", "=", "0", ")", "{", "$", "id", "=", "static", "::", "createId", "(", "$", "queue", ",", "$", "class", ",",...
Create a new job and save it to the specified queue. @param string $queue The name of the queue to place the job in @param string $class The name of the class that contains the code to execute the job @param array $data Any optional arguments that should be passed when the job is executed @param int $run_at Unix timestamp of when to run the job to delay execution @return string
[ "Create", "a", "new", "job", "and", "save", "it", "to", "the", "specified", "queue", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L114-L132
mjphaynes/php-resque
src/Resque/Job.php
Job.createId
public static function createId($queue, $class, $data = null, $run_at = 0) { $id = dechex(crc32($queue)). dechex(microtime(true) * 1000). md5(json_encode($class).json_encode($data).$run_at.uniqid('', true)); return substr($id, 0, self::ID_LENGTH); }
php
public static function createId($queue, $class, $data = null, $run_at = 0) { $id = dechex(crc32($queue)). dechex(microtime(true) * 1000). md5(json_encode($class).json_encode($data).$run_at.uniqid('', true)); return substr($id, 0, self::ID_LENGTH); }
[ "public", "static", "function", "createId", "(", "$", "queue", ",", "$", "class", ",", "$", "data", "=", "null", ",", "$", "run_at", "=", "0", ")", "{", "$", "id", "=", "dechex", "(", "crc32", "(", "$", "queue", ")", ")", ".", "dechex", "(", "m...
Create a new job id @param string $queue The name of the queue to place the job in @param string $class The name of the class that contains the code to execute the job @param array $data Any optional arguments that should be passed when the job is executed @param int $run_at Unix timestamp of when to run the job to delay execution @return string
[ "Create", "a", "new", "job", "id" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L143-L150
mjphaynes/php-resque
src/Resque/Job.php
Job.load
public static function load($id) { $packet = Redis::instance()->hgetall(self::redisKey($id)); if (empty($packet) or empty($packet['queue']) or !count($payload = json_decode($packet['payload'], true))) { return null; } return new static($packet['queue'], $payload['id'], $payload['class'], $payload['data']); }
php
public static function load($id) { $packet = Redis::instance()->hgetall(self::redisKey($id)); if (empty($packet) or empty($packet['queue']) or !count($payload = json_decode($packet['payload'], true))) { return null; } return new static($packet['queue'], $payload['id'], $payload['class'], $payload['data']); }
[ "public", "static", "function", "load", "(", "$", "id", ")", "{", "$", "packet", "=", "Redis", "::", "instance", "(", ")", "->", "hgetall", "(", "self", "::", "redisKey", "(", "$", "id", ")", ")", ";", "if", "(", "empty", "(", "$", "packet", ")",...
Load a job from id @param string $id The job id @return string
[ "Load", "a", "job", "from", "id" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L158-L167
mjphaynes/php-resque
src/Resque/Job.php
Job.loadPayload
public static function loadPayload($queue, $payload) { $payload = json_decode($payload, true); if (!is_array($payload) or !count($payload)) { throw new \InvalidArgumentException('Supplied $payload must be a json encoded array.'); } return new static($queue, $payload['id'], $payload['class'], $payload['data']); }
php
public static function loadPayload($queue, $payload) { $payload = json_decode($payload, true); if (!is_array($payload) or !count($payload)) { throw new \InvalidArgumentException('Supplied $payload must be a json encoded array.'); } return new static($queue, $payload['id'], $payload['class'], $payload['data']); }
[ "public", "static", "function", "loadPayload", "(", "$", "queue", ",", "$", "payload", ")", "{", "$", "payload", "=", "json_decode", "(", "$", "payload", ",", "true", ")", ";", "if", "(", "!", "is_array", "(", "$", "payload", ")", "or", "!", "count",...
Load a job from the Redis payload @param string $queue The name of the queue to place the job in @param string $payload The payload that was stored in Redis @return string
[ "Load", "a", "job", "from", "the", "Redis", "payload" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L176-L185
mjphaynes/php-resque
src/Resque/Job.php
Job.queue
public function queue() { if (Event::fire(Event::JOB_QUEUE, $this) === false) { return false; } $this->redis->sadd(Queue::redisKey(), $this->queue); $status = $this->redis->rpush(Queue::redisKey($this->queue), $this->payload); if ($status < 1) { return false; } $this->setStatus(self::STATUS_WAITING); Stats::incr('queued', 1); Stats::incr('queued', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_QUEUED, $this); return true; }
php
public function queue() { if (Event::fire(Event::JOB_QUEUE, $this) === false) { return false; } $this->redis->sadd(Queue::redisKey(), $this->queue); $status = $this->redis->rpush(Queue::redisKey($this->queue), $this->payload); if ($status < 1) { return false; } $this->setStatus(self::STATUS_WAITING); Stats::incr('queued', 1); Stats::incr('queued', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_QUEUED, $this); return true; }
[ "public", "function", "queue", "(", ")", "{", "if", "(", "Event", "::", "fire", "(", "Event", "::", "JOB_QUEUE", ",", "$", "this", ")", "===", "false", ")", "{", "return", "false", ";", "}", "$", "this", "->", "redis", "->", "sadd", "(", "Queue", ...
Save the job to Redis queue @return bool success
[ "Save", "the", "job", "to", "Redis", "queue" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L246-L267
mjphaynes/php-resque
src/Resque/Job.php
Job.delay
public function delay($time) { if (Event::fire(Event::JOB_DELAY, array($this, $time)) === false) { return false; } $this->redis->sadd(Queue::redisKey(), $this->queue); $status = $this->redis->zadd(Queue::redisKey($this->queue, 'delayed'), $time, $this->payload); if ($status < 1) { return false; } $this->setStatus(self::STATUS_DELAYED); $this->redis->hset(self::redisKey($this), 'delayed', $time); Stats::incr('delayed', 1); Stats::incr('delayed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_DELAYED, array($this, $time)); return true; }
php
public function delay($time) { if (Event::fire(Event::JOB_DELAY, array($this, $time)) === false) { return false; } $this->redis->sadd(Queue::redisKey(), $this->queue); $status = $this->redis->zadd(Queue::redisKey($this->queue, 'delayed'), $time, $this->payload); if ($status < 1) { return false; } $this->setStatus(self::STATUS_DELAYED); $this->redis->hset(self::redisKey($this), 'delayed', $time); Stats::incr('delayed', 1); Stats::incr('delayed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_DELAYED, array($this, $time)); return true; }
[ "public", "function", "delay", "(", "$", "time", ")", "{", "if", "(", "Event", "::", "fire", "(", "Event", "::", "JOB_DELAY", ",", "array", "(", "$", "this", ",", "$", "time", ")", ")", "===", "false", ")", "{", "return", "false", ";", "}", "$", ...
Save the job to Redis delayed queue @param int $time unix time of when to perform job @return bool success
[ "Save", "the", "job", "to", "Redis", "delayed", "queue" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L275-L297
mjphaynes/php-resque
src/Resque/Job.php
Job.perform
public function perform() { Stats::decr('queued', 1); Stats::decr('queued', 1, Queue::redisKey($this->queue, 'stats')); if (Event::fire(Event::JOB_PERFORM, $this) === false) { $this->cancel(); return false; } $this->run(); $retval = true; try { $instance = $this->getInstance(); ob_start(); if (method_exists($instance, 'setUp')) { $instance->setUp(); } call_user_func_array(array($instance, $this->method), array($this->data, $this)); if (method_exists($instance, 'tearDown')) { $instance->tearDown(); } $this->complete(); } catch (Exception\Cancel $e) { // setUp said don't perform this job $this->cancel(); $retval = false; } catch (\Exception $e) { $this->fail($e); $retval = false; } $output = ob_get_contents(); while (ob_get_length()) { ob_end_clean(); } $this->redis->hset(self::redisKey($this), 'output', $output); Event::fire(Event::JOB_DONE, $this); return $retval; }
php
public function perform() { Stats::decr('queued', 1); Stats::decr('queued', 1, Queue::redisKey($this->queue, 'stats')); if (Event::fire(Event::JOB_PERFORM, $this) === false) { $this->cancel(); return false; } $this->run(); $retval = true; try { $instance = $this->getInstance(); ob_start(); if (method_exists($instance, 'setUp')) { $instance->setUp(); } call_user_func_array(array($instance, $this->method), array($this->data, $this)); if (method_exists($instance, 'tearDown')) { $instance->tearDown(); } $this->complete(); } catch (Exception\Cancel $e) { // setUp said don't perform this job $this->cancel(); $retval = false; } catch (\Exception $e) { $this->fail($e); $retval = false; } $output = ob_get_contents(); while (ob_get_length()) { ob_end_clean(); } $this->redis->hset(self::redisKey($this), 'output', $output); Event::fire(Event::JOB_DONE, $this); return $retval; }
[ "public", "function", "perform", "(", ")", "{", "Stats", "::", "decr", "(", "'queued'", ",", "1", ")", ";", "Stats", "::", "decr", "(", "'queued'", ",", "1", ",", "Queue", "::", "redisKey", "(", "$", "this", "->", "queue", ",", "'stats'", ")", ")",...
Perform the job @return bool
[ "Perform", "the", "job" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L304-L354
mjphaynes/php-resque
src/Resque/Job.php
Job.getInstance
public function getInstance() { if (!is_null($this->instance)) { return $this->instance; } if (!class_exists($this->class)) { throw new \RuntimeException('Could not find job class "'.$this->class.'"'); } if (!method_exists($this->class, $this->method) or !is_callable(array($this->class, $this->method))) { throw new \RuntimeException('Job class "'.$this->class.'" does not contain a public "'.$this->method.'" method'); } $class = new \ReflectionClass($this->class); if ($class->isAbstract()) { throw new \RuntimeException('Job class "'.$this->class.'" cannot be an abstract class'); } $instance = $class->newInstance(); return $this->instance = $instance; }
php
public function getInstance() { if (!is_null($this->instance)) { return $this->instance; } if (!class_exists($this->class)) { throw new \RuntimeException('Could not find job class "'.$this->class.'"'); } if (!method_exists($this->class, $this->method) or !is_callable(array($this->class, $this->method))) { throw new \RuntimeException('Job class "'.$this->class.'" does not contain a public "'.$this->method.'" method'); } $class = new \ReflectionClass($this->class); if ($class->isAbstract()) { throw new \RuntimeException('Job class "'.$this->class.'" cannot be an abstract class'); } $instance = $class->newInstance(); return $this->instance = $instance; }
[ "public", "function", "getInstance", "(", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "instance", ")", ")", "{", "return", "$", "this", "->", "instance", ";", "}", "if", "(", "!", "class_exists", "(", "$", "this", "->", "class", ")...
Get the instantiated object for this job that will be performing work @return object Instance of the object that this job belongs to
[ "Get", "the", "instantiated", "object", "for", "this", "job", "that", "will", "be", "performing", "work" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L361-L384
mjphaynes/php-resque
src/Resque/Job.php
Job.run
public function run() { $this->setStatus(Job::STATUS_RUNNING); $this->redis->zadd(Queue::redisKey($this->queue, 'running'), time(), $this->payload); Stats::incr('running', 1); Stats::incr('running', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_RUNNING, $this); }
php
public function run() { $this->setStatus(Job::STATUS_RUNNING); $this->redis->zadd(Queue::redisKey($this->queue, 'running'), time(), $this->payload); Stats::incr('running', 1); Stats::incr('running', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_RUNNING, $this); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "setStatus", "(", "Job", "::", "STATUS_RUNNING", ")", ";", "$", "this", "->", "redis", "->", "zadd", "(", "Queue", "::", "redisKey", "(", "$", "this", "->", "queue", ",", "'running'", ")"...
Mark the current job running
[ "Mark", "the", "current", "job", "running" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L389-L398
mjphaynes/php-resque
src/Resque/Job.php
Job.stopped
protected function stopped() { $this->redis->zrem(Queue::redisKey($this->queue, 'running'), $this->payload); Stats::decr('running', 1); Stats::decr('running', 1, Queue::redisKey($this->queue, 'stats')); }
php
protected function stopped() { $this->redis->zrem(Queue::redisKey($this->queue, 'running'), $this->payload); Stats::decr('running', 1); Stats::decr('running', 1, Queue::redisKey($this->queue, 'stats')); }
[ "protected", "function", "stopped", "(", ")", "{", "$", "this", "->", "redis", "->", "zrem", "(", "Queue", "::", "redisKey", "(", "$", "this", "->", "queue", ",", "'running'", ")", ",", "$", "this", "->", "payload", ")", ";", "Stats", "::", "decr", ...
Mark the current job stopped This is an internal function as the job is either completed, cancelled or failed
[ "Mark", "the", "current", "job", "stopped", "This", "is", "an", "internal", "function", "as", "the", "job", "is", "either", "completed", "cancelled", "or", "failed" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L404-L410
mjphaynes/php-resque
src/Resque/Job.php
Job.complete
public function complete() { $this->stopped(); $this->setStatus(Job::STATUS_COMPLETE); $this->redis->zadd(Queue::redisKey($this->queue, 'processed'), time(), $this->payload); Stats::incr('processed', 1); Stats::incr('processed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_COMPLETE, $this); }
php
public function complete() { $this->stopped(); $this->setStatus(Job::STATUS_COMPLETE); $this->redis->zadd(Queue::redisKey($this->queue, 'processed'), time(), $this->payload); Stats::incr('processed', 1); Stats::incr('processed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_COMPLETE, $this); }
[ "public", "function", "complete", "(", ")", "{", "$", "this", "->", "stopped", "(", ")", ";", "$", "this", "->", "setStatus", "(", "Job", "::", "STATUS_COMPLETE", ")", ";", "$", "this", "->", "redis", "->", "zadd", "(", "Queue", "::", "redisKey", "("...
Mark the current job as complete
[ "Mark", "the", "current", "job", "as", "complete" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L415-L426
mjphaynes/php-resque
src/Resque/Job.php
Job.cancel
public function cancel() { $this->stopped(); $this->setStatus(Job::STATUS_CANCELLED); $this->redis->zadd(Queue::redisKey($this->queue, 'cancelled'), time(), $this->payload); Stats::incr('cancelled', 1); Stats::incr('cancelled', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_CANCELLED, $this); }
php
public function cancel() { $this->stopped(); $this->setStatus(Job::STATUS_CANCELLED); $this->redis->zadd(Queue::redisKey($this->queue, 'cancelled'), time(), $this->payload); Stats::incr('cancelled', 1); Stats::incr('cancelled', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_CANCELLED, $this); }
[ "public", "function", "cancel", "(", ")", "{", "$", "this", "->", "stopped", "(", ")", ";", "$", "this", "->", "setStatus", "(", "Job", "::", "STATUS_CANCELLED", ")", ";", "$", "this", "->", "redis", "->", "zadd", "(", "Queue", "::", "redisKey", "(",...
Mark the current job as cancelled
[ "Mark", "the", "current", "job", "as", "cancelled" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L431-L442
mjphaynes/php-resque
src/Resque/Job.php
Job.fail
public function fail(\Exception $e) { $this->stopped(); $this->setStatus(Job::STATUS_FAILED, $e); // For the failed jobs we store a lot more data for debugging $packet = $this->getPacket(); $failed_payload = array_merge(json_decode($this->payload, true), array( 'worker' => $packet['worker'], 'started' => $packet['started'], 'finished' => $packet['finished'], 'output' => $packet['output'], 'exception' => (array)json_decode($packet['exception'], true), )); $this->redis->zadd(Queue::redisKey($this->queue, 'failed'), time(), json_encode($failed_payload)); Stats::incr('failed', 1); Stats::incr('failed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_FAILURE, array($this, $e)); }
php
public function fail(\Exception $e) { $this->stopped(); $this->setStatus(Job::STATUS_FAILED, $e); // For the failed jobs we store a lot more data for debugging $packet = $this->getPacket(); $failed_payload = array_merge(json_decode($this->payload, true), array( 'worker' => $packet['worker'], 'started' => $packet['started'], 'finished' => $packet['finished'], 'output' => $packet['output'], 'exception' => (array)json_decode($packet['exception'], true), )); $this->redis->zadd(Queue::redisKey($this->queue, 'failed'), time(), json_encode($failed_payload)); Stats::incr('failed', 1); Stats::incr('failed', 1, Queue::redisKey($this->queue, 'stats')); Event::fire(Event::JOB_FAILURE, array($this, $e)); }
[ "public", "function", "fail", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "stopped", "(", ")", ";", "$", "this", "->", "setStatus", "(", "Job", "::", "STATUS_FAILED", ",", "$", "e", ")", ";", "// For the failed jobs we store a lot more d...
Mark the current job as having failed @param \Exception $e
[ "Mark", "the", "current", "job", "as", "having", "failed" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L449-L469
mjphaynes/php-resque
src/Resque/Job.php
Job.failError
public function failError() { if ( ($packet = $this->getPacket()) and $packet['status'] !== Job::STATUS_FAILED and ($e = json_decode($packet['exception'], true)) ) { return $e['error']; } return 'Unknown exception'; }
php
public function failError() { if ( ($packet = $this->getPacket()) and $packet['status'] !== Job::STATUS_FAILED and ($e = json_decode($packet['exception'], true)) ) { return $e['error']; } return 'Unknown exception'; }
[ "public", "function", "failError", "(", ")", "{", "if", "(", "(", "$", "packet", "=", "$", "this", "->", "getPacket", "(", ")", ")", "and", "$", "packet", "[", "'status'", "]", "!==", "Job", "::", "STATUS_FAILED", "and", "(", "$", "e", "=", "json_d...
Returns the fail error for the job @return mixed
[ "Returns", "the", "fail", "error", "for", "the", "job" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L476-L487
mjphaynes/php-resque
src/Resque/Job.php
Job.createPayload
protected function createPayload() { if ($this->data instanceof Closure) { $closure = serialize(new Helpers\SerializableClosure($this->data)); $data = compact('closure'); } else { $data = $this->data; } return json_encode(array('id' => $this->id, 'class' => $this->class, 'data' => $data)); }
php
protected function createPayload() { if ($this->data instanceof Closure) { $closure = serialize(new Helpers\SerializableClosure($this->data)); $data = compact('closure'); } else { $data = $this->data; } return json_encode(array('id' => $this->id, 'class' => $this->class, 'data' => $data)); }
[ "protected", "function", "createPayload", "(", ")", "{", "if", "(", "$", "this", "->", "data", "instanceof", "Closure", ")", "{", "$", "closure", "=", "serialize", "(", "new", "Helpers", "\\", "SerializableClosure", "(", "$", "this", "->", "data", ")", "...
Create a payload string from the given job and data @param string $job @param mixed $data @return string
[ "Create", "a", "payload", "string", "from", "the", "given", "job", "and", "data" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L496-L506
mjphaynes/php-resque
src/Resque/Job.php
Job.setStatus
public function setStatus($status, \Exception $e = null) { if (!($packet = $this->getPacket())) { $packet = array( 'id' => $this->id, 'queue' => $this->queue, 'payload' => $this->payload, 'worker' => '', 'status' => $status, 'created' => microtime(true), 'updated' => microtime(true), 'delayed' => 0, 'started' => 0, 'finished' => 0, 'output' => '', 'exception' => null, ); } $packet['worker'] = (string)$this->worker; $packet['status'] = $status; $packet['updated'] = microtime(true); if ($status == Job::STATUS_RUNNING) { $packet['started'] = microtime(true); } if (in_array($status, self::$completeStatuses)) { $packet['finished'] = microtime(true); } if ($e) { $packet['exception'] = json_encode(array( 'class' => get_class($e), 'error' => sprintf('%s in %s on line %d', $e->getMessage(), $e->getFile(), $e->getLine()), 'backtrace' => explode("\n", $e->getTraceAsString()) )); } $this->redis->hmset(self::redisKey($this), $packet); // Expire the status for completed jobs if (in_array($status, self::$completeStatuses)) { $this->redis->expire(self::redisKey($this), \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } }
php
public function setStatus($status, \Exception $e = null) { if (!($packet = $this->getPacket())) { $packet = array( 'id' => $this->id, 'queue' => $this->queue, 'payload' => $this->payload, 'worker' => '', 'status' => $status, 'created' => microtime(true), 'updated' => microtime(true), 'delayed' => 0, 'started' => 0, 'finished' => 0, 'output' => '', 'exception' => null, ); } $packet['worker'] = (string)$this->worker; $packet['status'] = $status; $packet['updated'] = microtime(true); if ($status == Job::STATUS_RUNNING) { $packet['started'] = microtime(true); } if (in_array($status, self::$completeStatuses)) { $packet['finished'] = microtime(true); } if ($e) { $packet['exception'] = json_encode(array( 'class' => get_class($e), 'error' => sprintf('%s in %s on line %d', $e->getMessage(), $e->getFile(), $e->getLine()), 'backtrace' => explode("\n", $e->getTraceAsString()) )); } $this->redis->hmset(self::redisKey($this), $packet); // Expire the status for completed jobs if (in_array($status, self::$completeStatuses)) { $this->redis->expire(self::redisKey($this), \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } }
[ "public", "function", "setStatus", "(", "$", "status", ",", "\\", "Exception", "$", "e", "=", "null", ")", "{", "if", "(", "!", "(", "$", "packet", "=", "$", "this", "->", "getPacket", "(", ")", ")", ")", "{", "$", "packet", "=", "array", "(", ...
Update the status indicator for the current job with a new status @param int $status The status of the job @param \Exception $e If failed status it sends through exception
[ "Update", "the", "status", "indicator", "for", "the", "current", "job", "with", "a", "new", "status" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L514-L559
mjphaynes/php-resque
src/Resque/Job.php
Job.getPacket
public function getPacket() { if ($packet = $this->redis->hgetall(self::redisKey($this))) { return $packet; } return false; }
php
public function getPacket() { if ($packet = $this->redis->hgetall(self::redisKey($this))) { return $packet; } return false; }
[ "public", "function", "getPacket", "(", ")", "{", "if", "(", "$", "packet", "=", "$", "this", "->", "redis", "->", "hgetall", "(", "self", "::", "redisKey", "(", "$", "this", ")", ")", ")", "{", "return", "$", "packet", ";", "}", "return", "false",...
Fetch the packet for the job being monitored. @return array
[ "Fetch", "the", "packet", "for", "the", "job", "being", "monitored", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L566-L573
mjphaynes/php-resque
src/Resque/Job.php
Job.toArray
public function toArray() { $packet = $this->getPacket(); return array( 'id' => (string)$this->id, 'queue' => (string)$this->queue, 'class' => (string)$this->class, 'data' => $this->data, 'worker' => (string)$packet['worker'], 'status' => (int)$packet['status'], 'created' => (float)$packet['created'], 'updated' => (float)$packet['updated'], 'delayed' => (float)$packet['delayed'], 'started' => (float)$packet['started'], 'finished' => (float)$packet['finished'], 'output' => $packet['output'], 'exception' => $packet['exception'] ); }
php
public function toArray() { $packet = $this->getPacket(); return array( 'id' => (string)$this->id, 'queue' => (string)$this->queue, 'class' => (string)$this->class, 'data' => $this->data, 'worker' => (string)$packet['worker'], 'status' => (int)$packet['status'], 'created' => (float)$packet['created'], 'updated' => (float)$packet['updated'], 'delayed' => (float)$packet['delayed'], 'started' => (float)$packet['started'], 'finished' => (float)$packet['finished'], 'output' => $packet['output'], 'exception' => $packet['exception'] ); }
[ "public", "function", "toArray", "(", ")", "{", "$", "packet", "=", "$", "this", "->", "getPacket", "(", ")", ";", "return", "array", "(", "'id'", "=>", "(", "string", ")", "$", "this", "->", "id", ",", "'queue'", "=>", "(", "string", ")", "$", "...
Return array representation of this job @return array
[ "Return", "array", "representation", "of", "this", "job" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L744-L763
mjphaynes/php-resque
src/Resque/Job.php
Job.cleanup
public static function cleanup(array $queues = array('*')) { $cleaned = array('zombie' => 0, 'processed' => 0); $redis = Redis::instance(); if (in_array('*', $queues)) { $queues = (array)$redis->smembers(Queue::redisKey()); sort($queues); } $workers = $redis->smembers(Worker::redisKey()); foreach ($queues as $queue) { $jobs = $redis->zrangebyscore(Queue::redisKey($queue, 'running'), 0, time()); foreach ($jobs as $payload) { $job = self::loadPayload($queue, $payload); $packet = $job->getPacket(); if (!in_array($packet['worker'], $workers)) { $job->fail(new Exception\Zombie); $cleaned['zombie']++; } } $cleaned['processed'] = $redis->zremrangebyscore(Queue::redisKey($queue, 'processed'), 0, time() - \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } return $cleaned; }
php
public static function cleanup(array $queues = array('*')) { $cleaned = array('zombie' => 0, 'processed' => 0); $redis = Redis::instance(); if (in_array('*', $queues)) { $queues = (array)$redis->smembers(Queue::redisKey()); sort($queues); } $workers = $redis->smembers(Worker::redisKey()); foreach ($queues as $queue) { $jobs = $redis->zrangebyscore(Queue::redisKey($queue, 'running'), 0, time()); foreach ($jobs as $payload) { $job = self::loadPayload($queue, $payload); $packet = $job->getPacket(); if (!in_array($packet['worker'], $workers)) { $job->fail(new Exception\Zombie); $cleaned['zombie']++; } } $cleaned['processed'] = $redis->zremrangebyscore(Queue::redisKey($queue, 'processed'), 0, time() - \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } return $cleaned; }
[ "public", "static", "function", "cleanup", "(", "array", "$", "queues", "=", "array", "(", "'*'", ")", ")", "{", "$", "cleaned", "=", "array", "(", "'zombie'", "=>", "0", ",", "'processed'", "=>", "0", ")", ";", "$", "redis", "=", "Redis", "::", "i...
Look for any jobs which are running but the worker is dead. Meaning that they are also not running but left in limbo This is a form of garbage collection to handle cases where the server may have been killed and the workers did not die gracefully and therefore leave state information in Redis. @param array $queues list of queues to check
[ "Look", "for", "any", "jobs", "which", "are", "running", "but", "the", "worker", "is", "dead", ".", "Meaning", "that", "they", "are", "also", "not", "running", "but", "left", "in", "limbo" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Job.php#L775-L805
mjphaynes/php-resque
src/Resque/Worker.php
Worker.redisKey
public static function redisKey($worker = null, $suffix = null) { if (is_null($worker)) { return 'workers'; } $id = $worker instanceof Worker ? $worker->id : $worker; return 'worker:'.$id.($suffix ? ':'.$suffix : ''); }
php
public static function redisKey($worker = null, $suffix = null) { if (is_null($worker)) { return 'workers'; } $id = $worker instanceof Worker ? $worker->id : $worker; return 'worker:'.$id.($suffix ? ':'.$suffix : ''); }
[ "public", "static", "function", "redisKey", "(", "$", "worker", "=", "null", ",", "$", "suffix", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "worker", ")", ")", "{", "return", "'workers'", ";", "}", "$", "id", "=", "$", "worker", "instan...
Get the Redis key @param Worker $worker the worker to get the key for @param string $suffix to be appended to key @return string
[ "Get", "the", "Redis", "key" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L158-L167
mjphaynes/php-resque
src/Resque/Worker.php
Worker.fromId
public static function fromId($id, Logger $logger = null) { if (!$id or !count($packet = Redis::instance()->hgetall(self::redisKey($id)))) { return false; } $worker = new static(explode(',', $packet['queues']), $packet['blocking']); $worker->setId($id); $worker->setPid($packet['pid']); $worker->setInterval($packet['interval']); $worker->setTimeout($packet['timeout']); $worker->setMemoryLimit($packet['memory_limit']); $worker->setHost(new Host($packet['hostname'])); $worker->shutdown = isset($packet['shutdown']) ? $packet['shutdown'] : null; $worker->setLogger($logger); return $worker; }
php
public static function fromId($id, Logger $logger = null) { if (!$id or !count($packet = Redis::instance()->hgetall(self::redisKey($id)))) { return false; } $worker = new static(explode(',', $packet['queues']), $packet['blocking']); $worker->setId($id); $worker->setPid($packet['pid']); $worker->setInterval($packet['interval']); $worker->setTimeout($packet['timeout']); $worker->setMemoryLimit($packet['memory_limit']); $worker->setHost(new Host($packet['hostname'])); $worker->shutdown = isset($packet['shutdown']) ? $packet['shutdown'] : null; $worker->setLogger($logger); return $worker; }
[ "public", "static", "function", "fromId", "(", "$", "id", ",", "Logger", "$", "logger", "=", "null", ")", "{", "if", "(", "!", "$", "id", "or", "!", "count", "(", "$", "packet", "=", "Redis", "::", "instance", "(", ")", "->", "hgetall", "(", "sel...
Return a worker from it's ID @param string $id Worker id @param Logger $logger Logger for the worker to use @return Worker
[ "Return", "a", "worker", "from", "it", "s", "ID" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L176-L193
mjphaynes/php-resque
src/Resque/Worker.php
Worker.work
public function work() { $this->log('Starting worker <pop>'.$this.'</pop>', Logger::INFO); $this->updateProcLine('Worker: starting...'); $this->startup(); $this->log('Listening to queues: <pop>'.implode(', ', $this->queues).'</pop>, with '. ($this->blocking ? 'timeout blocking' : 'time interval').' <pop>'.$this->interval_string().'</pop>', Logger::INFO); while (true) { if ($this->memoryExceeded()) { $this->log('Worker memory has been exceeded, aborting', Logger::CRITICAL); $this->shutdown(); Event::fire(Event::WORKER_LOW_MEMORY, $this); } if (!$this->redis->sismember(self::redisKey(), $this->id) or $this->redis->hlen(self::redisKey($this)) == 0) { $this->log('Worker is not in list of workers or packet is corrupt, aborting', Logger::CRITICAL); $this->shutdown(); Event::fire(Event::WORKER_CORRUPT, $this); } $this->shutdown = $this->redis->hget(self::redisKey($this), 'shutdown'); if ($this->shutdown) { $this->log('Shutting down worker <pop>'.$this.'</pop>', Logger::INFO); $this->updateProcLine('Worker: shutting down...'); break; } if ($this->status == self::STATUS_PAUSED) { $this->log('Worker paused, trying again in '.$this->interval_string(), Logger::INFO); $this->updateProcLine('Worker: paused'); sleep($this->interval); continue; } $this->host->working($this); $this->redis->hmset(self::redisKey($this), 'memory', memory_get_usage()); Event::fire(Event::WORKER_WORK, $this); if (!count($this->resolveQueues())) { $this->log('No queues found, waiting for '.$this->interval_string(), Logger::INFO); sleep($this->interval); continue; } $this->queueDelayed(); if ($this->blocking) { $this->log('Pop blocking with timeout of '.$this->interval_string(), Logger::DEBUG); $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with blocking timeout '.$this->interval_string()); } else { $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with interval '.$this->interval_string()); } $job = \Resque::pop($this->resolveQueues(), $this->interval, $this->blocking); if (!$job instanceof Job) { if (!$this->blocking) { $this->log('Sleeping for '.$this->interval_string(), Logger::DEBUG); sleep($this->interval); } continue; } $this->log('Found a job <pop>'.$job.'</pop>', Logger::NOTICE); $this->workingOn($job); Event::fire(Event::WORKER_FORK, array($this, $job)); // Fork into another process $this->child = pcntl_fork(); // Returning -1 means error in forking if ($this->child == -1) { Event::fire(Event::WORKER_FORK_ERROR, array($this, $job)); $this->log('Unable to fork process, this is a fatal error, aborting worker', Logger::ALERT); $this->log('Re-queuing job <pop>'.$job.'</pop>', Logger::INFO); // Because it wasn't the job that failed the job is readded to the queue // so that in can be tried again at a later time $job->queue(); $this->shutdown(); } elseif ($this->child > 0) { // In parent if $pid > 0 since pcntl_fork returns process id of child Event::fire(Event::WORKER_FORK_PARENT, array($this, $job, $this->child)); $this->log('Forked process to run job on pid:'.$this->child, Logger::DEBUG); $this->updateProcLine('Worker: forked '.$this->child.' at '.strftime('%F %T')); // Set the PID in redis $this->redis->hset(self::redisKey($this), 'job_pid', $this->child); // Wait until the child process finishes before continuing pcntl_wait($status); if (!pcntl_wifexited($status) or ($exitStatus = pcntl_wexitstatus($status)) !== 0) { if ($this->job->getStatus() == Job::STATUS_FAILED) { $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$this->job->execTimeStr(), Logger::ERROR); } else { $this->log('Job '.$job.' exited with code '.$exitStatus, Logger::ERROR); $this->job->fail(new Exception\Dirty($exitStatus)); } } } else { // Reset the redis connection to prevent forking issues $this->redis->disconnect(); $this->redis->connect(); Event::fire(Event::WORKER_FORK_CHILD, array($this, $job, getmypid())); $this->log('Running job <pop>'.$job.'</pop>', Logger::INFO); $this->updateProcLine('Job: processing '.$job->getQueue().'#'.$job->getId().' since '.strftime('%F %T')); $this->perform($job); exit(0); } $this->child = null; $this->doneWorking(); } }
php
public function work() { $this->log('Starting worker <pop>'.$this.'</pop>', Logger::INFO); $this->updateProcLine('Worker: starting...'); $this->startup(); $this->log('Listening to queues: <pop>'.implode(', ', $this->queues).'</pop>, with '. ($this->blocking ? 'timeout blocking' : 'time interval').' <pop>'.$this->interval_string().'</pop>', Logger::INFO); while (true) { if ($this->memoryExceeded()) { $this->log('Worker memory has been exceeded, aborting', Logger::CRITICAL); $this->shutdown(); Event::fire(Event::WORKER_LOW_MEMORY, $this); } if (!$this->redis->sismember(self::redisKey(), $this->id) or $this->redis->hlen(self::redisKey($this)) == 0) { $this->log('Worker is not in list of workers or packet is corrupt, aborting', Logger::CRITICAL); $this->shutdown(); Event::fire(Event::WORKER_CORRUPT, $this); } $this->shutdown = $this->redis->hget(self::redisKey($this), 'shutdown'); if ($this->shutdown) { $this->log('Shutting down worker <pop>'.$this.'</pop>', Logger::INFO); $this->updateProcLine('Worker: shutting down...'); break; } if ($this->status == self::STATUS_PAUSED) { $this->log('Worker paused, trying again in '.$this->interval_string(), Logger::INFO); $this->updateProcLine('Worker: paused'); sleep($this->interval); continue; } $this->host->working($this); $this->redis->hmset(self::redisKey($this), 'memory', memory_get_usage()); Event::fire(Event::WORKER_WORK, $this); if (!count($this->resolveQueues())) { $this->log('No queues found, waiting for '.$this->interval_string(), Logger::INFO); sleep($this->interval); continue; } $this->queueDelayed(); if ($this->blocking) { $this->log('Pop blocking with timeout of '.$this->interval_string(), Logger::DEBUG); $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with blocking timeout '.$this->interval_string()); } else { $this->updateProcLine('Worker: waiting for job on '.implode(',', $this->queues).' with interval '.$this->interval_string()); } $job = \Resque::pop($this->resolveQueues(), $this->interval, $this->blocking); if (!$job instanceof Job) { if (!$this->blocking) { $this->log('Sleeping for '.$this->interval_string(), Logger::DEBUG); sleep($this->interval); } continue; } $this->log('Found a job <pop>'.$job.'</pop>', Logger::NOTICE); $this->workingOn($job); Event::fire(Event::WORKER_FORK, array($this, $job)); // Fork into another process $this->child = pcntl_fork(); // Returning -1 means error in forking if ($this->child == -1) { Event::fire(Event::WORKER_FORK_ERROR, array($this, $job)); $this->log('Unable to fork process, this is a fatal error, aborting worker', Logger::ALERT); $this->log('Re-queuing job <pop>'.$job.'</pop>', Logger::INFO); // Because it wasn't the job that failed the job is readded to the queue // so that in can be tried again at a later time $job->queue(); $this->shutdown(); } elseif ($this->child > 0) { // In parent if $pid > 0 since pcntl_fork returns process id of child Event::fire(Event::WORKER_FORK_PARENT, array($this, $job, $this->child)); $this->log('Forked process to run job on pid:'.$this->child, Logger::DEBUG); $this->updateProcLine('Worker: forked '.$this->child.' at '.strftime('%F %T')); // Set the PID in redis $this->redis->hset(self::redisKey($this), 'job_pid', $this->child); // Wait until the child process finishes before continuing pcntl_wait($status); if (!pcntl_wifexited($status) or ($exitStatus = pcntl_wexitstatus($status)) !== 0) { if ($this->job->getStatus() == Job::STATUS_FAILED) { $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$this->job->execTimeStr(), Logger::ERROR); } else { $this->log('Job '.$job.' exited with code '.$exitStatus, Logger::ERROR); $this->job->fail(new Exception\Dirty($exitStatus)); } } } else { // Reset the redis connection to prevent forking issues $this->redis->disconnect(); $this->redis->connect(); Event::fire(Event::WORKER_FORK_CHILD, array($this, $job, getmypid())); $this->log('Running job <pop>'.$job.'</pop>', Logger::INFO); $this->updateProcLine('Job: processing '.$job->getQueue().'#'.$job->getId().' since '.strftime('%F %T')); $this->perform($job); exit(0); } $this->child = null; $this->doneWorking(); } }
[ "public", "function", "work", "(", ")", "{", "$", "this", "->", "log", "(", "'Starting worker <pop>'", ".", "$", "this", ".", "'</pop>'", ",", "Logger", "::", "INFO", ")", ";", "$", "this", "->", "updateProcLine", "(", "'Worker: starting...'", ")", ";", ...
The primary loop for a worker which when called on an instance starts the worker's life cycle. Queues are checked every $interval (seconds) for new jobs.
[ "The", "primary", "loop", "for", "a", "worker", "which", "when", "called", "on", "an", "instance", "starts", "the", "worker", "s", "life", "cycle", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L230-L360
mjphaynes/php-resque
src/Resque/Worker.php
Worker.perform
public function perform(Job $job) { // Set timeout so as to stop any hanged jobs // and turn off displaying errors as it fills // up the console set_time_limit($this->timeout); ini_set('display_errors', 0); $job->perform(); $status = $job->getStatus(); switch ($status) { case Job::STATUS_COMPLETE: $this->log('Done job <pop>'.$job.'</pop> in <pop>'.$job->execTimeStr().'</pop>', Logger::INFO); break; case Job::STATUS_CANCELLED: $this->log('Cancelled job <pop>'.$job.'</pop>', Logger::INFO); break; case Job::STATUS_FAILED: $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$job->execTimeStr(), Logger::ERROR); break; default: $this->log('Unknown job status "('.gettype($status).')'.$status.'" for <pop>'.$job.'</pop>', Logger::WARNING); break; } }
php
public function perform(Job $job) { // Set timeout so as to stop any hanged jobs // and turn off displaying errors as it fills // up the console set_time_limit($this->timeout); ini_set('display_errors', 0); $job->perform(); $status = $job->getStatus(); switch ($status) { case Job::STATUS_COMPLETE: $this->log('Done job <pop>'.$job.'</pop> in <pop>'.$job->execTimeStr().'</pop>', Logger::INFO); break; case Job::STATUS_CANCELLED: $this->log('Cancelled job <pop>'.$job.'</pop>', Logger::INFO); break; case Job::STATUS_FAILED: $this->log('Job '.$job.' failed: "'.$job->failError().'" in '.$job->execTimeStr(), Logger::ERROR); break; default: $this->log('Unknown job status "('.gettype($status).')'.$status.'" for <pop>'.$job.'</pop>', Logger::WARNING); break; } }
[ "public", "function", "perform", "(", "Job", "$", "job", ")", "{", "// Set timeout so as to stop any hanged jobs", "// and turn off displaying errors as it fills", "// up the console", "set_time_limit", "(", "$", "this", "->", "timeout", ")", ";", "ini_set", "(", "'displa...
Process a single job @param Job $job The job to be processed.
[ "Process", "a", "single", "job" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L367-L394
mjphaynes/php-resque
src/Resque/Worker.php
Worker.startup
protected function startup() { $this->host->cleanup(); $this->cleanup(); $this->register(); $cleaned = Job::cleanup($this->queues); if ($cleaned['zombie']) { $this->log('Failed <pop>'.$cleaned['zombie'].'</pop> zombie job'.($cleaned['zombie'] == 1 ? '' : 's'), Logger::NOTICE); } if ($cleaned['processed']) { $this->log('Cleared <pop>'.$cleaned['processed'].'</pop> processed job'.($cleaned['processed'] == 1 ? '' : 's'), Logger::NOTICE); } $this->setStatus(self::STATUS_RUNNING); Event::fire(Event::WORKER_STARTUP, $this); }
php
protected function startup() { $this->host->cleanup(); $this->cleanup(); $this->register(); $cleaned = Job::cleanup($this->queues); if ($cleaned['zombie']) { $this->log('Failed <pop>'.$cleaned['zombie'].'</pop> zombie job'.($cleaned['zombie'] == 1 ? '' : 's'), Logger::NOTICE); } if ($cleaned['processed']) { $this->log('Cleared <pop>'.$cleaned['processed'].'</pop> processed job'.($cleaned['processed'] == 1 ? '' : 's'), Logger::NOTICE); } $this->setStatus(self::STATUS_RUNNING); Event::fire(Event::WORKER_STARTUP, $this); }
[ "protected", "function", "startup", "(", ")", "{", "$", "this", "->", "host", "->", "cleanup", "(", ")", ";", "$", "this", "->", "cleanup", "(", ")", ";", "$", "this", "->", "register", "(", ")", ";", "$", "cleaned", "=", "Job", "::", "cleanup", ...
Perform necessary actions to start a worker
[ "Perform", "necessary", "actions", "to", "start", "a", "worker" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L399-L416
mjphaynes/php-resque
src/Resque/Worker.php
Worker.shutdown
public function shutdown() { $this->shutdown = true; $this->redis->hmset(self::redisKey($this), 'shutdown', true); Event::fire(Event::WORKER_SHUTDOWN, $this); }
php
public function shutdown() { $this->shutdown = true; $this->redis->hmset(self::redisKey($this), 'shutdown', true); Event::fire(Event::WORKER_SHUTDOWN, $this); }
[ "public", "function", "shutdown", "(", ")", "{", "$", "this", "->", "shutdown", "=", "true", ";", "$", "this", "->", "redis", "->", "hmset", "(", "self", "::", "redisKey", "(", "$", "this", ")", ",", "'shutdown'", ",", "true", ")", ";", "Event", ":...
Schedule a worker for shutdown. Will finish processing the current job and when the timeout interval is reached, the worker will shut down.
[ "Schedule", "a", "worker", "for", "shutdown", ".", "Will", "finish", "processing", "the", "current", "job", "and", "when", "the", "timeout", "interval", "is", "reached", "the", "worker", "will", "shut", "down", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L422-L428
mjphaynes/php-resque
src/Resque/Worker.php
Worker.forceShutdown
public function forceShutdown() { Event::fire(Event::WORKER_FORCE_SHUTDOWN, $this); if ($this->child === 0) { $this->log('Forcing shutdown of job <pop>'.$this->job.'</pop>', Logger::NOTICE); } else { $this->log('Forcing shutdown of worker <pop>'.$this.'</pop>', Logger::NOTICE); } $this->shutdown(); $this->killChild(); }
php
public function forceShutdown() { Event::fire(Event::WORKER_FORCE_SHUTDOWN, $this); if ($this->child === 0) { $this->log('Forcing shutdown of job <pop>'.$this->job.'</pop>', Logger::NOTICE); } else { $this->log('Forcing shutdown of worker <pop>'.$this.'</pop>', Logger::NOTICE); } $this->shutdown(); $this->killChild(); }
[ "public", "function", "forceShutdown", "(", ")", "{", "Event", "::", "fire", "(", "Event", "::", "WORKER_FORCE_SHUTDOWN", ",", "$", "this", ")", ";", "if", "(", "$", "this", "->", "child", "===", "0", ")", "{", "$", "this", "->", "log", "(", "'Forcin...
Force an immediate shutdown of the worker, killing any child jobs currently running.
[ "Force", "an", "immediate", "shutdown", "of", "the", "worker", "killing", "any", "child", "jobs", "currently", "running", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L434-L446
mjphaynes/php-resque
src/Resque/Worker.php
Worker.killChild
public function killChild() { if (is_null($this->child)) { return; } if ($this->child === 0) { throw new Exception\Shutdown('Job forced shutdown'); } Event::fire(Event::WORKER_KILLCHILD, array($this, $this->child)); if (posix_kill($this->child, 0)) { $this->log('Killing child process at pid:'.$this->child, Logger::DEBUG); posix_kill($this->child, SIGTERM); } $this->child = null; }
php
public function killChild() { if (is_null($this->child)) { return; } if ($this->child === 0) { throw new Exception\Shutdown('Job forced shutdown'); } Event::fire(Event::WORKER_KILLCHILD, array($this, $this->child)); if (posix_kill($this->child, 0)) { $this->log('Killing child process at pid:'.$this->child, Logger::DEBUG); posix_kill($this->child, SIGTERM); } $this->child = null; }
[ "public", "function", "killChild", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "child", ")", ")", "{", "return", ";", "}", "if", "(", "$", "this", "->", "child", "===", "0", ")", "{", "throw", "new", "Exception", "\\", "Shutdown", ...
Kill a forked child job immediately. The job it is processing will not be completed.
[ "Kill", "a", "forked", "child", "job", "immediately", ".", "The", "job", "it", "is", "processing", "will", "not", "be", "completed", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L464-L483
mjphaynes/php-resque
src/Resque/Worker.php
Worker.register
public function register() { $this->log('Registering worker <pop>'.$this.'</pop>', Logger::NOTICE); $this->redis->sadd(self::redisKey(), $this->id); $this->redis->hmset(self::redisKey($this), array( 'started' => microtime(true), 'hostname' => (string)$this->host, 'pid' => getmypid(), 'memory' => memory_get_usage(), 'memory_limit' => $this->memoryLimit, 'queues' => implode(',', $this->queues), 'shutdown' => false, 'blocking' => $this->blocking, 'status' => $this->status, 'interval' => $this->interval, 'timeout' => $this->timeout, 'processed' => 0, 'cancelled' => 0, 'failed' => 0, 'job_id' => '', 'job_pid' => 0, 'job_started' => 0 )); if (function_exists('pcntl_signal')) { $this->log('Registering sig handlers for worker '.$this, Logger::DEBUG); // PHP 7.1 allows async signals if (function_exists('pcntl_async_signals')) { pcntl_async_signals(true); } else { declare(ticks = 1); } foreach ($this->signalHandlerMapping as $signalName => $signalHandler) { pcntl_signal($signalName, array($this, $signalHandler)); } } register_shutdown_function(array($this, 'unregister')); Event::fire(Event::WORKER_REGISTER, $this); }
php
public function register() { $this->log('Registering worker <pop>'.$this.'</pop>', Logger::NOTICE); $this->redis->sadd(self::redisKey(), $this->id); $this->redis->hmset(self::redisKey($this), array( 'started' => microtime(true), 'hostname' => (string)$this->host, 'pid' => getmypid(), 'memory' => memory_get_usage(), 'memory_limit' => $this->memoryLimit, 'queues' => implode(',', $this->queues), 'shutdown' => false, 'blocking' => $this->blocking, 'status' => $this->status, 'interval' => $this->interval, 'timeout' => $this->timeout, 'processed' => 0, 'cancelled' => 0, 'failed' => 0, 'job_id' => '', 'job_pid' => 0, 'job_started' => 0 )); if (function_exists('pcntl_signal')) { $this->log('Registering sig handlers for worker '.$this, Logger::DEBUG); // PHP 7.1 allows async signals if (function_exists('pcntl_async_signals')) { pcntl_async_signals(true); } else { declare(ticks = 1); } foreach ($this->signalHandlerMapping as $signalName => $signalHandler) { pcntl_signal($signalName, array($this, $signalHandler)); } } register_shutdown_function(array($this, 'unregister')); Event::fire(Event::WORKER_REGISTER, $this); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "log", "(", "'Registering worker <pop>'", ".", "$", "this", ".", "'</pop>'", ",", "Logger", "::", "NOTICE", ")", ";", "$", "this", "->", "redis", "->", "sadd", "(", "self", "::", "redi...
Register this worker in Redis and signal handlers that a worker should respond to - TERM: Shutdown immediately and stop processing jobs - INT: Shutdown immediately and stop processing jobs - QUIT: Shutdown after the current job finishes processing - USR1: Kill the forked child immediately and continue processing jobs
[ "Register", "this", "worker", "in", "Redis", "and", "signal", "handlers", "that", "a", "worker", "should", "respond", "to" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L493-L535
mjphaynes/php-resque
src/Resque/Worker.php
Worker.unregister
public function unregister() { if ($this->child === 0) { // This is a child process so don't unregister worker // However if the shutdown was due to an error, for instance the job hitting the // max execution time, then catch the error and fail the job if (($error = error_get_last()) and in_array($error['type'], $this->shutdownErrors)) { $this->job->fail(new \ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line'])); } return; } elseif (!is_null($this->child)) { // There is a child process running $this->log('There is a child process pid:'.$this->child.' running, killing it', Logger::DEBUG); $this->killChild(); } if (is_object($this->job)) { $this->job->fail(new Exception\Cancel); $this->log('Failing running job <pop>'.$this->job.'</pop>', Logger::NOTICE); } $this->log('Unregistering worker <pop>'.$this.'</pop>', Logger::NOTICE); $this->redis->srem(self::redisKey(), $this->id); $this->redis->expire(self::redisKey($this), \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); $this->host->finished($this); // Remove pid file if one set if (!is_null($this->pidFile) and getmypid() === (int)trim(file_get_contents($this->pidFile))) { unlink($this->pidFile); } Event::fire(Event::WORKER_UNREGISTER, $this); }
php
public function unregister() { if ($this->child === 0) { // This is a child process so don't unregister worker // However if the shutdown was due to an error, for instance the job hitting the // max execution time, then catch the error and fail the job if (($error = error_get_last()) and in_array($error['type'], $this->shutdownErrors)) { $this->job->fail(new \ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line'])); } return; } elseif (!is_null($this->child)) { // There is a child process running $this->log('There is a child process pid:'.$this->child.' running, killing it', Logger::DEBUG); $this->killChild(); } if (is_object($this->job)) { $this->job->fail(new Exception\Cancel); $this->log('Failing running job <pop>'.$this->job.'</pop>', Logger::NOTICE); } $this->log('Unregistering worker <pop>'.$this.'</pop>', Logger::NOTICE); $this->redis->srem(self::redisKey(), $this->id); $this->redis->expire(self::redisKey($this), \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); $this->host->finished($this); // Remove pid file if one set if (!is_null($this->pidFile) and getmypid() === (int)trim(file_get_contents($this->pidFile))) { unlink($this->pidFile); } Event::fire(Event::WORKER_UNREGISTER, $this); }
[ "public", "function", "unregister", "(", ")", "{", "if", "(", "$", "this", "->", "child", "===", "0", ")", "{", "// This is a child process so don't unregister worker", "// However if the shutdown was due to an error, for instance the job hitting the", "// max execution time, the...
Unregister this worker in Redis
[ "Unregister", "this", "worker", "in", "Redis" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L540-L575
mjphaynes/php-resque
src/Resque/Worker.php
Worker.sigForceShutdown
public function sigForceShutdown($sig) { switch ($sig) { case SIGTERM: $sig = 'TERM'; break; case SIGINT: $sig = 'INT'; break; default: $sig = 'Unknown'; break; } $this->log($sig.' received; force shutdown worker', Logger::DEBUG); $this->forceShutdown(); }
php
public function sigForceShutdown($sig) { switch ($sig) { case SIGTERM: $sig = 'TERM'; break; case SIGINT: $sig = 'INT'; break; default: $sig = 'Unknown'; break; } $this->log($sig.' received; force shutdown worker', Logger::DEBUG); $this->forceShutdown(); }
[ "public", "function", "sigForceShutdown", "(", "$", "sig", ")", "{", "switch", "(", "$", "sig", ")", "{", "case", "SIGTERM", ":", "$", "sig", "=", "'TERM'", ";", "break", ";", "case", "SIGINT", ":", "$", "sig", "=", "'INT'", ";", "break", ";", "def...
Signal handler callback for TERM or INT, forces shutdown of worker @param int $sig Signal that was sent
[ "Signal", "handler", "callback", "for", "TERM", "or", "INT", "forces", "shutdown", "of", "worker" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L582-L598
mjphaynes/php-resque
src/Resque/Worker.php
Worker.sigWakeUp
public function sigWakeUp() { $this->log('SIGPIPE received; attempting to wake up', Logger::DEBUG); $this->redis->establishConnection(); Event::fire(Event::WORKER_WAKEUP, $this); }
php
public function sigWakeUp() { $this->log('SIGPIPE received; attempting to wake up', Logger::DEBUG); $this->redis->establishConnection(); Event::fire(Event::WORKER_WAKEUP, $this); }
[ "public", "function", "sigWakeUp", "(", ")", "{", "$", "this", "->", "log", "(", "'SIGPIPE received; attempting to wake up'", ",", "Logger", "::", "DEBUG", ")", ";", "$", "this", "->", "redis", "->", "establishConnection", "(", ")", ";", "Event", "::", "fire...
Signal handler for SIGPIPE, in the event the Redis connection has gone away. Attempts to reconnect to Redis, or raises an Exception.
[ "Signal", "handler", "for", "SIGPIPE", "in", "the", "event", "the", "Redis", "connection", "has", "gone", "away", ".", "Attempts", "to", "reconnect", "to", "Redis", "or", "raises", "an", "Exception", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L641-L647
mjphaynes/php-resque
src/Resque/Worker.php
Worker.workingOn
public function workingOn(Job &$job) { $this->job = $job; $job->setWorker($this); Event::fire(Event::WORKER_WORKING_ON, array($this, $job)); $this->redis->hmset(self::redisKey($this), array( 'job_id' => $job->getId(), 'job_started' => microtime(true) )); }
php
public function workingOn(Job &$job) { $this->job = $job; $job->setWorker($this); Event::fire(Event::WORKER_WORKING_ON, array($this, $job)); $this->redis->hmset(self::redisKey($this), array( 'job_id' => $job->getId(), 'job_started' => microtime(true) )); }
[ "public", "function", "workingOn", "(", "Job", "&", "$", "job", ")", "{", "$", "this", "->", "job", "=", "$", "job", ";", "$", "job", "->", "setWorker", "(", "$", "this", ")", ";", "Event", "::", "fire", "(", "Event", "::", "WORKER_WORKING_ON", ","...
Tell Redis which job we're currently working on. @param Job $job Job instance containing the job we're working on.
[ "Tell", "Redis", "which", "job", "we", "re", "currently", "working", "on", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L654-L665
mjphaynes/php-resque
src/Resque/Worker.php
Worker.doneWorking
public function doneWorking() { Event::fire(Event::WORKER_DONE_WORKING, array($this, $this->job)); $this->redis->hmset(self::redisKey($this), array( 'job_id' => '', 'job_pid' => 0, 'job_started' => 0 )); switch ($this->job->getStatus()) { case Job::STATUS_COMPLETE: $this->redis->hincrby(self::redisKey($this), 'processed', 1); break; case Job::STATUS_CANCELLED: $this->redis->hincrby(self::redisKey($this), 'cancelled', 1); break; case Job::STATUS_FAILED: $this->redis->hincrby(self::redisKey($this), 'failed', 1); break; } $this->job = null; }
php
public function doneWorking() { Event::fire(Event::WORKER_DONE_WORKING, array($this, $this->job)); $this->redis->hmset(self::redisKey($this), array( 'job_id' => '', 'job_pid' => 0, 'job_started' => 0 )); switch ($this->job->getStatus()) { case Job::STATUS_COMPLETE: $this->redis->hincrby(self::redisKey($this), 'processed', 1); break; case Job::STATUS_CANCELLED: $this->redis->hincrby(self::redisKey($this), 'cancelled', 1); break; case Job::STATUS_FAILED: $this->redis->hincrby(self::redisKey($this), 'failed', 1); break; } $this->job = null; }
[ "public", "function", "doneWorking", "(", ")", "{", "Event", "::", "fire", "(", "Event", "::", "WORKER_DONE_WORKING", ",", "array", "(", "$", "this", ",", "$", "this", "->", "job", ")", ")", ";", "$", "this", "->", "redis", "->", "hmset", "(", "self"...
Notify Redis that we've finished working on a job, clearing the working state and incrementing the job stats.
[ "Notify", "Redis", "that", "we", "ve", "finished", "working", "on", "a", "job", "clearing", "the", "working", "state", "and", "incrementing", "the", "job", "stats", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L671-L694
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setStatus
public function setStatus($status) { $this->redis->hset(self::redisKey($this), 'status', $status); $oldstatus = $this->status; $this->status = $status; switch ($status) { case self::STATUS_NEW: break; case self::STATUS_RUNNING: if ($oldstatus != self::STATUS_NEW) { Event::fire(Event::WORKER_RESUME, $this); } break; case self::STATUS_PAUSED: Event::fire(Event::WORKER_PAUSE, $this); break; } }
php
public function setStatus($status) { $this->redis->hset(self::redisKey($this), 'status', $status); $oldstatus = $this->status; $this->status = $status; switch ($status) { case self::STATUS_NEW: break; case self::STATUS_RUNNING: if ($oldstatus != self::STATUS_NEW) { Event::fire(Event::WORKER_RESUME, $this); } break; case self::STATUS_PAUSED: Event::fire(Event::WORKER_PAUSE, $this); break; } }
[ "public", "function", "setStatus", "(", "$", "status", ")", "{", "$", "this", "->", "redis", "->", "hset", "(", "self", "::", "redisKey", "(", "$", "this", ")", ",", "'status'", ",", "$", "status", ")", ";", "$", "oldstatus", "=", "$", "this", "->"...
Update the status indicator for the current worker with a new status. @param int $status The status of the worker
[ "Update", "the", "status", "indicator", "for", "the", "current", "worker", "with", "a", "new", "status", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L726-L746
mjphaynes/php-resque
src/Resque/Worker.php
Worker.resolveQueues
public function resolveQueues() { if (in_array('*', $this->queues)) { $queues = $this->redis->smembers(Queue::redisKey()); is_array($queues) and sort($queues); } else { $queues = $this->queues; } if (!is_array($queues)) { $queues = array(); } return $queues; }
php
public function resolveQueues() { if (in_array('*', $this->queues)) { $queues = $this->redis->smembers(Queue::redisKey()); is_array($queues) and sort($queues); } else { $queues = $this->queues; } if (!is_array($queues)) { $queues = array(); } return $queues; }
[ "public", "function", "resolveQueues", "(", ")", "{", "if", "(", "in_array", "(", "'*'", ",", "$", "this", "->", "queues", ")", ")", "{", "$", "queues", "=", "$", "this", "->", "redis", "->", "smembers", "(", "Queue", "::", "redisKey", "(", ")", ")...
Return an array containing all of the queues that this worker should use when searching for jobs. If * is found in the list of queues, every queue will be searched in alphabetic order. @return array Array of associated queues.
[ "Return", "an", "array", "containing", "all", "of", "the", "queues", "that", "this", "worker", "should", "use", "when", "searching", "for", "jobs", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L757-L771
mjphaynes/php-resque
src/Resque/Worker.php
Worker.queueDelayed
public function queueDelayed($endTime = null, $startTime = 0) { $startTime = $startTime ?: 0; $endTime = $endTime ?: time(); foreach ($this->resolveQueues() as $queue) { $this->redis->multi(); $jobs = $this->redis->zrangebyscore(Queue::redisKey($queue, 'delayed'), $startTime, $endTime); $this->redis->zremrangebyscore(Queue::redisKey($queue, 'delayed'), $startTime, $endTime); list($jobs, $found) = $this->redis->exec(); if ($found > 0) { foreach ($jobs as $payload) { $job = Job::loadPayload($queue, $payload); $job->setWorker($this); if (Event::fire(Event::JOB_QUEUE_DELAYED, $job) !== false) { $job->queue(); Event::fire(Event::JOB_QUEUED_DELAYED, $job); } } Stats::decr('delayed', $found); Stats::decr('delayed', $found, Queue::redisKey($queue, 'stats')); $this->log('Added <pop>'.$found.'</pop> delayed job'.($found == 1 ? '' : 's').' to <pop>'.$queue.'</pop> queue', Logger::NOTICE); } } }
php
public function queueDelayed($endTime = null, $startTime = 0) { $startTime = $startTime ?: 0; $endTime = $endTime ?: time(); foreach ($this->resolveQueues() as $queue) { $this->redis->multi(); $jobs = $this->redis->zrangebyscore(Queue::redisKey($queue, 'delayed'), $startTime, $endTime); $this->redis->zremrangebyscore(Queue::redisKey($queue, 'delayed'), $startTime, $endTime); list($jobs, $found) = $this->redis->exec(); if ($found > 0) { foreach ($jobs as $payload) { $job = Job::loadPayload($queue, $payload); $job->setWorker($this); if (Event::fire(Event::JOB_QUEUE_DELAYED, $job) !== false) { $job->queue(); Event::fire(Event::JOB_QUEUED_DELAYED, $job); } } Stats::decr('delayed', $found); Stats::decr('delayed', $found, Queue::redisKey($queue, 'stats')); $this->log('Added <pop>'.$found.'</pop> delayed job'.($found == 1 ? '' : 's').' to <pop>'.$queue.'</pop> queue', Logger::NOTICE); } } }
[ "public", "function", "queueDelayed", "(", "$", "endTime", "=", "null", ",", "$", "startTime", "=", "0", ")", "{", "$", "startTime", "=", "$", "startTime", "?", ":", "0", ";", "$", "endTime", "=", "$", "endTime", "?", ":", "time", "(", ")", ";", ...
Find any delayed jobs and add them to the queue if found @param int $endTime optional end time for range @param int $startTime optional start time for range
[ "Find", "any", "delayed", "jobs", "and", "add", "them", "to", "the", "queue", "if", "found" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L779-L808
mjphaynes/php-resque
src/Resque/Worker.php
Worker.cleanup
public function cleanup() { $workers = self::allWorkers(); $hosts = $this->redis->smembers(Host::redisKey()); $cleaned = array(); foreach ($workers as $worker) { list($host, $pid) = explode(':', (string)$worker, 2); if ( ($host != (string)$this->host and in_array($host, $hosts)) or ($host == (string)$this->host and posix_kill((int)$pid, 0)) ) { continue; } $this->log('Pruning dead worker: '.$worker, Logger::DEBUG); $worker->unregister(); $cleaned[] = (string)$worker; } $workerIds = array_map( function ($w) { return (string)$w; }, $workers ); $keys = (array)$this->redis->keys('worker:'.$this->host.':*'); foreach ($keys as $key) { $key = $this->redis->removeNamespace($key); $id = substr($key, strlen('worker:')); if (!in_array($id, $workerIds)) { if ($this->redis->ttl($key) < 0) { $this->log('Expiring worker data: '.$key, Logger::DEBUG); $this->redis->expire($key, \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } } } Event::fire(Event::WORKER_CLEANUP, array($this, $cleaned)); return $cleaned; }
php
public function cleanup() { $workers = self::allWorkers(); $hosts = $this->redis->smembers(Host::redisKey()); $cleaned = array(); foreach ($workers as $worker) { list($host, $pid) = explode(':', (string)$worker, 2); if ( ($host != (string)$this->host and in_array($host, $hosts)) or ($host == (string)$this->host and posix_kill((int)$pid, 0)) ) { continue; } $this->log('Pruning dead worker: '.$worker, Logger::DEBUG); $worker->unregister(); $cleaned[] = (string)$worker; } $workerIds = array_map( function ($w) { return (string)$w; }, $workers ); $keys = (array)$this->redis->keys('worker:'.$this->host.':*'); foreach ($keys as $key) { $key = $this->redis->removeNamespace($key); $id = substr($key, strlen('worker:')); if (!in_array($id, $workerIds)) { if ($this->redis->ttl($key) < 0) { $this->log('Expiring worker data: '.$key, Logger::DEBUG); $this->redis->expire($key, \Resque::getConfig('default.expiry_time', \Resque::DEFAULT_EXPIRY_TIME)); } } } Event::fire(Event::WORKER_CLEANUP, array($this, $cleaned)); return $cleaned; }
[ "public", "function", "cleanup", "(", ")", "{", "$", "workers", "=", "self", "::", "allWorkers", "(", ")", ";", "$", "hosts", "=", "$", "this", "->", "redis", "->", "smembers", "(", "Host", "::", "redisKey", "(", ")", ")", ";", "$", "cleaned", "=",...
Look for any workers which should be running on this server and if they're not, remove them from Redis. This is a form of garbage collection to handle cases where the server may have been killed and the workers did not die gracefully and therefore leave state information in Redis.
[ "Look", "for", "any", "workers", "which", "should", "be", "running", "on", "this", "server", "and", "if", "they", "re", "not", "remove", "them", "from", "Redis", "." ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L818-L864
mjphaynes/php-resque
src/Resque/Worker.php
Worker.allWorkers
public static function allWorkers(Logger $logger = null) { if (!($ids = Redis::instance()->smembers(self::redisKey()))) { return array(); } $workers = array(); foreach ($ids as $id) { if (($worker = self::fromId($id, $logger)) !== false) { $workers[] = $worker; } } return $workers; }
php
public static function allWorkers(Logger $logger = null) { if (!($ids = Redis::instance()->smembers(self::redisKey()))) { return array(); } $workers = array(); foreach ($ids as $id) { if (($worker = self::fromId($id, $logger)) !== false) { $workers[] = $worker; } } return $workers; }
[ "public", "static", "function", "allWorkers", "(", "Logger", "$", "logger", "=", "null", ")", "{", "if", "(", "!", "(", "$", "ids", "=", "Redis", "::", "instance", "(", ")", "->", "smembers", "(", "self", "::", "redisKey", "(", ")", ")", ")", ")", ...
Return all known workers @return array
[ "Return", "all", "known", "workers" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L871-L885
mjphaynes/php-resque
src/Resque/Worker.php
Worker.hostWorker
public static function hostWorker($id, $host = null, Logger $logger = null) { $workers = self::hostWorkers($host); foreach ($workers as $worker) { if ((string)$id == (string)$worker and posix_kill($worker->getPid(), 0)) { return $worker; } } return false; }
php
public static function hostWorker($id, $host = null, Logger $logger = null) { $workers = self::hostWorkers($host); foreach ($workers as $worker) { if ((string)$id == (string)$worker and posix_kill($worker->getPid(), 0)) { return $worker; } } return false; }
[ "public", "static", "function", "hostWorker", "(", "$", "id", ",", "$", "host", "=", "null", ",", "Logger", "$", "logger", "=", "null", ")", "{", "$", "workers", "=", "self", "::", "hostWorkers", "(", "$", "host", ")", ";", "foreach", "(", "$", "wo...
Return host worker by id @param string $id Worker id @param string $host Hostname @param Logger $logger Logger @return array|false
[ "Return", "host", "worker", "by", "id" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L895-L906
mjphaynes/php-resque
src/Resque/Worker.php
Worker.hostWorkers
public static function hostWorkers($host = null, Logger $logger = null) { if (!($ids = Redis::instance()->smembers(self::redisKey()))) { return array(); } $host = $host ?: gethostname(); $workers = array(); foreach ($ids as $id) { if ( (strpos($id, $host.':') !== false) and ($worker = self::fromId($id, $logger)) !== false ) { $workers[] = $worker; } } return $workers; }
php
public static function hostWorkers($host = null, Logger $logger = null) { if (!($ids = Redis::instance()->smembers(self::redisKey()))) { return array(); } $host = $host ?: gethostname(); $workers = array(); foreach ($ids as $id) { if ( (strpos($id, $host.':') !== false) and ($worker = self::fromId($id, $logger)) !== false ) { $workers[] = $worker; } } return $workers; }
[ "public", "static", "function", "hostWorkers", "(", "$", "host", "=", "null", ",", "Logger", "$", "logger", "=", "null", ")", "{", "if", "(", "!", "(", "$", "ids", "=", "Redis", "::", "instance", "(", ")", "->", "smembers", "(", "self", "::", "redi...
Return all known workers @param string $host Hostname @param Logger $logger Logger @return array
[ "Return", "all", "known", "workers" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L915-L934
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setId
public function setId($id) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker id after worker has started working'); } $this->id = $id; }
php
public function setId($id) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker id after worker has started working'); } $this->id = $id; }
[ "public", "function", "setId", "(", "$", "id", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker id after worker has started working'", ")", ";", "}"...
Set the worker id @param string $id Id to set to
[ "Set", "the", "worker", "id" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L951-L958
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setQueues
public function setQueues($queues) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker queues after worker has started working'); } $this->queues = $queues; }
php
public function setQueues($queues) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker queues after worker has started working'); } $this->queues = $queues; }
[ "public", "function", "setQueues", "(", "$", "queues", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker queues after worker has started working'", ")", ...
Set the worker queues @param string $queues Queues for worker to watch @return array
[ "Set", "the", "worker", "queues" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L976-L983
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setPid
public function setPid($pid) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker pid after worker has started working'); } $this->pid = (int)$pid; }
php
public function setPid($pid) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker pid after worker has started working'); } $this->pid = (int)$pid; }
[ "public", "function", "setPid", "(", "$", "pid", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker pid after worker has started working'", ")", ";", ...
Set the worker process id - this is done when worker is loaded from memory @param int $pid Set worker pid
[ "Set", "the", "worker", "process", "id", "-", "this", "is", "done", "when", "worker", "is", "loaded", "from", "memory" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1001-L1008
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setPidFile
public function setPidFile($pidFile) { $dir = realpath(dirname($pidFile)); $filename = basename($pidFile); if (substr($pidFile, -1) == '/' or $filename == '.') { throw new \InvalidArgumentException('The pid file "'.$pidFile.'" must be a valid file path'); } if (!is_dir($dir)) { throw new \RuntimeException('The pid file directory "'.$dir.'" does not exist'); } if (!is_writeable($dir)) { throw new \RuntimeException('The pid file directory "'.$dir.'" is not writeable'); } $this->pidFile = $dir.'/'.$filename; if (file_exists($this->pidFile) and posix_kill((int)trim(file_get_contents($this->pidFile)), 0)) { throw new \RuntimeException('Pid file "'.$pidFile.'" already exists and worker is still running.'); } if (!file_put_contents($this->pidFile, getmypid(), LOCK_EX)) { throw new \RuntimeException('Could not write pid to file "'.$pidFile.'"'); } }
php
public function setPidFile($pidFile) { $dir = realpath(dirname($pidFile)); $filename = basename($pidFile); if (substr($pidFile, -1) == '/' or $filename == '.') { throw new \InvalidArgumentException('The pid file "'.$pidFile.'" must be a valid file path'); } if (!is_dir($dir)) { throw new \RuntimeException('The pid file directory "'.$dir.'" does not exist'); } if (!is_writeable($dir)) { throw new \RuntimeException('The pid file directory "'.$dir.'" is not writeable'); } $this->pidFile = $dir.'/'.$filename; if (file_exists($this->pidFile) and posix_kill((int)trim(file_get_contents($this->pidFile)), 0)) { throw new \RuntimeException('Pid file "'.$pidFile.'" already exists and worker is still running.'); } if (!file_put_contents($this->pidFile, getmypid(), LOCK_EX)) { throw new \RuntimeException('Could not write pid to file "'.$pidFile.'"'); } }
[ "public", "function", "setPidFile", "(", "$", "pidFile", ")", "{", "$", "dir", "=", "realpath", "(", "dirname", "(", "$", "pidFile", ")", ")", ";", "$", "filename", "=", "basename", "(", "$", "pidFile", ")", ";", "if", "(", "substr", "(", "$", "pid...
Set the worker pid file @param string $pidFile Filename to store pid in @throws \Exception
[ "Set", "the", "worker", "pid", "file" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1026-L1052
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setHost
public function setHost(Host $host) { $this->host = $host; if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker host after worker has started working'); } }
php
public function setHost(Host $host) { $this->host = $host; if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker host after worker has started working'); } }
[ "public", "function", "setHost", "(", "Host", "$", "host", ")", "{", "$", "this", "->", "host", "=", "$", "host", ";", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", ...
Set the queue host @param Host $host The host to set for this worker
[ "Set", "the", "queue", "host" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1069-L1076
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setBlocking
public function setBlocking($blocking) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker blocking after worker has started working'); } $this->blocking = (bool)$blocking; }
php
public function setBlocking($blocking) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker blocking after worker has started working'); } $this->blocking = (bool)$blocking; }
[ "public", "function", "setBlocking", "(", "$", "blocking", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker blocking after worker has started working'", ...
Set the queue blocking @param bool $blocking Should worker use Redis blocking
[ "Set", "the", "queue", "blocking" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1128-L1135
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setInterval
public function setInterval($interval) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker interval after worker has started working'); } $this->interval = $interval; }
php
public function setInterval($interval) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker interval after worker has started working'); } $this->interval = $interval; }
[ "public", "function", "setInterval", "(", "$", "interval", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker interval after worker has started working'", ...
Set the worker interval @param int $interval The worker interval
[ "Set", "the", "worker", "interval" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1152-L1159
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setTimeout
public function setTimeout($timeout) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker timeout after worker has started working'); } $this->timeout = $timeout; }
php
public function setTimeout($timeout) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker timeout after worker has started working'); } $this->timeout = $timeout; }
[ "public", "function", "setTimeout", "(", "$", "timeout", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker timeout after worker has started working'", ")...
Set the worker queue timeout @param string $timeout Worker queue timeout @return string
[ "Set", "the", "worker", "queue", "timeout" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1177-L1184
mjphaynes/php-resque
src/Resque/Worker.php
Worker.setMemoryLimit
public function setMemoryLimit($memoryLimit) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker memory limit after worker has started working'); } $this->memoryLimit = $memoryLimit; }
php
public function setMemoryLimit($memoryLimit) { if ($this->status != self::STATUS_NEW) { throw new \RuntimeException('Cannot set worker memory limit after worker has started working'); } $this->memoryLimit = $memoryLimit; }
[ "public", "function", "setMemoryLimit", "(", "$", "memoryLimit", ")", "{", "if", "(", "$", "this", "->", "status", "!=", "self", "::", "STATUS_NEW", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Cannot set worker memory limit after worker has started wo...
Set the queue memory limit @param int $memoryLimit Memory limit
[ "Set", "the", "queue", "memory", "limit" ]
train
https://github.com/mjphaynes/php-resque/blob/d35cd7bcf3b4b00da65afaaae60098dba3be8b60/src/Resque/Worker.php#L1201-L1208