repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
hail-framework/framework
src/I18n/Gettext/Translator.php
Translator.fixTerseIfs
private static function fixTerseIfs($code, $inner = false) { /* * (?P<expression>[^?]+) Capture everything up to ? as 'expression' * \? ? * (?P<success>[^:]+) Capture everything up to : as 'success' * : : * (?P<failure>[^;]+) Capture everything up to ; as 'failure' */ \preg_match('/(?P<expression>[^?]+)\?(?P<success>[^:]+):(?P<failure>[^;]+)/', $code, $matches); // If no match was found then no terse if was present if (!isset($matches[0])) { return $code; } $expression = $matches['expression']; $success = $matches['success']; $failure = $matches['failure']; // Go look for another terse if in the failure state. $failure = self::fixTerseIfs($failure, true); $code = $expression.' ? '.$success.' : '.$failure; if ($inner) { return "($code)"; } // note the semicolon. We need that for executing the code. return "$code;"; }
php
private static function fixTerseIfs($code, $inner = false) { /* * (?P<expression>[^?]+) Capture everything up to ? as 'expression' * \? ? * (?P<success>[^:]+) Capture everything up to : as 'success' * : : * (?P<failure>[^;]+) Capture everything up to ; as 'failure' */ \preg_match('/(?P<expression>[^?]+)\?(?P<success>[^:]+):(?P<failure>[^;]+)/', $code, $matches); // If no match was found then no terse if was present if (!isset($matches[0])) { return $code; } $expression = $matches['expression']; $success = $matches['success']; $failure = $matches['failure']; // Go look for another terse if in the failure state. $failure = self::fixTerseIfs($failure, true); $code = $expression.' ? '.$success.' : '.$failure; if ($inner) { return "($code)"; } // note the semicolon. We need that for executing the code. return "$code;"; }
[ "private", "static", "function", "fixTerseIfs", "(", "$", "code", ",", "$", "inner", "=", "false", ")", "{", "/*\n * (?P<expression>[^?]+) Capture everything up to ? as 'expression'\n * \\? ?\n * (?P<success>[^:]+) Capture everything up...
This function will recursively wrap failure states in brackets if they contain a nested terse if. This because PHP can not handle nested terse if's unless they are wrapped in brackets. This code probably only works for the gettext plural decision codes. return ($n==1 ? 0 : $n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2); becomes return ($n==1 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2)); @param string $code the terse if string @param bool $inner If inner is true we wrap it in brackets @return string A formatted terse If that PHP can work with.
[ "This", "function", "will", "recursively", "wrap", "failure", "states", "in", "brackets", "if", "they", "contain", "a", "nested", "terse", "if", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/I18n/Gettext/Translator.php#L267-L297
train
Kajna/K-Core
Core/Core/Controller.php
Controller.render
protected function render($view, array $data = []) { // Extract variables. extract($data); // Start buffering. ob_start(); // Load view file (root location is declared in viewPath var). include $this->container->get('config')['viewsPath'] . '/' . $view . '.php'; // Get buffered content $body = ob_get_contents(); ob_end_clean(); // Make response and add body to it $response = new Response(); $response->writeBody($body); return $response; }
php
protected function render($view, array $data = []) { // Extract variables. extract($data); // Start buffering. ob_start(); // Load view file (root location is declared in viewPath var). include $this->container->get('config')['viewsPath'] . '/' . $view . '.php'; // Get buffered content $body = ob_get_contents(); ob_end_clean(); // Make response and add body to it $response = new Response(); $response->writeBody($body); return $response; }
[ "protected", "function", "render", "(", "$", "view", ",", "array", "$", "data", "=", "[", "]", ")", "{", "// Extract variables.", "extract", "(", "$", "data", ")", ";", "// Start buffering.", "ob_start", "(", ")", ";", "// Load view file (root location is declar...
Render output for display. @param string $view @param array $data @return ResponseInterface
[ "Render", "output", "for", "display", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Core/Controller.php#L30-L49
train
Kajna/K-Core
Core/Core/Controller.php
Controller.buffer
protected function buffer($view, array $data = []) { // Extract variables. extract($data); // Start buffering. ob_start(); // Load view file (root location is declared in viewsPath var). include $this->container->get('config')['viewsPath'] . '/' . $view . '.php'; // Return string. $buffer = ob_get_contents(); ob_end_clean(); return $buffer; }
php
protected function buffer($view, array $data = []) { // Extract variables. extract($data); // Start buffering. ob_start(); // Load view file (root location is declared in viewsPath var). include $this->container->get('config')['viewsPath'] . '/' . $view . '.php'; // Return string. $buffer = ob_get_contents(); ob_end_clean(); return $buffer; }
[ "protected", "function", "buffer", "(", "$", "view", ",", "array", "$", "data", "=", "[", "]", ")", "{", "// Extract variables.", "extract", "(", "$", "data", ")", ";", "// Start buffering.", "ob_start", "(", ")", ";", "// Load view file (root location is declar...
Buffer output and return it as string. @param string $view @param array $data @return string
[ "Buffer", "output", "and", "return", "it", "as", "string", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Core/Controller.php#L58-L73
train
hail-framework/framework
src/Debugger/Logger.php
Logger.log
public function log($level, $message, array $context = []): void { if (!isset($this->logLevels[$level])) { $level = LogLevel::DEBUG; } $this->exceptionFile = null; if ($this->logLevels[$level] < $this->level) { return; } $exceptionFile = null; if (isset($context['exception']) && $context['exception'] instanceof \Throwable) { $exceptionFile = $this->getExceptionFile($context['exception']); } if (SEASLOG_EXTENSION) { $message .= $exceptionFile ? ' @@ ' . \basename($exceptionFile) : ''; \SeasLog::log($level, $message, $context); } else { $message = Dumper::interpolate($message, $context); $line = static::formatLogLine($message, $exceptionFile); $file = $this->directory . '/' . $level . '.log'; if (!@\file_put_contents($file, $line . PHP_EOL, FILE_APPEND | LOCK_EX)) { // @ is escalated to exception throw new \RuntimeException("Unable to write to log file '$file'. Is directory writable?"); } } if ($exceptionFile) { $this->logException($context['exception'], $exceptionFile); } if (\in_array($level, [LogLevel::ERROR, LogLevel::EMERGENCY, LogLevel::CRITICAL, LogLevel::ALERT], true)) { $this->sendEmail($message); } $this->exceptionFile = $exceptionFile; }
php
public function log($level, $message, array $context = []): void { if (!isset($this->logLevels[$level])) { $level = LogLevel::DEBUG; } $this->exceptionFile = null; if ($this->logLevels[$level] < $this->level) { return; } $exceptionFile = null; if (isset($context['exception']) && $context['exception'] instanceof \Throwable) { $exceptionFile = $this->getExceptionFile($context['exception']); } if (SEASLOG_EXTENSION) { $message .= $exceptionFile ? ' @@ ' . \basename($exceptionFile) : ''; \SeasLog::log($level, $message, $context); } else { $message = Dumper::interpolate($message, $context); $line = static::formatLogLine($message, $exceptionFile); $file = $this->directory . '/' . $level . '.log'; if (!@\file_put_contents($file, $line . PHP_EOL, FILE_APPEND | LOCK_EX)) { // @ is escalated to exception throw new \RuntimeException("Unable to write to log file '$file'. Is directory writable?"); } } if ($exceptionFile) { $this->logException($context['exception'], $exceptionFile); } if (\in_array($level, [LogLevel::ERROR, LogLevel::EMERGENCY, LogLevel::CRITICAL, LogLevel::ALERT], true)) { $this->sendEmail($message); } $this->exceptionFile = $exceptionFile; }
[ "public", "function", "log", "(", "$", "level", ",", "$", "message", ",", "array", "$", "context", "=", "[", "]", ")", ":", "void", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "logLevels", "[", "$", "level", "]", ")", ")", "{", "$", ...
Logs message or exception to file and sends email notification. @param mixed $level @param string $message @param array $context @return void
[ "Logs", "message", "or", "exception", "to", "file", "and", "sends", "email", "notification", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Logger.php#L99-L140
train
hail-framework/framework
src/Debugger/Logger.php
Logger.logException
protected function logException(\Throwable $exception, string $file = null): string { $file = $file ?: $this->getExceptionFile($exception); $bs = $this->blueScreen ?: new BlueScreen; $bs->renderToFile($exception, $file); return $file; }
php
protected function logException(\Throwable $exception, string $file = null): string { $file = $file ?: $this->getExceptionFile($exception); $bs = $this->blueScreen ?: new BlueScreen; $bs->renderToFile($exception, $file); return $file; }
[ "protected", "function", "logException", "(", "\\", "Throwable", "$", "exception", ",", "string", "$", "file", "=", "null", ")", ":", "string", "{", "$", "file", "=", "$", "file", "?", ":", "$", "this", "->", "getExceptionFile", "(", "$", "exception", ...
Logs exception to the file if file doesn't exist. @param \Throwable $exception @param string $file @return string logged error filename
[ "Logs", "exception", "to", "the", "file", "if", "file", "doesn", "t", "exist", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Logger.php#L208-L215
train
hail-framework/framework
src/Debugger/Logger.php
Logger.defaultMailer
public function defaultMailer($message, string $email): void { $host = \preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n')); $parts = \str_replace( ["\r\n", "\n"], ["\n", PHP_EOL], [ 'headers' => \implode("\n", [ 'From: ' . ($this->fromEmail ?: "noreply@$host"), 'X-Mailer: Tracy', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', ]) . "\n", 'subject' => "PHP: An error occurred on the server $host", 'body' => Dumper::formatMessage($message) . "\n\nsource: " . Helpers::getSource(), ] ); \mail($email, $parts['subject'], $parts['body'], $parts['headers']); }
php
public function defaultMailer($message, string $email): void { $host = \preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n')); $parts = \str_replace( ["\r\n", "\n"], ["\n", PHP_EOL], [ 'headers' => \implode("\n", [ 'From: ' . ($this->fromEmail ?: "noreply@$host"), 'X-Mailer: Tracy', 'Content-Type: text/plain; charset=UTF-8', 'Content-Transfer-Encoding: 8bit', ]) . "\n", 'subject' => "PHP: An error occurred on the server $host", 'body' => Dumper::formatMessage($message) . "\n\nsource: " . Helpers::getSource(), ] ); \mail($email, $parts['subject'], $parts['body'], $parts['headers']); }
[ "public", "function", "defaultMailer", "(", "$", "message", ",", "string", "$", "email", ")", ":", "void", "{", "$", "host", "=", "\\", "preg_replace", "(", "'#[^\\w.-]+#'", ",", "''", ",", "$", "_SERVER", "[", "'HTTP_HOST'", "]", "??", "php_uname", "(",...
Default mailer. @param mixed @param string @return void @internal
[ "Default", "mailer", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Logger.php#L247-L266
train
Kajna/K-Core
Core/Routing/Router.php
Router.execute
public function execute($uri, $requestMethod) { foreach ($this->routes as $route) { if (true === $route->matches($uri, $requestMethod)) { return $route; } } return null; }
php
public function execute($uri, $requestMethod) { foreach ($this->routes as $route) { if (true === $route->matches($uri, $requestMethod)) { return $route; } } return null; }
[ "public", "function", "execute", "(", "$", "uri", ",", "$", "requestMethod", ")", "{", "foreach", "(", "$", "this", "->", "routes", "as", "$", "route", ")", "{", "if", "(", "true", "===", "$", "route", "->", "matches", "(", "$", "uri", ",", "$", ...
Check routes and returns matching one if found, otherwise return null. @var string $uri @var string $requestMethod @return null|RouteInterface
[ "Check", "routes", "and", "returns", "matching", "one", "if", "found", "otherwise", "return", "null", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Routing/Router.php#L48-L56
train
Kajna/K-Core
Core/Routing/Router.php
Router.put
public function put($url, $class, $function) { $route = new Route($this->urlPrefix . $url, 'PUT', self::$CONTROLLERS_ROOT . $class, $function); $this->addRoute($route); return $route; }
php
public function put($url, $class, $function) { $route = new Route($this->urlPrefix . $url, 'PUT', self::$CONTROLLERS_ROOT . $class, $function); $this->addRoute($route); return $route; }
[ "public", "function", "put", "(", "$", "url", ",", "$", "class", ",", "$", "function", ")", "{", "$", "route", "=", "new", "Route", "(", "$", "this", "->", "urlPrefix", ".", "$", "url", ",", "'PUT'", ",", "self", "::", "$", "CONTROLLERS_ROOT", ".",...
Add a route object to the router accepting PUT request method. @param string $url @param string $class @param string $function @return RouteInterface
[ "Add", "a", "route", "object", "to", "the", "router", "accepting", "PUT", "request", "method", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Routing/Router.php#L96-L101
train
Kajna/K-Core
Core/Routing/Router.php
Router.addRoute
public function addRoute(RouteInterface $route) { foreach ($this->middlewares as $m) { $route->addMiddleware($m); } $this->routes[] = $route; return $this; }
php
public function addRoute(RouteInterface $route) { foreach ($this->middlewares as $m) { $route->addMiddleware($m); } $this->routes[] = $route; return $this; }
[ "public", "function", "addRoute", "(", "RouteInterface", "$", "route", ")", "{", "foreach", "(", "$", "this", "->", "middlewares", "as", "$", "m", ")", "{", "$", "route", "->", "addMiddleware", "(", "$", "m", ")", ";", "}", "$", "this", "->", "routes...
Add custom route object to routes array. @param RouteInterface $route @return self
[ "Add", "custom", "route", "object", "to", "routes", "array", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Routing/Router.php#L174-L181
train
hiqdev/hipanel-module-server
src/widgets/OSFormatter.php
OSFormatter.generateInfoCircle
public function generateInfoCircle() { Modal::begin([ 'toggleButton' => [ 'class' => 'fa fa-info text-info os-info-popover', 'label' => '', ], 'header' => Html::tag('h4', $this->osimage->getFullOsName()), 'size' => Modal::SIZE_LARGE, ]); echo Html::tag('div', $this->generateOSInfo(), [ 'class' => 'table-responsive', ]); Modal::end(); }
php
public function generateInfoCircle() { Modal::begin([ 'toggleButton' => [ 'class' => 'fa fa-info text-info os-info-popover', 'label' => '', ], 'header' => Html::tag('h4', $this->osimage->getFullOsName()), 'size' => Modal::SIZE_LARGE, ]); echo Html::tag('div', $this->generateOSInfo(), [ 'class' => 'table-responsive', ]); Modal::end(); }
[ "public", "function", "generateInfoCircle", "(", ")", "{", "Modal", "::", "begin", "(", "[", "'toggleButton'", "=>", "[", "'class'", "=>", "'fa fa-info text-info os-info-popover'", ",", "'label'", "=>", "''", ",", "]", ",", "'header'", "=>", "Html", "::", "tag...
Renders info-circle with modal popup.
[ "Renders", "info", "-", "circle", "with", "modal", "popup", "." ]
e40c3601952cf1fd420ebb97093ee17a33ff3207
https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/widgets/OSFormatter.php#L85-L99
train
DoSomething/gateway
src/Laravel/HasNorthstarToken.php
HasNorthstarToken.getOAuthToken
public function getOAuthToken() { // If any of the required fields are empty, return null. $hasAnEmptyField = empty($this->northstar_id) || empty($this->access_token) || empty($this->access_token_expiration) || empty($this->refresh_token) || empty($this->role); if ($hasAnEmptyField) { return null; } return new AccessToken([ 'resource_owner_id' => $this->getNorthstarIdentifier(), 'access_token' => $this->access_token, 'refresh_token' => $this->refresh_token, 'expires' => $this->access_token_expiration, 'role' => $this->role, ]); }
php
public function getOAuthToken() { // If any of the required fields are empty, return null. $hasAnEmptyField = empty($this->northstar_id) || empty($this->access_token) || empty($this->access_token_expiration) || empty($this->refresh_token) || empty($this->role); if ($hasAnEmptyField) { return null; } return new AccessToken([ 'resource_owner_id' => $this->getNorthstarIdentifier(), 'access_token' => $this->access_token, 'refresh_token' => $this->refresh_token, 'expires' => $this->access_token_expiration, 'role' => $this->role, ]); }
[ "public", "function", "getOAuthToken", "(", ")", "{", "// If any of the required fields are empty, return null.", "$", "hasAnEmptyField", "=", "empty", "(", "$", "this", "->", "northstar_id", ")", "||", "empty", "(", "$", "this", "->", "access_token", ")", "||", "...
Get the access token for the user. @return AccessToken|null
[ "Get", "the", "access", "token", "for", "the", "user", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Laravel/HasNorthstarToken.php#L72-L89
train
DoSomething/gateway
src/Laravel/HasNorthstarToken.php
HasNorthstarToken.setOAuthToken
public function setOAuthToken(AccessToken $token) { $this->access_token = $token->getToken(); $this->access_token_expiration = $token->getExpires(); $this->refresh_token = $token->getRefreshToken(); $this->role = $token->getValues()['role']; }
php
public function setOAuthToken(AccessToken $token) { $this->access_token = $token->getToken(); $this->access_token_expiration = $token->getExpires(); $this->refresh_token = $token->getRefreshToken(); $this->role = $token->getValues()['role']; }
[ "public", "function", "setOAuthToken", "(", "AccessToken", "$", "token", ")", "{", "$", "this", "->", "access_token", "=", "$", "token", "->", "getToken", "(", ")", ";", "$", "this", "->", "access_token_expiration", "=", "$", "token", "->", "getExpires", "...
Save the access token for the user. @param AccessToken $token
[ "Save", "the", "access", "token", "for", "the", "user", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Laravel/HasNorthstarToken.php#L96-L102
train
DoSomething/gateway
src/Laravel/HasNorthstarToken.php
HasNorthstarToken.clearOAuthToken
public function clearOAuthToken() { $this->access_token = null; $this->access_token_expiration = null; $this->refresh_token = null; }
php
public function clearOAuthToken() { $this->access_token = null; $this->access_token_expiration = null; $this->refresh_token = null; }
[ "public", "function", "clearOAuthToken", "(", ")", "{", "$", "this", "->", "access_token", "=", "null", ";", "$", "this", "->", "access_token_expiration", "=", "null", ";", "$", "this", "->", "refresh_token", "=", "null", ";", "}" ]
Clear the access token for the user. @return void
[ "Clear", "the", "access", "token", "for", "the", "user", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Laravel/HasNorthstarToken.php#L109-L114
train
jormin/aliyun
sdk/aliyun-opensearch-php-sdk/OpenSearch/Thrift/Protocol/TProtocol.php
TProtocol.skip
public function skip($type) { switch ($type) { case TType::BOOL: return $this->readBool($bool); case TType::BYTE: return $this->readByte($byte); case TType::I16: return $this->readI16($i16); case TType::I32: return $this->readI32($i32); case TType::I64: return $this->readI64($i64); case TType::DOUBLE: return $this->readDouble($dub); case TType::STRING: return $this->readString($str); case TType::STRUCT: { $result = $this->readStructBegin($name); while (true) { $result += $this->readFieldBegin($name, $ftype, $fid); if ($ftype == TType::STOP) { break; } $result += $this->skip($ftype); $result += $this->readFieldEnd(); } $result += $this->readStructEnd(); return $result; } case TType::MAP: { $result = $this->readMapBegin($keyType, $valType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($keyType); $result += $this->skip($valType); } $result += $this->readMapEnd(); return $result; } case TType::SET: { $result = $this->readSetBegin($elemType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($elemType); } $result += $this->readSetEnd(); return $result; } case TType::LST: { $result = $this->readListBegin($elemType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($elemType); } $result += $this->readListEnd(); return $result; } default: throw new TProtocolException('Unknown field type: '.$type, TProtocolException::INVALID_DATA); } }
php
public function skip($type) { switch ($type) { case TType::BOOL: return $this->readBool($bool); case TType::BYTE: return $this->readByte($byte); case TType::I16: return $this->readI16($i16); case TType::I32: return $this->readI32($i32); case TType::I64: return $this->readI64($i64); case TType::DOUBLE: return $this->readDouble($dub); case TType::STRING: return $this->readString($str); case TType::STRUCT: { $result = $this->readStructBegin($name); while (true) { $result += $this->readFieldBegin($name, $ftype, $fid); if ($ftype == TType::STOP) { break; } $result += $this->skip($ftype); $result += $this->readFieldEnd(); } $result += $this->readStructEnd(); return $result; } case TType::MAP: { $result = $this->readMapBegin($keyType, $valType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($keyType); $result += $this->skip($valType); } $result += $this->readMapEnd(); return $result; } case TType::SET: { $result = $this->readSetBegin($elemType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($elemType); } $result += $this->readSetEnd(); return $result; } case TType::LST: { $result = $this->readListBegin($elemType, $size); for ($i = 0; $i < $size; $i++) { $result += $this->skip($elemType); } $result += $this->readListEnd(); return $result; } default: throw new TProtocolException('Unknown field type: '.$type, TProtocolException::INVALID_DATA); } }
[ "public", "function", "skip", "(", "$", "type", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "TType", "::", "BOOL", ":", "return", "$", "this", "->", "readBool", "(", "$", "bool", ")", ";", "case", "TType", "::", "BYTE", ":", "return", ...
The skip function is a utility to parse over unrecognized date without causing corruption. @param TType $type What type is it
[ "The", "skip", "function", "is", "a", "utility", "to", "parse", "over", "unrecognized", "date", "without", "causing", "corruption", "." ]
c0eb19f5c265dba1f463af1db7347acdcfddb240
https://github.com/jormin/aliyun/blob/c0eb19f5c265dba1f463af1db7347acdcfddb240/sdk/aliyun-opensearch-php-sdk/OpenSearch/Thrift/Protocol/TProtocol.php#L184-L251
train
hiqdev/hipanel-module-server
src/forms/ServerForm.php
ServerForm.fromServer
public static function fromServer(Server $server): ServerForm { return new self(array_merge($server->getAttributes(), ['server' => $server->name, 'scenario' => 'update'], [ 'ips' => implode(',', ArrayHelper::getColumn($server->ips, 'ip')), ])); }
php
public static function fromServer(Server $server): ServerForm { return new self(array_merge($server->getAttributes(), ['server' => $server->name, 'scenario' => 'update'], [ 'ips' => implode(',', ArrayHelper::getColumn($server->ips, 'ip')), ])); }
[ "public", "static", "function", "fromServer", "(", "Server", "$", "server", ")", ":", "ServerForm", "{", "return", "new", "self", "(", "array_merge", "(", "$", "server", "->", "getAttributes", "(", ")", ",", "[", "'server'", "=>", "$", "server", "->", "n...
Create ServerForm model from Server model. @param Server $server @return ServerForm
[ "Create", "ServerForm", "model", "from", "Server", "model", "." ]
e40c3601952cf1fd420ebb97093ee17a33ff3207
https://github.com/hiqdev/hipanel-module-server/blob/e40c3601952cf1fd420ebb97093ee17a33ff3207/src/forms/ServerForm.php#L39-L44
train
hail-framework/framework
src/Http/Header.php
Header.replace
public function replace(array $headers = []): void { $this->headerNames = []; $this->headers = []; $headers !== [] && $this->add($headers); if (!isset($this->headers['Cache-Control'])) { $this->set('Cache-Control', ''); } }
php
public function replace(array $headers = []): void { $this->headerNames = []; $this->headers = []; $headers !== [] && $this->add($headers); if (!isset($this->headers['Cache-Control'])) { $this->set('Cache-Control', ''); } }
[ "public", "function", "replace", "(", "array", "$", "headers", "=", "[", "]", ")", ":", "void", "{", "$", "this", "->", "headerNames", "=", "[", "]", ";", "$", "this", "->", "headers", "=", "[", "]", ";", "$", "headers", "!==", "[", "]", "&&", ...
Replaces the current HTTP headers by a new set. @param array $headers An array of HTTP headers @throws \LogicException
[ "Replaces", "the", "current", "HTTP", "headers", "by", "a", "new", "set", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Header.php#L55-L65
train
hail-framework/framework
src/Http/Header.php
Header.has
public function has($key) { if (\strpos($key, '_')) { $key = \str_replace('_', '-', $key); } return isset($this->headerNames[\strtolower($key)]); }
php
public function has($key) { if (\strpos($key, '_')) { $key = \str_replace('_', '-', $key); } return isset($this->headerNames[\strtolower($key)]); }
[ "public", "function", "has", "(", "$", "key", ")", "{", "if", "(", "\\", "strpos", "(", "$", "key", ",", "'_'", ")", ")", "{", "$", "key", "=", "\\", "str_replace", "(", "'_'", ",", "'-'", ",", "$", "key", ")", ";", "}", "return", "isset", "(...
Returns true if the HTTP header is defined. @param string $key The HTTP header @return bool true if the parameter exists, false otherwise
[ "Returns", "true", "if", "the", "HTTP", "header", "is", "defined", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Header.php#L162-L169
train
hail-framework/framework
src/Http/Header.php
Header.hasCacheControlDirective
public function hasCacheControlDirective($key) { return isset($this->computedCacheControl[$key]) || \array_key_exists($key, $this->computedCacheControl); }
php
public function hasCacheControlDirective($key) { return isset($this->computedCacheControl[$key]) || \array_key_exists($key, $this->computedCacheControl); }
[ "public", "function", "hasCacheControlDirective", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "this", "->", "computedCacheControl", "[", "$", "key", "]", ")", "||", "\\", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "computedCac...
Returns true if the Cache-Control directive is defined. @param string $key The Cache-Control directive @return bool true if the directive exists, false otherwise
[ "Returns", "true", "if", "the", "Cache", "-", "Control", "directive", "is", "defined", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Header.php#L218-L221
train
hail-framework/framework
src/Http/Header.php
Header.parseCacheControl
protected function parseCacheControl($header) { $cacheControl = []; \preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $cacheControl[\strtolower($match[1])] = $match[3] ?? ($match[2] ?? true); } return $cacheControl; }
php
protected function parseCacheControl($header) { $cacheControl = []; \preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $cacheControl[\strtolower($match[1])] = $match[3] ?? ($match[2] ?? true); } return $cacheControl; }
[ "protected", "function", "parseCacheControl", "(", "$", "header", ")", "{", "$", "cacheControl", "=", "[", "]", ";", "\\", "preg_match_all", "(", "'#([a-zA-Z][a-zA-Z_-]*)\\s*(?:=(?:\"([^\"]*)\"|([^ \\t\",;]*)))?#'", ",", "$", "header", ",", "$", "matches", ",", "PRE...
Parses a Cache-Control HTTP header. @param string $header The value of the Cache-Control HTTP header @return array An array representing the attribute values
[ "Parses", "a", "Cache", "-", "Control", "HTTP", "header", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Header.php#L415-L424
train
hail-framework/framework
src/Http/RequestHandler.php
RequestHandler.get
protected function get(ServerRequestInterface $request, bool $next = false): ?MiddlewareInterface { $index = $next ? ++$this->index : $this->index; if (!isset($this->middleware[$index])) { return null; } $middleware = $this->middleware[$index]; if (\is_array($middleware)) { $conditions = $middleware; $middleware = \array_pop($conditions); if (!Matcher\Factory::matches($conditions, $request)) { return $this->get($request, true); } } if (\is_callable($middleware)) { return new Middleware\CallableWrapper($middleware); } if (\is_string($middleware)) { if ($this->container === null) { throw new \RuntimeException("No valid middleware provided: $middleware"); } $middleware = $this->container->get($middleware); } if (!$middleware instanceof MiddlewareInterface) { throw new \RuntimeException('The middleware must be an instance of MiddlewareInterface'); } return $middleware; }
php
protected function get(ServerRequestInterface $request, bool $next = false): ?MiddlewareInterface { $index = $next ? ++$this->index : $this->index; if (!isset($this->middleware[$index])) { return null; } $middleware = $this->middleware[$index]; if (\is_array($middleware)) { $conditions = $middleware; $middleware = \array_pop($conditions); if (!Matcher\Factory::matches($conditions, $request)) { return $this->get($request, true); } } if (\is_callable($middleware)) { return new Middleware\CallableWrapper($middleware); } if (\is_string($middleware)) { if ($this->container === null) { throw new \RuntimeException("No valid middleware provided: $middleware"); } $middleware = $this->container->get($middleware); } if (!$middleware instanceof MiddlewareInterface) { throw new \RuntimeException('The middleware must be an instance of MiddlewareInterface'); } return $middleware; }
[ "protected", "function", "get", "(", "ServerRequestInterface", "$", "request", ",", "bool", "$", "next", "=", "false", ")", ":", "?", "MiddlewareInterface", "{", "$", "index", "=", "$", "next", "?", "++", "$", "this", "->", "index", ":", "$", "this", "...
Return the current or next available middleware frame in the middleware. @param ServerRequestInterface $request @param bool $next @return null|MiddlewareInterface @throws
[ "Return", "the", "current", "or", "next", "available", "middleware", "frame", "in", "the", "middleware", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/RequestHandler.php#L87-L123
train
hail-framework/framework
src/Http/Middleware/BasePath.php
BasePath.addBasePath
private function addBasePath($path) { if (\strpos($path, $this->basePath) === 0) { return $path; } return \str_replace('//', '/', $this->basePath . '/' . $path); }
php
private function addBasePath($path) { if (\strpos($path, $this->basePath) === 0) { return $path; } return \str_replace('//', '/', $this->basePath . '/' . $path); }
[ "private", "function", "addBasePath", "(", "$", "path", ")", "{", "if", "(", "\\", "strpos", "(", "$", "path", ",", "$", "this", "->", "basePath", ")", "===", "0", ")", "{", "return", "$", "path", ";", "}", "return", "\\", "str_replace", "(", "'//'...
Adds the basepath to a path. @param string $path @return string
[ "Adds", "the", "basepath", "to", "a", "path", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Http/Middleware/BasePath.php#L111-L118
train
hail-framework/framework
src/Image/Commands/Argument.php
Argument.required
public function required() { if (!array_key_exists($this->key, $this->command->arguments)) { throw new \Hail\Image\Exception\InvalidArgumentException( sprintf('Missing argument %d for %s', $this->key + 1, $this->getCommandName()) ); } return $this; }
php
public function required() { if (!array_key_exists($this->key, $this->command->arguments)) { throw new \Hail\Image\Exception\InvalidArgumentException( sprintf('Missing argument %d for %s', $this->key + 1, $this->getCommandName()) ); } return $this; }
[ "public", "function", "required", "(", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "this", "->", "key", ",", "$", "this", "->", "command", "->", "arguments", ")", ")", "{", "throw", "new", "\\", "Hail", "\\", "Image", "\\", "Exception", "...
Defines current argument as required @return self
[ "Defines", "current", "argument", "as", "required" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/Commands/Argument.php#L68-L77
train
hiqdev/hipanel-module-dns
src/models/Record.php
Record.buildRuleWhen
protected function buildRuleWhen($type, $not = false) { return function ($model) use ($type, $not) { /* @var $model Record */ return $not xor in_array($model->type, (array) $type, true); }; }
php
protected function buildRuleWhen($type, $not = false) { return function ($model) use ($type, $not) { /* @var $model Record */ return $not xor in_array($model->type, (array) $type, true); }; }
[ "protected", "function", "buildRuleWhen", "(", "$", "type", ",", "$", "not", "=", "false", ")", "{", "return", "function", "(", "$", "model", ")", "use", "(", "$", "type", ",", "$", "not", ")", "{", "/* @var $model Record */", "return", "$", "not", "xo...
Builds a closure for Yii server-side validation property `when` in order to apply the rule to only a certain list of DNS record types. @param array|string $type types, that are must be validated with the rule @param bool $not inverts $type @return \Closure
[ "Builds", "a", "closure", "for", "Yii", "server", "-", "side", "validation", "property", "when", "in", "order", "to", "apply", "the", "rule", "to", "only", "a", "certain", "list", "of", "DNS", "record", "types", "." ]
7e9199c95d91a979b7bd4fd07fe801dbe9e69183
https://github.com/hiqdev/hipanel-module-dns/blob/7e9199c95d91a979b7bd4fd07fe801dbe9e69183/src/models/Record.php#L156-L162
train
hiqdev/hipanel-module-dns
src/models/Record.php
Record.buildRuleWhenClient
protected function buildRuleWhenClient($type, $not = false) { $not = Json::encode($not); $types = Json::encode((array) $type); return new JsExpression(" function (attribute, value) { var type = $(attribute.input).closest('.record-item').find('[data-attribute=type]'); if (!type) return true; var types = $types; return $not !== (types.indexOf(type.val()) > -1); } "); }
php
protected function buildRuleWhenClient($type, $not = false) { $not = Json::encode($not); $types = Json::encode((array) $type); return new JsExpression(" function (attribute, value) { var type = $(attribute.input).closest('.record-item').find('[data-attribute=type]'); if (!type) return true; var types = $types; return $not !== (types.indexOf(type.val()) > -1); } "); }
[ "protected", "function", "buildRuleWhenClient", "(", "$", "type", ",", "$", "not", "=", "false", ")", "{", "$", "not", "=", "Json", "::", "encode", "(", "$", "not", ")", ";", "$", "types", "=", "Json", "::", "encode", "(", "(", "array", ")", "$", ...
Builds the JS expression for Yii `whenClient` validation in order to apply validation to only a certain list of DNS record types. @param array|string $type types, that are must be validated with the rule @param bool $not inverts $type @return JsExpression
[ "Builds", "the", "JS", "expression", "for", "Yii", "whenClient", "validation", "in", "order", "to", "apply", "validation", "to", "only", "a", "certain", "list", "of", "DNS", "record", "types", "." ]
7e9199c95d91a979b7bd4fd07fe801dbe9e69183
https://github.com/hiqdev/hipanel-module-dns/blob/7e9199c95d91a979b7bd4fd07fe801dbe9e69183/src/models/Record.php#L172-L185
train
hail-framework/framework
src/Database/Migration/Adapter/PostgresAdapter.php
PostgresAdapter.createSchema
public function createSchema($schemaName = 'public') { $sql = \sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name" $this->execute($sql); }
php
public function createSchema($schemaName = 'public') { $sql = \sprintf('CREATE SCHEMA %s;', $this->quoteSchemaName($schemaName)); // from postgres 9.3 we can use "CREATE SCHEMA IF NOT EXISTS schema_name" $this->execute($sql); }
[ "public", "function", "createSchema", "(", "$", "schemaName", "=", "'public'", ")", "{", "$", "sql", "=", "\\", "sprintf", "(", "'CREATE SCHEMA %s;'", ",", "$", "this", "->", "quoteSchemaName", "(", "$", "schemaName", ")", ")", ";", "// from postgres 9.3 we ca...
Creates the specified schema. @param string $schemaName Schema Name @return void
[ "Creates", "the", "specified", "schema", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/PostgresAdapter.php#L1053-L1058
train
hail-framework/framework
src/Database/Migration/Adapter/PostgresAdapter.php
PostgresAdapter.isArrayType
protected function isArrayType($columnType) { if (!\preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) { return false; } $baseType = $matches[1]; return \in_array($baseType, $this->getColumnTypes(), true); }
php
protected function isArrayType($columnType) { if (!\preg_match('/^([a-z]+)(?:\[\]){1,}$/', $columnType, $matches)) { return false; } $baseType = $matches[1]; return \in_array($baseType, $this->getColumnTypes(), true); }
[ "protected", "function", "isArrayType", "(", "$", "columnType", ")", "{", "if", "(", "!", "\\", "preg_match", "(", "'/^([a-z]+)(?:\\[\\]){1,}$/'", ",", "$", "columnType", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "$", "baseType", "="...
Check if the given column is an array of a valid type. @param string $columnType @return bool
[ "Check", "if", "the", "given", "column", "is", "an", "array", "of", "a", "valid", "type", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/PostgresAdapter.php#L1148-L1157
train
hail-framework/framework
src/Util/Env.php
Env.get
public static function get(string $name): ?string { if (isset($_ENV[$name])) { return $_ENV[$name]; } if (isset($_SERVER[$name])) { return $_SERVER[$name]; } $value = \getenv($name); return $value === false ? null : $value; // switch getenv default to null }
php
public static function get(string $name): ?string { if (isset($_ENV[$name])) { return $_ENV[$name]; } if (isset($_SERVER[$name])) { return $_SERVER[$name]; } $value = \getenv($name); return $value === false ? null : $value; // switch getenv default to null }
[ "public", "static", "function", "get", "(", "string", "$", "name", ")", ":", "?", "string", "{", "if", "(", "isset", "(", "$", "_ENV", "[", "$", "name", "]", ")", ")", "{", "return", "$", "_ENV", "[", "$", "name", "]", ";", "}", "if", "(", "i...
Search the different places for environment variables and return first value found. @param string $name @return string|null
[ "Search", "the", "different", "places", "for", "environment", "variables", "and", "return", "first", "value", "found", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Env.php#L107-L120
train
hail-framework/framework
src/Util/Env.php
Env.clear
public static function clear($name): void { if (static::$immutable) { return; } if (\function_exists('\\putenv')) { \putenv($name); } unset($_ENV[$name], $_SERVER[$name]); }
php
public static function clear($name): void { if (static::$immutable) { return; } if (\function_exists('\\putenv')) { \putenv($name); } unset($_ENV[$name], $_SERVER[$name]); }
[ "public", "static", "function", "clear", "(", "$", "name", ")", ":", "void", "{", "if", "(", "static", "::", "$", "immutable", ")", "{", "return", ";", "}", "if", "(", "\\", "function_exists", "(", "'\\\\putenv'", ")", ")", "{", "\\", "putenv", "(", ...
Clear an environment variable. @param string $name @return void
[ "Clear", "an", "environment", "variable", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Env.php#L169-L180
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.isClosingElementImplied
public function isClosingElementImplied(string $html): bool { $parent = $this->getParent(); if ($parent === null || !($parent instanceof self)) { return false; } $name = $this->parseElementName($html); $parentName = $parent->getName(); // HEAD: no closing tag. if ($name === 'body' && $parentName === 'head') { return true; } // P if ($parentName === 'p' && \in_array($name, self::NO_CHILDREN_OF_P, true)) { return true; } // LI if ($parentName === 'li' && $name === 'li') { return true; } // DT and DD if (($parentName === 'dt' || $parentName === 'dd') && ($name === 'dt' || $name === 'dd')) { return true; } // RP and RT if (($parentName === 'rp' || $parentName === 'rt') && ($name === 'rp' || $name === 'rt')) { return true; } return false; }
php
public function isClosingElementImplied(string $html): bool { $parent = $this->getParent(); if ($parent === null || !($parent instanceof self)) { return false; } $name = $this->parseElementName($html); $parentName = $parent->getName(); // HEAD: no closing tag. if ($name === 'body' && $parentName === 'head') { return true; } // P if ($parentName === 'p' && \in_array($name, self::NO_CHILDREN_OF_P, true)) { return true; } // LI if ($parentName === 'li' && $name === 'li') { return true; } // DT and DD if (($parentName === 'dt' || $parentName === 'dd') && ($name === 'dt' || $name === 'dd')) { return true; } // RP and RT if (($parentName === 'rp' || $parentName === 'rt') && ($name === 'rp' || $name === 'rt')) { return true; } return false; }
[ "public", "function", "isClosingElementImplied", "(", "string", "$", "html", ")", ":", "bool", "{", "$", "parent", "=", "$", "this", "->", "getParent", "(", ")", ";", "if", "(", "$", "parent", "===", "null", "||", "!", "(", "$", "parent", "instanceof",...
Does the parent have an implied closing tag? @param string $html @return boolean
[ "Does", "the", "parent", "have", "an", "implied", "closing", "tag?" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L80-L116
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.parse
public function parse(string $html): string { $html = ltrim($html); $this->setTokenPosition($html); try { $this->name = $this->parseElementName($html); $remainingHtml = $this->parseAttributes($html); $posOfClosingBracket = $this->getPositionOfElementEndTag($remainingHtml); // Is self-closing? $posOfSelfClosingBracket = \mb_strpos($remainingHtml, '/>'); $remainingHtml = \mb_substr($remainingHtml, $posOfClosingBracket + 1); if ($posOfSelfClosingBracket !== false && $posOfSelfClosingBracket === $posOfClosingBracket - 1) { // Self-closing element. (Note: $this->valuue is unchanged.) return $remainingHtml; } // Lets close those closed-only elements that are left open. if (\in_array($this->name, self::VOID_ELEMENTS, true)) { return $remainingHtml; } // Open element. return $this->parseContents($remainingHtml); } catch (ParseException $e) { if ($this->getThrowOnError()) { throw $e; } } return ''; }
php
public function parse(string $html): string { $html = ltrim($html); $this->setTokenPosition($html); try { $this->name = $this->parseElementName($html); $remainingHtml = $this->parseAttributes($html); $posOfClosingBracket = $this->getPositionOfElementEndTag($remainingHtml); // Is self-closing? $posOfSelfClosingBracket = \mb_strpos($remainingHtml, '/>'); $remainingHtml = \mb_substr($remainingHtml, $posOfClosingBracket + 1); if ($posOfSelfClosingBracket !== false && $posOfSelfClosingBracket === $posOfClosingBracket - 1) { // Self-closing element. (Note: $this->valuue is unchanged.) return $remainingHtml; } // Lets close those closed-only elements that are left open. if (\in_array($this->name, self::VOID_ELEMENTS, true)) { return $remainingHtml; } // Open element. return $this->parseContents($remainingHtml); } catch (ParseException $e) { if ($this->getThrowOnError()) { throw $e; } } return ''; }
[ "public", "function", "parse", "(", "string", "$", "html", ")", ":", "string", "{", "$", "html", "=", "ltrim", "(", "$", "html", ")", ";", "$", "this", "->", "setTokenPosition", "(", "$", "html", ")", ";", "try", "{", "$", "this", "->", "name", "...
Will parse this element. @param string $html @return string Remaining HTML.
[ "Will", "parse", "this", "element", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L125-L157
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.parseContents
private function parseContents(string $html): string { if (\trim($html) === '') { return ''; } // Determine value. $this->value = $html; if (\preg_match("/(.*)<\/\s*" . $this->name . "\s*>/iU", $html, $valueMatches) === 1) { $this->value = $valueMatches[1]; } // Don't parse contents of "iframe" element. if ($this->name === 'iframe') { return $this->parseNoContents('iframe', $html); } // Only TEXT inside a "script" element. if ($this->name === 'script') { return $this->parseForeignContents('script', $html); } // Only TEXT inside a "style" element. if ($this->name === 'style') { return $this->parseForeignContents('style', $html); } // Parse contents one token at a time. $remainingHtml = $html; while ($this->isAnotherTokenPresent($remainingHtml)) { $token = Tokenizer::buildFromHtml($remainingHtml, $this); if (!$token instanceof TokenInterface || $token->isClosingElementImplied($remainingHtml)) { return $remainingHtml; } $remainingHtml = $token->parse($remainingHtml); $this->children[] = $token; } $this->removeLastTokenIfContainsOnlyWhitespace(); // Remove remaining closing tag. $posOfClosingBracket = \mb_strpos($remainingHtml, '>'); return \mb_substr($remainingHtml, $posOfClosingBracket + 1); }
php
private function parseContents(string $html): string { if (\trim($html) === '') { return ''; } // Determine value. $this->value = $html; if (\preg_match("/(.*)<\/\s*" . $this->name . "\s*>/iU", $html, $valueMatches) === 1) { $this->value = $valueMatches[1]; } // Don't parse contents of "iframe" element. if ($this->name === 'iframe') { return $this->parseNoContents('iframe', $html); } // Only TEXT inside a "script" element. if ($this->name === 'script') { return $this->parseForeignContents('script', $html); } // Only TEXT inside a "style" element. if ($this->name === 'style') { return $this->parseForeignContents('style', $html); } // Parse contents one token at a time. $remainingHtml = $html; while ($this->isAnotherTokenPresent($remainingHtml)) { $token = Tokenizer::buildFromHtml($remainingHtml, $this); if (!$token instanceof TokenInterface || $token->isClosingElementImplied($remainingHtml)) { return $remainingHtml; } $remainingHtml = $token->parse($remainingHtml); $this->children[] = $token; } $this->removeLastTokenIfContainsOnlyWhitespace(); // Remove remaining closing tag. $posOfClosingBracket = \mb_strpos($remainingHtml, '>'); return \mb_substr($remainingHtml, $posOfClosingBracket + 1); }
[ "private", "function", "parseContents", "(", "string", "$", "html", ")", ":", "string", "{", "if", "(", "\\", "trim", "(", "$", "html", ")", "===", "''", ")", "{", "return", "''", ";", "}", "// Determine value.", "$", "this", "->", "value", "=", "$",...
Will parse the contents of this element. @param string $html @return string Remaining HTML.
[ "Will", "parse", "the", "contents", "of", "this", "element", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L234-L280
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.parseElementName
private function parseElementName(string $html): string { $html = \trim($html); $elementMatchSuccessful = \preg_match( "/^(<(([a-z0-9\-]+:)?[a-z0-9\-]+))/i", $html, $elementMatches ); if ($elementMatchSuccessful !== 1) { if ($this->getThrowOnError()) { throw new ParseException('Invalid element name. Truncated html = ' . \mb_substr($html, 0, 20)); } return ''; } return \mb_strtolower($elementMatches[2]); }
php
private function parseElementName(string $html): string { $html = \trim($html); $elementMatchSuccessful = \preg_match( "/^(<(([a-z0-9\-]+:)?[a-z0-9\-]+))/i", $html, $elementMatches ); if ($elementMatchSuccessful !== 1) { if ($this->getThrowOnError()) { throw new ParseException('Invalid element name. Truncated html = ' . \mb_substr($html, 0, 20)); } return ''; } return \mb_strtolower($elementMatches[2]); }
[ "private", "function", "parseElementName", "(", "string", "$", "html", ")", ":", "string", "{", "$", "html", "=", "\\", "trim", "(", "$", "html", ")", ";", "$", "elementMatchSuccessful", "=", "\\", "preg_match", "(", "\"/^(<(([a-z0-9\\-]+:)?[a-z0-9\\-]+))/i\"", ...
Will get the element name from the html string. @param $html string @return string The element name.
[ "Will", "get", "the", "element", "name", "from", "the", "html", "string", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L289-L306
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.parseForeignContents
private function parseForeignContents(string $tag, string $html): string { $remainingHtml = \ltrim($html); // Find all contents. $remainingHtml = $this->determineRemainingHtmlOfForeignContents( $tag, $html, $remainingHtml ); // Handle no contents. if ($this->value === '') { return $remainingHtml; } if ($tag === 'script') { $text = new TextJs($this, $this->value); } elseif ($tag === 'style') { $text = new TextCss($this, $this->value); } else { $text = new Text($this, $this->value); } $this->children[] = $text; return $remainingHtml; }
php
private function parseForeignContents(string $tag, string $html): string { $remainingHtml = \ltrim($html); // Find all contents. $remainingHtml = $this->determineRemainingHtmlOfForeignContents( $tag, $html, $remainingHtml ); // Handle no contents. if ($this->value === '') { return $remainingHtml; } if ($tag === 'script') { $text = new TextJs($this, $this->value); } elseif ($tag === 'style') { $text = new TextCss($this, $this->value); } else { $text = new Text($this, $this->value); } $this->children[] = $text; return $remainingHtml; }
[ "private", "function", "parseForeignContents", "(", "string", "$", "tag", ",", "string", "$", "html", ")", ":", "string", "{", "$", "remainingHtml", "=", "\\", "ltrim", "(", "$", "html", ")", ";", "// Find all contents.", "$", "remainingHtml", "=", "$", "t...
Will parse the script and style contents correctly. @param $tag string @param $html string @return string The remaining HTML.
[ "Will", "parse", "the", "script", "and", "style", "contents", "correctly", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L316-L343
train
hail-framework/framework
src/Template/Tokenizer/Token/Element.php
Element.parseNoContents
private function parseNoContents(string $tag, string $html): string { $remainingHtml = \ltrim($html); $matchingResult = \preg_match( "/(<\/\s*" . $tag . "\s*>)/i", $html, $endOfScriptMatches ); if ($matchingResult === 0) { return ''; } $closingTag = $endOfScriptMatches[1]; $this->value = \mb_substr($remainingHtml, 0, \mb_strpos($html, $closingTag)); return \mb_substr( \mb_strstr($remainingHtml, $closingTag), \mb_strlen($closingTag) ); }
php
private function parseNoContents(string $tag, string $html): string { $remainingHtml = \ltrim($html); $matchingResult = \preg_match( "/(<\/\s*" . $tag . "\s*>)/i", $html, $endOfScriptMatches ); if ($matchingResult === 0) { return ''; } $closingTag = $endOfScriptMatches[1]; $this->value = \mb_substr($remainingHtml, 0, \mb_strpos($html, $closingTag)); return \mb_substr( \mb_strstr($remainingHtml, $closingTag), \mb_strlen($closingTag) ); }
[ "private", "function", "parseNoContents", "(", "string", "$", "tag", ",", "string", "$", "html", ")", ":", "string", "{", "$", "remainingHtml", "=", "\\", "ltrim", "(", "$", "html", ")", ";", "$", "matchingResult", "=", "\\", "preg_match", "(", "\"/(<\\/...
Will not parse the contents of an element. "iframe" elements. @param $tag string @param $html string @return string The remaining HTML.
[ "Will", "not", "parse", "the", "contents", "of", "an", "element", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Tokenizer/Token/Element.php#L355-L374
train
hail-framework/framework
src/Database/Migration/Adapter/AdapterFactory.php
AdapterFactory.registerAdapter
public function registerAdapter($name, $class) { if (!is_subclass_of($class, AdapterInterface::class)) { throw new \RuntimeException(sprintf( 'Adapter class "%s" must implement ' . AdapterInterface::class, $class )); } $this->adapters[$name] = $class; return $this; }
php
public function registerAdapter($name, $class) { if (!is_subclass_of($class, AdapterInterface::class)) { throw new \RuntimeException(sprintf( 'Adapter class "%s" must implement ' . AdapterInterface::class, $class )); } $this->adapters[$name] = $class; return $this; }
[ "public", "function", "registerAdapter", "(", "$", "name", ",", "$", "class", ")", "{", "if", "(", "!", "is_subclass_of", "(", "$", "class", ",", "AdapterInterface", "::", "class", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", ...
Add or replace an adapter with a fully qualified class name. @throws \RuntimeException @param string $name @param string $class @return $this
[ "Add", "or", "replace", "an", "adapter", "with", "a", "fully", "qualified", "class", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/AdapterFactory.php#L93-L104
train
hail-framework/framework
src/Database/Migration/Adapter/AdapterFactory.php
AdapterFactory.registerWrapper
public function registerWrapper($name, $class) { if (!is_subclass_of($class, WrapperInterface::class)) { throw new \RuntimeException(sprintf( 'Wrapper class "%s" must be implement ' . WrapperInterface::class, $class )); } $this->wrappers[$name] = $class; return $this; }
php
public function registerWrapper($name, $class) { if (!is_subclass_of($class, WrapperInterface::class)) { throw new \RuntimeException(sprintf( 'Wrapper class "%s" must be implement ' . WrapperInterface::class, $class )); } $this->wrappers[$name] = $class; return $this; }
[ "public", "function", "registerWrapper", "(", "$", "name", ",", "$", "class", ")", "{", "if", "(", "!", "is_subclass_of", "(", "$", "class", ",", "WrapperInterface", "::", "class", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", ...
Add or replace a wrapper with a fully qualified class name. @throws \RuntimeException @param string $name @param string $class @return $this
[ "Add", "or", "replace", "a", "wrapper", "with", "a", "fully", "qualified", "class", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Adapter/AdapterFactory.php#L152-L163
train
aimeos/ai-slim
lib/custom/src/MW/View/Helper/Response/Slim.php
Slim.createStream
public function createStream( $resource ) { if( is_resource( $resource ) === true ) { return new \Slim\Http\Stream( $resource ); } if( ( $fh = @fopen( $resource, 'r' ) ) !== false ) { return new \Slim\Http\Stream( $fh ); } throw new \Aimeos\MW\Exception( sprintf( 'Unable to open file "%1$s"', $resource ) ); }
php
public function createStream( $resource ) { if( is_resource( $resource ) === true ) { return new \Slim\Http\Stream( $resource ); } if( ( $fh = @fopen( $resource, 'r' ) ) !== false ) { return new \Slim\Http\Stream( $fh ); } throw new \Aimeos\MW\Exception( sprintf( 'Unable to open file "%1$s"', $resource ) ); }
[ "public", "function", "createStream", "(", "$", "resource", ")", "{", "if", "(", "is_resource", "(", "$", "resource", ")", "===", "true", ")", "{", "return", "new", "\\", "Slim", "\\", "Http", "\\", "Stream", "(", "$", "resource", ")", ";", "}", "if"...
Creates a new PSR-7 stream object @param string|resource Absolute file path or file descriptor @return \Psr\Http\Message\StreamInterface Stream object
[ "Creates", "a", "new", "PSR", "-", "7", "stream", "object" ]
13f22efe21450df4c822d9a77034f66a471cfa69
https://github.com/aimeos/ai-slim/blob/13f22efe21450df4c822d9a77034f66a471cfa69/lib/custom/src/MW/View/Helper/Response/Slim.php#L32-L43
train
htmlburger/wpemerge-cli
src/NodePackageManagers/Proxy.php
Proxy.getNodePackageManager
protected function getNodePackageManager() { $is_windows = strtolower( substr( PHP_OS, 0, 3 ) ) === 'win'; $node_package_managers = [ 'yarn' => Yarn::class, 'npm' => Npm::class, ]; foreach ( $node_package_managers as $manager => $class ) { $command = $is_windows ? 'where ' . escapeshellarg( $manager ) : 'which ' . escapeshellarg( $manager ); try { $output = App::execute( $command ); } catch ( ProcessFailedException $e ) { continue; } if ( ! trim( $output ) ) { continue; } return new $class(); } throw new RuntimeException( 'Could not find a node package manager. Please check if npm is added to your PATH.' ); }
php
protected function getNodePackageManager() { $is_windows = strtolower( substr( PHP_OS, 0, 3 ) ) === 'win'; $node_package_managers = [ 'yarn' => Yarn::class, 'npm' => Npm::class, ]; foreach ( $node_package_managers as $manager => $class ) { $command = $is_windows ? 'where ' . escapeshellarg( $manager ) : 'which ' . escapeshellarg( $manager ); try { $output = App::execute( $command ); } catch ( ProcessFailedException $e ) { continue; } if ( ! trim( $output ) ) { continue; } return new $class(); } throw new RuntimeException( 'Could not find a node package manager. Please check if npm is added to your PATH.' ); }
[ "protected", "function", "getNodePackageManager", "(", ")", "{", "$", "is_windows", "=", "strtolower", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ")", ")", "===", "'win'", ";", "$", "node_package_managers", "=", "[", "'yarn'", "=>", "Yarn", "::", ...
Get an instance of the first available package manager @return NodePackageManagerInterface
[ "Get", "an", "instance", "of", "the", "first", "available", "package", "manager" ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/NodePackageManagers/Proxy.php#L51-L75
train
hail-framework/framework
src/Container/Builder.php
Builder.create
public static function create(ContainerInterface $container, string $class, array $map = [], array $params = null) { if (!\class_exists($class)) { throw new \InvalidArgumentException("unable to create component: {$class} (autoloading failed)"); } if (\method_exists($class, 'getInstance')) { return $class::getInstance(); } if ($params === null) { $reflection = new \ReflectionClass($class); if (!$reflection->isInstantiable()) { throw new \InvalidArgumentException("unable to create instance of abstract class: {$class}"); } $constructor = $reflection->getConstructor(); if ($constructor && ($params = $constructor->getParameters()) !== []) { $params = static::resolve($container, $params, $map, false); } else { $params = []; } return $reflection->newInstanceArgs($params); } if ($params !== []) { $params = static::resolve($container, $params, $map, false); } return new $class(...$params); }
php
public static function create(ContainerInterface $container, string $class, array $map = [], array $params = null) { if (!\class_exists($class)) { throw new \InvalidArgumentException("unable to create component: {$class} (autoloading failed)"); } if (\method_exists($class, 'getInstance')) { return $class::getInstance(); } if ($params === null) { $reflection = new \ReflectionClass($class); if (!$reflection->isInstantiable()) { throw new \InvalidArgumentException("unable to create instance of abstract class: {$class}"); } $constructor = $reflection->getConstructor(); if ($constructor && ($params = $constructor->getParameters()) !== []) { $params = static::resolve($container, $params, $map, false); } else { $params = []; } return $reflection->newInstanceArgs($params); } if ($params !== []) { $params = static::resolve($container, $params, $map, false); } return new $class(...$params); }
[ "public", "static", "function", "create", "(", "ContainerInterface", "$", "container", ",", "string", "$", "class", ",", "array", "$", "map", "=", "[", "]", ",", "array", "$", "params", "=", "null", ")", "{", "if", "(", "!", "\\", "class_exists", "(", ...
Create an instance of a given class. @noinspection PhpDocMissingThrowsInspection @param ContainerInterface $container @param string $class fully-qualified class-name @param mixed[] $map mixed list/map of parameter values (and/or boxed values) @param \ReflectionParameter[]|array[]|null $params @return mixed @throws \InvalidArgumentException
[ "Create", "an", "instance", "of", "a", "given", "class", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Builder.php#L67-L100
train
hail-framework/framework
src/Container/Builder.php
Builder.resolve
protected static function resolve( ContainerInterface $container, array $params, array $map, bool $safe = true ): array { $args = []; foreach ($params as $index => $param) { $value = static::getParameterValue($container, $param, $index, $map, $safe); if ($value instanceof \Closure) { $value = $value($container); // unbox a boxed value } $args[] = $value; // argument resolved! } return $args; }
php
protected static function resolve( ContainerInterface $container, array $params, array $map, bool $safe = true ): array { $args = []; foreach ($params as $index => $param) { $value = static::getParameterValue($container, $param, $index, $map, $safe); if ($value instanceof \Closure) { $value = $value($container); // unbox a boxed value } $args[] = $value; // argument resolved! } return $args; }
[ "protected", "static", "function", "resolve", "(", "ContainerInterface", "$", "container", ",", "array", "$", "params", ",", "array", "$", "map", ",", "bool", "$", "safe", "=", "true", ")", ":", "array", "{", "$", "args", "=", "[", "]", ";", "foreach",...
Internally resolves parameters to functions or constructors. @param ContainerInterface $container @param \ReflectionParameter[]|array[] $params parameter reflections @param array $map mixed list/map of parameter values (and/or boxed values) @param bool $safe if TRUE, it's considered safe to resolve against parameter names @return array parameters @throws \InvalidArgumentException
[ "Internally", "resolves", "parameters", "to", "functions", "or", "constructors", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Container/Builder.php#L137-L155
train
hail-framework/framework
src/Debugger/Helpers.php
Helpers.editorLink
public static function editorLink(string $file, int $line = null): string { $file = \strtr($origFile = $file, Debugger::$editorMapping); if ($editor = self::editorUri($origFile, $line)) { $file = \str_replace('\\', '/', $file); if (\preg_match('#(^[a-z]:)?/.{1,50}$#i', $file, $m) && \strlen($file) > \strlen($m[0])) { $file = '...' . $m[0]; } $file = \str_replace('/', DIRECTORY_SEPARATOR, $file); return self::formatHtml('<a href="%" title="%">%<b>%</b>%</a>', $editor, $file . ($line ? ":$line" : ''), \rtrim(\dirname($file), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, \basename($file), $line ? ":$line" : '' ); } return self::formatHtml('<span>%</span>', $file . ($line ? ":$line" : '')); }
php
public static function editorLink(string $file, int $line = null): string { $file = \strtr($origFile = $file, Debugger::$editorMapping); if ($editor = self::editorUri($origFile, $line)) { $file = \str_replace('\\', '/', $file); if (\preg_match('#(^[a-z]:)?/.{1,50}$#i', $file, $m) && \strlen($file) > \strlen($m[0])) { $file = '...' . $m[0]; } $file = \str_replace('/', DIRECTORY_SEPARATOR, $file); return self::formatHtml('<a href="%" title="%">%<b>%</b>%</a>', $editor, $file . ($line ? ":$line" : ''), \rtrim(\dirname($file), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR, \basename($file), $line ? ":$line" : '' ); } return self::formatHtml('<span>%</span>', $file . ($line ? ":$line" : '')); }
[ "public", "static", "function", "editorLink", "(", "string", "$", "file", ",", "int", "$", "line", "=", "null", ")", ":", "string", "{", "$", "file", "=", "\\", "strtr", "(", "$", "origFile", "=", "$", "file", ",", "Debugger", "::", "$", "editorMappi...
Returns HTML link to editor. @param string $file @param int|null $line @return string
[ "Returns", "HTML", "link", "to", "editor", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Helpers.php#L29-L49
train
hail-framework/framework
src/Debugger/Helpers.php
Helpers.editorUri
public static function editorUri( string $file, int $line = null, string $action = 'open', string $search = '', string $replace = '' ): ?string { if (Debugger::$editor && $file && ($action === 'create' || is_file($file))) { $file = \str_replace('/', DIRECTORY_SEPARATOR, $file); $file = \strtr($file, Debugger::$editorMapping); return strtr(Debugger::$editor, [ '%action' => $action, '%file' => rawurlencode($file), '%line' => $line ?: 1, '%search' => rawurlencode($search), '%replace' => rawurlencode($replace), ]); } return null; }
php
public static function editorUri( string $file, int $line = null, string $action = 'open', string $search = '', string $replace = '' ): ?string { if (Debugger::$editor && $file && ($action === 'create' || is_file($file))) { $file = \str_replace('/', DIRECTORY_SEPARATOR, $file); $file = \strtr($file, Debugger::$editorMapping); return strtr(Debugger::$editor, [ '%action' => $action, '%file' => rawurlencode($file), '%line' => $line ?: 1, '%search' => rawurlencode($search), '%replace' => rawurlencode($replace), ]); } return null; }
[ "public", "static", "function", "editorUri", "(", "string", "$", "file", ",", "int", "$", "line", "=", "null", ",", "string", "$", "action", "=", "'open'", ",", "string", "$", "search", "=", "''", ",", "string", "$", "replace", "=", "''", ")", ":", ...
Returns link to editor. @return string|null
[ "Returns", "link", "to", "editor", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Helpers.php#L57-L78
train
hail-framework/framework
src/Debugger/Helpers.php
Helpers.getSuggestion
public static function getSuggestion(array $items, string $value): ?string { $best = null; $min = (\strlen($value) / 4 + 1) * 10 + .1; foreach (\array_unique($items, SORT_REGULAR) as $item) { $item = \is_object($item) ? $item->getName() : $item; if (($len = \levenshtein($item, $value, 10, 11, 10)) > 0 && $len < $min) { $min = $len; $best = $item; } } return $best; }
php
public static function getSuggestion(array $items, string $value): ?string { $best = null; $min = (\strlen($value) / 4 + 1) * 10 + .1; foreach (\array_unique($items, SORT_REGULAR) as $item) { $item = \is_object($item) ? $item->getName() : $item; if (($len = \levenshtein($item, $value, 10, 11, 10)) > 0 && $len < $min) { $min = $len; $best = $item; } } return $best; }
[ "public", "static", "function", "getSuggestion", "(", "array", "$", "items", ",", "string", "$", "value", ")", ":", "?", "string", "{", "$", "best", "=", "null", ";", "$", "min", "=", "(", "\\", "strlen", "(", "$", "value", ")", "/", "4", "+", "1...
Finds the best suggestion. @return string|NULL
[ "Finds", "the", "best", "suggestion", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/Helpers.php#L292-L305
train
hail-framework/framework
src/Session/Session.php
Session.isStarted
public function isStarted() { $started = \session_status() === PHP_SESSION_ACTIVE; // if the session was started externally, move the flash values forward if ($started && !$this->flashMoved) { $this->moveFlash(); } // done return $started; }
php
public function isStarted() { $started = \session_status() === PHP_SESSION_ACTIVE; // if the session was started externally, move the flash values forward if ($started && !$this->flashMoved) { $this->moveFlash(); } // done return $started; }
[ "public", "function", "isStarted", "(", ")", "{", "$", "started", "=", "\\", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", ";", "// if the session was started externally, move the flash values forward", "if", "(", "$", "started", "&&", "!", "$", "this", "...
Is the session already started? @return bool
[ "Is", "the", "session", "already", "started?" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L178-L189
train
hail-framework/framework
src/Session/Session.php
Session.start
public function start(array $options = null) { $sessionStatus = \session_status(); if ($sessionStatus === PHP_SESSION_DISABLED) { throw new \RuntimeException('PHP sessions are disabled'); } if ($sessionStatus === PHP_SESSION_ACTIVE) { throw new \RuntimeException('session has already been started'); } if ($this->handler) { \session_set_save_handler($this->handler, true); } \session_set_cookie_params( $this->cookieParams['lifetime'], $this->cookieParams['path'], $this->cookieParams['domain'], $this->cookieParams['secure'], $this->cookieParams['httponly'] ); if ($options === null) { $options = []; } if (!isset($options['serialize_handler'])) { $serializeHandler = \ini_get('serialize_handler'); if ($serializeHandler === 'php' || $serializeHandler === 'php_binary') { $options['serialize_handler'] = 'php_serialize'; } } $result = \session_start($options); if ($result) { $this->moveFlash(); } return $result; }
php
public function start(array $options = null) { $sessionStatus = \session_status(); if ($sessionStatus === PHP_SESSION_DISABLED) { throw new \RuntimeException('PHP sessions are disabled'); } if ($sessionStatus === PHP_SESSION_ACTIVE) { throw new \RuntimeException('session has already been started'); } if ($this->handler) { \session_set_save_handler($this->handler, true); } \session_set_cookie_params( $this->cookieParams['lifetime'], $this->cookieParams['path'], $this->cookieParams['domain'], $this->cookieParams['secure'], $this->cookieParams['httponly'] ); if ($options === null) { $options = []; } if (!isset($options['serialize_handler'])) { $serializeHandler = \ini_get('serialize_handler'); if ($serializeHandler === 'php' || $serializeHandler === 'php_binary') { $options['serialize_handler'] = 'php_serialize'; } } $result = \session_start($options); if ($result) { $this->moveFlash(); } return $result; }
[ "public", "function", "start", "(", "array", "$", "options", "=", "null", ")", "{", "$", "sessionStatus", "=", "\\", "session_status", "(", ")", ";", "if", "(", "$", "sessionStatus", "===", "PHP_SESSION_DISABLED", ")", "{", "throw", "new", "\\", "RuntimeEx...
Starts a new or existing session. @param array $options @return bool @throws \RuntimeException
[ "Starts", "a", "new", "or", "existing", "session", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L200-L242
train
hail-framework/framework
src/Session/Session.php
Session.moveFlash
protected function moveFlash() { if (!isset($_SESSION[static::FLASH_NEXT])) { $_SESSION[static::FLASH_NEXT] = []; } $_SESSION[static::FLASH_NOW] = $_SESSION[static::FLASH_NEXT]; $_SESSION[static::FLASH_NEXT] = []; $this->flashMoved = true; }
php
protected function moveFlash() { if (!isset($_SESSION[static::FLASH_NEXT])) { $_SESSION[static::FLASH_NEXT] = []; } $_SESSION[static::FLASH_NOW] = $_SESSION[static::FLASH_NEXT]; $_SESSION[static::FLASH_NEXT] = []; $this->flashMoved = true; }
[ "protected", "function", "moveFlash", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "_SESSION", "[", "static", "::", "FLASH_NEXT", "]", ")", ")", "{", "$", "_SESSION", "[", "static", "::", "FLASH_NEXT", "]", "=", "[", "]", ";", "}", "$", "_SESS...
Moves the "next" flash values to the "now" values, thereby clearing the "next" values.
[ "Moves", "the", "next", "flash", "values", "to", "the", "now", "values", "thereby", "clearing", "the", "next", "values", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L248-L256
train
hail-framework/framework
src/Session/Session.php
Session.isResumable
public function isResumable(): bool { $name = $this->getName(); if ($this->request) { return $this->request->cookie($name) !== null; } return isset($_COOKIE[$name]); }
php
public function isResumable(): bool { $name = $this->getName(); if ($this->request) { return $this->request->cookie($name) !== null; } return isset($_COOKIE[$name]); }
[ "public", "function", "isResumable", "(", ")", ":", "bool", "{", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "this", "->", "request", ")", "{", "return", "$", "this", "->", "request", "->", "cookie", "(", "$", "...
Is a session available to be resumed? @return bool
[ "Is", "a", "session", "available", "to", "be", "resumed?" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L295-L304
train
hail-framework/framework
src/Session/Session.php
Session.resume
public function resume(): bool { if ($this->isStarted()) { return true; } if ($this->isResumable()) { return $this->start(); } return false; }
php
public function resume(): bool { if ($this->isStarted()) { return true; } if ($this->isResumable()) { return $this->start(); } return false; }
[ "public", "function", "resume", "(", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "isStarted", "(", ")", ")", "{", "return", "true", ";", "}", "if", "(", "$", "this", "->", "isResumable", "(", ")", ")", "{", "return", "$", "this", "->", ...
Resumes a session, but does not start a new one if there is no existing one. @return bool
[ "Resumes", "a", "session", "but", "does", "not", "start", "a", "new", "one", "if", "there", "is", "no", "existing", "one", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L313-L324
train
hail-framework/framework
src/Session/Session.php
Session.regenerateId
public function regenerateId(): bool { $result = \session_regenerate_id(true); if ($result && $this->csrfToken) { $this->csrfToken->regenerateValue(); } return $result; }
php
public function regenerateId(): bool { $result = \session_regenerate_id(true); if ($result && $this->csrfToken) { $this->csrfToken->regenerateValue(); } return $result; }
[ "public", "function", "regenerateId", "(", ")", ":", "bool", "{", "$", "result", "=", "\\", "session_regenerate_id", "(", "true", ")", ";", "if", "(", "$", "result", "&&", "$", "this", "->", "csrfToken", ")", "{", "$", "this", "->", "csrfToken", "->", ...
Regenerates and replaces the current session id; also regenerates the CSRF token value if one exists. @return bool True if regeneration worked, false if not.
[ "Regenerates", "and", "replaces", "the", "current", "session", "id", ";", "also", "regenerates", "the", "CSRF", "token", "value", "if", "one", "exists", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Session/Session.php#L409-L417
train
hail-framework/framework
src/Image/ImageCache.php
ImageCache.make
public function make($data) { // include "modified" property for any files if ($this->isFile($data)) { $this->setProperty('modified', \filemtime((string) $data)); } // register make call $this->__call('make', [$data]); return $this; }
php
public function make($data) { // include "modified" property for any files if ($this->isFile($data)) { $this->setProperty('modified', \filemtime((string) $data)); } // register make call $this->__call('make', [$data]); return $this; }
[ "public", "function", "make", "(", "$", "data", ")", "{", "// include \"modified\" property for any files", "if", "(", "$", "this", "->", "isFile", "(", "$", "data", ")", ")", "{", "$", "this", "->", "setProperty", "(", "'modified'", ",", "\\", "filemtime", ...
Special make method to add modifed data to checksum @param mixed $data @return self
[ "Special", "make", "method", "to", "add", "modifed", "data", "to", "checksum" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Image/ImageCache.php#L81-L92
train
hail-framework/framework
src/Debugger/BlueScreen.php
BlueScreen.render
public function render(\Throwable $exception): string { \ob_start(); if (Helpers::isAjax() && \session_status() === PHP_SESSION_ACTIVE) { $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/content.phtml'); $contentId = $_SERVER['HTTP_X_TRACY_AJAX']; $_SESSION['_tracy']['bluescreen'][$contentId] = [ 'content' => \ob_get_clean(), 'dumps' => Dumper::fetchLiveData(), 'time' => \time(), ]; return ''; } $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/page.phtml'); return \ob_get_clean(); }
php
public function render(\Throwable $exception): string { \ob_start(); if (Helpers::isAjax() && \session_status() === PHP_SESSION_ACTIVE) { $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/content.phtml'); $contentId = $_SERVER['HTTP_X_TRACY_AJAX']; $_SESSION['_tracy']['bluescreen'][$contentId] = [ 'content' => \ob_get_clean(), 'dumps' => Dumper::fetchLiveData(), 'time' => \time(), ]; return ''; } $this->renderTemplate($exception, __DIR__ . '/assets/BlueScreen/page.phtml'); return \ob_get_clean(); }
[ "public", "function", "render", "(", "\\", "Throwable", "$", "exception", ")", ":", "string", "{", "\\", "ob_start", "(", ")", ";", "if", "(", "Helpers", "::", "isAjax", "(", ")", "&&", "\\", "session_status", "(", ")", "===", "PHP_SESSION_ACTIVE", ")", ...
Renders blue screen. @param \Throwable $exception @return string
[ "Renders", "blue", "screen", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/BlueScreen.php#L84-L102
train
hail-framework/framework
src/Debugger/BlueScreen.php
BlueScreen.highlightLine
public static function highlightLine(string $html, int $line, int $lines = 15): string { $source = \explode("\n", "\n" . \str_replace("\r\n", "\n", $html)); $out = ''; $spans = 1; $start = $i = \max(1, \min($line, \count($source) - 1) - (int)\floor($lines * 2 / 3)); while (--$i >= 1) { // find last highlighted block if (\preg_match('#.*(</?span[^>]*>)#', $source[$i], $m)) { if ($m[1] !== '</span>') { $spans++; $out .= $m[1]; } break; } } $source = \array_slice($source, $start, $lines, true); \end($source); $numWidth = \strlen((string)\key($source)); foreach ($source as $n => $s) { $spans += \substr_count($s, '<span') - \substr_count($s, '</span'); $s = \str_replace(["\r", "\n"], ['', ''], $s); \preg_match_all('#<[^>]+>#', $s, $tags); if ($n == $line) { $out .= \sprintf( "<span class=\"highlight\">%{$numWidth}s: %s\n</span>%s", $n, \strip_tags($s), \implode('', $tags[0]) ); } else { $out .= \sprintf("<span class=\"line\">%{$numWidth}s:</span> %s\n", $n, $s); } } $out .= \str_repeat('</span>', $spans) . '</code>'; return $out; }
php
public static function highlightLine(string $html, int $line, int $lines = 15): string { $source = \explode("\n", "\n" . \str_replace("\r\n", "\n", $html)); $out = ''; $spans = 1; $start = $i = \max(1, \min($line, \count($source) - 1) - (int)\floor($lines * 2 / 3)); while (--$i >= 1) { // find last highlighted block if (\preg_match('#.*(</?span[^>]*>)#', $source[$i], $m)) { if ($m[1] !== '</span>') { $spans++; $out .= $m[1]; } break; } } $source = \array_slice($source, $start, $lines, true); \end($source); $numWidth = \strlen((string)\key($source)); foreach ($source as $n => $s) { $spans += \substr_count($s, '<span') - \substr_count($s, '</span'); $s = \str_replace(["\r", "\n"], ['', ''], $s); \preg_match_all('#<[^>]+>#', $s, $tags); if ($n == $line) { $out .= \sprintf( "<span class=\"highlight\">%{$numWidth}s: %s\n</span>%s", $n, \strip_tags($s), \implode('', $tags[0]) ); } else { $out .= \sprintf("<span class=\"line\">%{$numWidth}s:</span> %s\n", $n, $s); } } $out .= \str_repeat('</span>', $spans) . '</code>'; return $out; }
[ "public", "static", "function", "highlightLine", "(", "string", "$", "html", ",", "int", "$", "line", ",", "int", "$", "lines", "=", "15", ")", ":", "string", "{", "$", "source", "=", "\\", "explode", "(", "\"\\n\"", ",", "\"\\n\"", ".", "\\", "str_r...
Returns highlighted line in HTML code. @param string $html @param int $line @param int $lines @return string
[ "Returns", "highlighted", "line", "in", "HTML", "code", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/BlueScreen.php#L344-L382
train
hail-framework/framework
src/Debugger/BlueScreen.php
BlueScreen.isCollapsed
public function isCollapsed(string $file): bool { $file = \str_replace('\\', '/', $file) . '/'; foreach ($this->collapsePaths as $path) { $path = \str_replace('\\', '/', $path) . '/'; if (\strpos($file, $path) === 0) { return true; } } return false; }
php
public function isCollapsed(string $file): bool { $file = \str_replace('\\', '/', $file) . '/'; foreach ($this->collapsePaths as $path) { $path = \str_replace('\\', '/', $path) . '/'; if (\strpos($file, $path) === 0) { return true; } } return false; }
[ "public", "function", "isCollapsed", "(", "string", "$", "file", ")", ":", "bool", "{", "$", "file", "=", "\\", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "file", ")", ".", "'/'", ";", "foreach", "(", "$", "this", "->", "collapsePaths", "as"...
Should a file be collapsed in stack trace? @param string $file @return bool
[ "Should", "a", "file", "be", "collapsed", "in", "stack", "trace?" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Debugger/BlueScreen.php#L392-L403
train
hail-framework/framework
src/Template/Extension/Asset.php
Asset.cachedAssetUrl
public function cachedAssetUrl($url) { $filePath = $this->path . '/' . \ltrim($url, '/'); if (!\file_exists($filePath)) { throw new \LogicException( 'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.' ); } $lastUpdated = \filemtime($filePath); $pathInfo = \pathinfo($url); if ($pathInfo['dirname'] === '.') { $directory = ''; } elseif ($pathInfo['dirname'] === '/') { $directory = '/'; } else { $directory = $pathInfo['dirname'] . '/'; } if ($this->filenameMethod) { return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension']; } return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated; }
php
public function cachedAssetUrl($url) { $filePath = $this->path . '/' . \ltrim($url, '/'); if (!\file_exists($filePath)) { throw new \LogicException( 'Unable to locate the asset "' . $url . '" in the "' . $this->path . '" directory.' ); } $lastUpdated = \filemtime($filePath); $pathInfo = \pathinfo($url); if ($pathInfo['dirname'] === '.') { $directory = ''; } elseif ($pathInfo['dirname'] === '/') { $directory = '/'; } else { $directory = $pathInfo['dirname'] . '/'; } if ($this->filenameMethod) { return $directory . $pathInfo['filename'] . '.' . $lastUpdated . '.' . $pathInfo['extension']; } return $directory . $pathInfo['filename'] . '.' . $pathInfo['extension'] . '?v=' . $lastUpdated; }
[ "public", "function", "cachedAssetUrl", "(", "$", "url", ")", "{", "$", "filePath", "=", "$", "this", "->", "path", ".", "'/'", ".", "\\", "ltrim", "(", "$", "url", ",", "'/'", ")", ";", "if", "(", "!", "\\", "file_exists", "(", "$", "filePath", ...
Create "cache busted" asset URL. @param string $url @return string
[ "Create", "cache", "busted", "asset", "URL", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Extension/Asset.php#L63-L89
train
hail-framework/framework
src/Database/Migration/Generator/MySqlAdapter.php
MySqlAdapter.getSchema
public function getSchema() { $this->output->writeln('Load current database schema.'); $result = []; $result['database'] = $this->getDatabaseSchemata($this->dbName); $tables = $this->getTables(); foreach ($tables as $table) { $tableName = $table['table_name']; $this->output->writeln(sprintf('Table: <info>%s</info>', $tableName)); $result['tables'][$tableName]['table'] = $table; $result['tables'][$tableName]['columns'] = $this->getColumns($tableName); $result['tables'][$tableName]['indexes'] = $this->getIndexes($tableName); $result['tables'][$tableName]['foreign_keys'] = $this->getForeignKeys($tableName); } return $result; }
php
public function getSchema() { $this->output->writeln('Load current database schema.'); $result = []; $result['database'] = $this->getDatabaseSchemata($this->dbName); $tables = $this->getTables(); foreach ($tables as $table) { $tableName = $table['table_name']; $this->output->writeln(sprintf('Table: <info>%s</info>', $tableName)); $result['tables'][$tableName]['table'] = $table; $result['tables'][$tableName]['columns'] = $this->getColumns($tableName); $result['tables'][$tableName]['indexes'] = $this->getIndexes($tableName); $result['tables'][$tableName]['foreign_keys'] = $this->getForeignKeys($tableName); } return $result; }
[ "public", "function", "getSchema", "(", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "'Load current database schema.'", ")", ";", "$", "result", "=", "[", "]", ";", "$", "result", "[", "'database'", "]", "=", "$", "this", "->", "getDataba...
Load current database schema. @return array
[ "Load", "current", "database", "schema", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlAdapter.php#L64-L82
train
hail-framework/framework
src/Database/Migration/Generator/MySqlAdapter.php
MySqlAdapter.getTableCreateSql
public function getTableCreateSql($tableName) { $sql = sprintf('SHOW CREATE TABLE %s', $this->ident($tableName)); $result = $this->pdo->query($sql)->fetch(); return $result['CREATE TABLE']; }
php
public function getTableCreateSql($tableName) { $sql = sprintf('SHOW CREATE TABLE %s', $this->ident($tableName)); $result = $this->pdo->query($sql)->fetch(); return $result['CREATE TABLE']; }
[ "public", "function", "getTableCreateSql", "(", "$", "tableName", ")", "{", "$", "sql", "=", "sprintf", "(", "'SHOW CREATE TABLE %s'", ",", "$", "this", "->", "ident", "(", "$", "tableName", ")", ")", ";", "$", "result", "=", "$", "this", "->", "pdo", ...
Get SQL to create a table. @param string $tableName @return string
[ "Get", "SQL", "to", "create", "a", "table", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Database/Migration/Generator/MySqlAdapter.php#L276-L282
train
DoSomething/gateway
src/Common/ApiCollection.php
ApiCollection.setPaginator
public function setPaginator($class, $options = []) { $interfaces = class_implements($class); if (in_array('Illuminate\Contracts\Pagination\LengthAwarePaginator', $interfaces)) { $paginator = new $class($this->items, $this->total, $this->perPage, $this->currentPage, $options); } elseif (in_array('Illuminate\Contracts\Pagination\Paginator', $interfaces)) { $paginator = new $class($this->items, $this->perPage, $this->currentPage, $options); $paginator->hasMorePagesWhen($this->hasMore); } else { throw new \InvalidArgumentException('Cannot use the given paginator.'); } $this->paginator = $paginator; }
php
public function setPaginator($class, $options = []) { $interfaces = class_implements($class); if (in_array('Illuminate\Contracts\Pagination\LengthAwarePaginator', $interfaces)) { $paginator = new $class($this->items, $this->total, $this->perPage, $this->currentPage, $options); } elseif (in_array('Illuminate\Contracts\Pagination\Paginator', $interfaces)) { $paginator = new $class($this->items, $this->perPage, $this->currentPage, $options); $paginator->hasMorePagesWhen($this->hasMore); } else { throw new \InvalidArgumentException('Cannot use the given paginator.'); } $this->paginator = $paginator; }
[ "public", "function", "setPaginator", "(", "$", "class", ",", "$", "options", "=", "[", "]", ")", "{", "$", "interfaces", "=", "class_implements", "(", "$", "class", ")", ";", "if", "(", "in_array", "(", "'Illuminate\\Contracts\\Pagination\\LengthAwarePaginator'...
Set a paginator for this collection. @param string $class @param array $options
[ "Set", "a", "paginator", "for", "this", "collection", "." ]
89c1c59c6af038dff790df6d5aaa9fc703246568
https://github.com/DoSomething/gateway/blob/89c1c59c6af038dff790df6d5aaa9fc703246568/src/Common/ApiCollection.php#L88-L102
train
Kajna/K-Core
Core/Util/Message.php
Message.get
public static function get($key = '', $preserve = false) { $value = null; if (isset($_SESSION['flashmessage'][$key])) { $value = $_SESSION['flashmessage'][$key]; if (!$preserve) { unset($_SESSION['flashmessage'][$key]); } } return $value; }
php
public static function get($key = '', $preserve = false) { $value = null; if (isset($_SESSION['flashmessage'][$key])) { $value = $_SESSION['flashmessage'][$key]; if (!$preserve) { unset($_SESSION['flashmessage'][$key]); } } return $value; }
[ "public", "static", "function", "get", "(", "$", "key", "=", "''", ",", "$", "preserve", "=", "false", ")", "{", "$", "value", "=", "null", ";", "if", "(", "isset", "(", "$", "_SESSION", "[", "'flashmessage'", "]", "[", "$", "key", "]", ")", ")",...
Get message and destroy upon reading unless stated otherwise. @param string $key @param bool $preserve @return mixed
[ "Get", "message", "and", "destroy", "upon", "reading", "unless", "stated", "otherwise", "." ]
6a354056cf95e471b9b1eb372c5626123fd77df2
https://github.com/Kajna/K-Core/blob/6a354056cf95e471b9b1eb372c5626123fd77df2/Core/Util/Message.php#L32-L42
train
hail-framework/framework
src/Template/Engine.php
Engine.addData
public function addData(array $data, $templates = null): self { if (null === $templates) { $this->sharedVariables = \array_merge($this->sharedVariables, $data); return $this; } if (\is_string($templates)) { $templates = [$templates]; } if (\is_array($templates)) { foreach ($templates as $template) { if (isset($this->templateVariables[$template])) { $this->templateVariables[$template] = \array_merge($this->templateVariables[$template], $data); } else { $this->templateVariables[$template] = $data; } } return $this; } throw new \InvalidArgumentException( 'The templates variable must be null, an array or a string, ' . \gettype($templates) . ' given.' ); }
php
public function addData(array $data, $templates = null): self { if (null === $templates) { $this->sharedVariables = \array_merge($this->sharedVariables, $data); return $this; } if (\is_string($templates)) { $templates = [$templates]; } if (\is_array($templates)) { foreach ($templates as $template) { if (isset($this->templateVariables[$template])) { $this->templateVariables[$template] = \array_merge($this->templateVariables[$template], $data); } else { $this->templateVariables[$template] = $data; } } return $this; } throw new \InvalidArgumentException( 'The templates variable must be null, an array or a string, ' . \gettype($templates) . ' given.' ); }
[ "public", "function", "addData", "(", "array", "$", "data", ",", "$", "templates", "=", "null", ")", ":", "self", "{", "if", "(", "null", "===", "$", "templates", ")", "{", "$", "this", "->", "sharedVariables", "=", "\\", "array_merge", "(", "$", "th...
Add preassigned template data. @param array $data ; @param null|string|array $templates ; @return self @throws \InvalidArgumentException
[ "Add", "preassigned", "template", "data", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Engine.php#L91-L118
train
hail-framework/framework
src/Template/Engine.php
Engine.callFunction
public function callFunction($name, Template $template = null, $arguments = []) { $callable = $this->getFunction($name); if (\is_array($callable) && isset($callable[0]) && $callable[0] instanceof ExtensionInterface ) { $callable[0]->template = $template; } return $callable(...$arguments); }
php
public function callFunction($name, Template $template = null, $arguments = []) { $callable = $this->getFunction($name); if (\is_array($callable) && isset($callable[0]) && $callable[0] instanceof ExtensionInterface ) { $callable[0]->template = $template; } return $callable(...$arguments); }
[ "public", "function", "callFunction", "(", "$", "name", ",", "Template", "$", "template", "=", "null", ",", "$", "arguments", "=", "[", "]", ")", "{", "$", "callable", "=", "$", "this", "->", "getFunction", "(", "$", "name", ")", ";", "if", "(", "\...
Call the function. @param string $name @param Template $template @param array $arguments @return mixed
[ "Call", "the", "function", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Engine.php#L229-L241
train
hail-framework/framework
src/Template/Engine.php
Engine.compile
public function compile($name): string { [ 'template' => $template, 'cache' => $cache, ] = $this->getTemplateFile($name); if (\filemtime($template) < @\filemtime($cache)) { return $cache; } $root = Tokenizer\Tokenizer::parseFile($template); Processor::parseToken($root, $this->processors); \file_put_contents($cache, (string) $root); return $cache; }
php
public function compile($name): string { [ 'template' => $template, 'cache' => $cache, ] = $this->getTemplateFile($name); if (\filemtime($template) < @\filemtime($cache)) { return $cache; } $root = Tokenizer\Tokenizer::parseFile($template); Processor::parseToken($root, $this->processors); \file_put_contents($cache, (string) $root); return $cache; }
[ "public", "function", "compile", "(", "$", "name", ")", ":", "string", "{", "[", "'template'", "=>", "$", "template", ",", "'cache'", "=>", "$", "cache", ",", "]", "=", "$", "this", "->", "getTemplateFile", "(", "$", "name", ")", ";", "if", "(", "\...
Compile the html, and return the compiled file. @return string the compiled file.
[ "Compile", "the", "html", "and", "return", "the", "compiled", "file", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Template/Engine.php#L340-L358
train
hail-framework/framework
src/Filesystem/Adapter/Memory.php
Memory.doListContents
protected function doListContents($directory, $recursive) { $filter = function ($path) use ($directory, $recursive) { // Remove the root directory from any listing. if ($path === '') { return false; } if (Util::dirname($path) === $directory) { return true; } return $recursive && $this->pathIsInDirectory($path, $directory); }; return \array_filter(\array_keys($this->storage), $filter); }
php
protected function doListContents($directory, $recursive) { $filter = function ($path) use ($directory, $recursive) { // Remove the root directory from any listing. if ($path === '') { return false; } if (Util::dirname($path) === $directory) { return true; } return $recursive && $this->pathIsInDirectory($path, $directory); }; return \array_filter(\array_keys($this->storage), $filter); }
[ "protected", "function", "doListContents", "(", "$", "directory", ",", "$", "recursive", ")", "{", "$", "filter", "=", "function", "(", "$", "path", ")", "use", "(", "$", "directory", ",", "$", "recursive", ")", "{", "// Remove the root directory from any list...
Filters the file system returning paths inside the directory. @param string $directory @param bool $recursive @return string[]
[ "Filters", "the", "file", "system", "returning", "paths", "inside", "the", "directory", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Filesystem/Adapter/Memory.php#L269-L285
train
hail-framework/framework
src/Util/Validator.php
Validator.validateRequired
protected function validateRequired($field, $value, array $params = [], array $fields = []) { if (isset($params[0]) && (bool) $params[0]) { $find = $this->getPart($fields, \explode('.', $field), true); return $find[1]; } if (null === $value) { return false; } if (\is_string($value) && \trim($value) === '') { return false; } return true; }
php
protected function validateRequired($field, $value, array $params = [], array $fields = []) { if (isset($params[0]) && (bool) $params[0]) { $find = $this->getPart($fields, \explode('.', $field), true); return $find[1]; } if (null === $value) { return false; } if (\is_string($value) && \trim($value) === '') { return false; } return true; }
[ "protected", "function", "validateRequired", "(", "$", "field", ",", "$", "value", ",", "array", "$", "params", "=", "[", "]", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "0", "]", ")", "&&",...
Required field validator @param string $field @param mixed $value @param array $params @param array $fields @return bool
[ "Required", "field", "validator" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L131-L148
train
hail-framework/framework
src/Util/Validator.php
Validator.validateEquals
protected function validateEquals($field, $value, array $params) { // extract the second field value, this accounts for nested array values [$field2Value, $multiple] = $this->getPart($this->_fields, \explode('.', $params[0])); return null !== $field2Value && $value === $field2Value; }
php
protected function validateEquals($field, $value, array $params) { // extract the second field value, this accounts for nested array values [$field2Value, $multiple] = $this->getPart($this->_fields, \explode('.', $params[0])); return null !== $field2Value && $value === $field2Value; }
[ "protected", "function", "validateEquals", "(", "$", "field", ",", "$", "value", ",", "array", "$", "params", ")", "{", "// extract the second field value, this accounts for nested array values", "[", "$", "field2Value", ",", "$", "multiple", "]", "=", "$", "this", ...
Validate that two values match @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "that", "two", "values", "match" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L160-L166
train
hail-framework/framework
src/Util/Validator.php
Validator.validateInteger
protected function validateInteger($field, $value, $params) { if (isset($params[0]) && (bool) $params[0]) { //strict mode return preg_match('/^(\d|-[1-9]|-?[1-9]\d*)$/i', $value); } return \filter_var($value, \FILTER_VALIDATE_INT) !== false; }
php
protected function validateInteger($field, $value, $params) { if (isset($params[0]) && (bool) $params[0]) { //strict mode return preg_match('/^(\d|-[1-9]|-?[1-9]\d*)$/i', $value); } return \filter_var($value, \FILTER_VALIDATE_INT) !== false; }
[ "protected", "function", "validateInteger", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "0", "]", ")", "&&", "(", "bool", ")", "$", "params", "[", "0", "]", ")", "{", "//strict ...
Validate that a field is an integer @param string $field @param mixed $value @return bool
[ "Validate", "that", "a", "field", "is", "an", "integer" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L237-L245
train
hail-framework/framework
src/Util/Validator.php
Validator.validateLength
protected function validateLength($field, $value, $params) { $length = $this->stringLength($value); // Length between if (isset($params[1])) { return $length >= $params[0] && $length <= $params[1]; } // Length same return ($length !== false) && $length == $params[0]; }
php
protected function validateLength($field, $value, $params) { $length = $this->stringLength($value); // Length between if (isset($params[1])) { return $length >= $params[0] && $length <= $params[1]; } // Length same return ($length !== false) && $length == $params[0]; }
[ "protected", "function", "validateLength", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "$", "length", "=", "$", "this", "->", "stringLength", "(", "$", "value", ")", ";", "// Length between", "if", "(", "isset", "(", "$", "param...
Validate the length of a string @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "the", "length", "of", "a", "string" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L257-L267
train
hail-framework/framework
src/Util/Validator.php
Validator.validateMin
protected function validateMin($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (\function_exists('\bccomp')) { return !(\bccomp($params[0], $value, 14) === 1); } return $params[0] <= $value; }
php
protected function validateMin($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (\function_exists('\bccomp')) { return !(\bccomp($params[0], $value, 14) === 1); } return $params[0] <= $value; }
[ "protected", "function", "validateMin", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "!", "\\", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "if", "(", "\\", "function_exists", "(", ...
Validate the size of a field is greater than a minimum value. @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "the", "size", "of", "a", "field", "is", "greater", "than", "a", "minimum", "value", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L343-L354
train
hail-framework/framework
src/Util/Validator.php
Validator.validateMax
protected function validateMax($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (\function_exists('\bccomp')) { return !(\bccomp($value, $params[0], 14) === 1); } return $params[0] >= $value; }
php
protected function validateMax($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (\function_exists('\bccomp')) { return !(\bccomp($value, $params[0], 14) === 1); } return $params[0] >= $value; }
[ "protected", "function", "validateMax", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "!", "\\", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "if", "(", "\\", "function_exists", "(", ...
Validate the size of a field is less than a maximum value @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "the", "size", "of", "a", "field", "is", "less", "than", "a", "maximum", "value" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L366-L377
train
hail-framework/framework
src/Util/Validator.php
Validator.validateBetween
protected function validateBetween($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (!isset($params[0]) || !\is_array($params[0]) || \count($params[0]) !== 2) { return false; } list($min, $max) = $params[0]; return $this->validateMin($field, $value, [$min]) && $this->validateMax($field, $value, [$max]); }
php
protected function validateBetween($field, $value, $params) { if (!\is_numeric($value)) { return false; } if (!isset($params[0]) || !\is_array($params[0]) || \count($params[0]) !== 2) { return false; } list($min, $max) = $params[0]; return $this->validateMin($field, $value, [$min]) && $this->validateMax($field, $value, [$max]); }
[ "protected", "function", "validateBetween", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "!", "\\", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "isset", "(", "$", ...
Validate the size of a field is between min and max values @param string $field @param mixed $value @param array $params @return bool
[ "Validate", "the", "size", "of", "a", "field", "is", "between", "min", "and", "max", "values" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L388-L400
train
hail-framework/framework
src/Util/Validator.php
Validator.validateIn
protected function validateIn($field, $value, $params) { $isAssoc = \array_values($params[0]) !== $params[0]; if ($isAssoc) { $params[0] = \array_keys($params[0]); } $strict = false; if (isset($params[1])) { $strict = $params[1]; } return \in_array($value, $params[0], $strict); }
php
protected function validateIn($field, $value, $params) { $isAssoc = \array_values($params[0]) !== $params[0]; if ($isAssoc) { $params[0] = \array_keys($params[0]); } $strict = false; if (isset($params[1])) { $strict = $params[1]; } return \in_array($value, $params[0], $strict); }
[ "protected", "function", "validateIn", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "$", "isAssoc", "=", "\\", "array_values", "(", "$", "params", "[", "0", "]", ")", "!==", "$", "params", "[", "0", "]", ";", "if", "(", "$"...
Validate a field is contained within a list of values @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "a", "field", "is", "contained", "within", "a", "list", "of", "values" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L412-L425
train
hail-framework/framework
src/Util/Validator.php
Validator.validateContains
protected function validateContains($field, $value, $params) { if (!isset($params[0])) { return false; } if (!\is_string($value) || !\is_string($params[0])) { return false; } $strict = true; if (isset($params[1])) { $strict = (bool) $params[1]; } if ($strict) { return \mb_strpos($value, $params[0]) !== false; } return \mb_stripos($value, $params[0]) !== false; }
php
protected function validateContains($field, $value, $params) { if (!isset($params[0])) { return false; } if (!\is_string($value) || !\is_string($params[0])) { return false; } $strict = true; if (isset($params[1])) { $strict = (bool) $params[1]; } if ($strict) { return \mb_strpos($value, $params[0]) !== false; } return \mb_stripos($value, $params[0]) !== false; }
[ "protected", "function", "validateContains", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "0", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "\\", "is_str...
Validate a field contains a given string @param string $field @param string $value @param array $params @return bool
[ "Validate", "a", "field", "contains", "a", "given", "string" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L451-L470
train
hail-framework/framework
src/Util/Validator.php
Validator.validateSubset
protected function validateSubset($field, $value, $params) { if (!isset($params[0])) { return false; } if (!\is_array($params[0])) { $params[0] = [$params[0]]; } if (\is_scalar($value)) { return $this->validateIn($field, $value, $params); } $intersect = \array_intersect($value, $params[0]); return \array_diff($value, $intersect) === \array_diff($intersect, $value); }
php
protected function validateSubset($field, $value, $params) { if (!isset($params[0])) { return false; } if (!\is_array($params[0])) { $params[0] = [$params[0]]; } if (\is_scalar($value)) { return $this->validateIn($field, $value, $params); } $intersect = \array_intersect($value, $params[0]); return \array_diff($value, $intersect) === \array_diff($intersect, $value); }
[ "protected", "function", "validateSubset", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "0", "]", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "\\", "is_array...
Validate that all field values contains a given array @param string $field @param array $value @param array $params @return bool
[ "Validate", "that", "all", "field", "values", "contains", "a", "given", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L481-L495
train
hail-framework/framework
src/Util/Validator.php
Validator.validateContainsUnique
protected function validateContainsUnique($field, $value) { if (!\is_array($value)) { return false; } return $value === \array_unique($value, SORT_REGULAR); }
php
protected function validateContainsUnique($field, $value) { if (!\is_array($value)) { return false; } return $value === \array_unique($value, SORT_REGULAR); }
[ "protected", "function", "validateContainsUnique", "(", "$", "field", ",", "$", "value", ")", "{", "if", "(", "!", "\\", "is_array", "(", "$", "value", ")", ")", "{", "return", "false", ";", "}", "return", "$", "value", "===", "\\", "array_unique", "("...
Validate that field array has only unique values @param string $field @param array $value @return bool
[ "Validate", "that", "field", "array", "has", "only", "unique", "values" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L505-L512
train
hail-framework/framework
src/Util/Validator.php
Validator.validateEmailDNS
protected function validateEmailDNS($field, $value) { if ($this->validateEmail($field, $value)) { $domain = \ltrim(\strstr($value, '@'), '@') . '.'; if (\defined('INTL_IDNA_VARIANT_UTS46') && \function_exists('\idn_to_ascii')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } return \checkdnsrr($domain, 'ANY'); } return false; }
php
protected function validateEmailDNS($field, $value) { if ($this->validateEmail($field, $value)) { $domain = \ltrim(\strstr($value, '@'), '@') . '.'; if (\defined('INTL_IDNA_VARIANT_UTS46') && \function_exists('\idn_to_ascii')) { $domain = \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); } return \checkdnsrr($domain, 'ANY'); } return false; }
[ "protected", "function", "validateEmailDNS", "(", "$", "field", ",", "$", "value", ")", "{", "if", "(", "$", "this", "->", "validateEmail", "(", "$", "field", ",", "$", "value", ")", ")", "{", "$", "domain", "=", "\\", "ltrim", "(", "\\", "strstr", ...
Validate that a field is a valid e-mail address and the domain name is active @param string $field @param mixed $value @return bool
[ "Validate", "that", "a", "field", "is", "a", "valid", "e", "-", "mail", "address", "and", "the", "domain", "name", "is", "active" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L593-L605
train
hail-framework/framework
src/Util/Validator.php
Validator.validateUrl
protected function validateUrl($field, $value) { foreach (static::$validUrlPrefixes as $prefix) { if (\strpos($value, $prefix) !== false) { return \filter_var($value, \FILTER_VALIDATE_URL) !== false; } } return false; }
php
protected function validateUrl($field, $value) { foreach (static::$validUrlPrefixes as $prefix) { if (\strpos($value, $prefix) !== false) { return \filter_var($value, \FILTER_VALIDATE_URL) !== false; } } return false; }
[ "protected", "function", "validateUrl", "(", "$", "field", ",", "$", "value", ")", "{", "foreach", "(", "static", "::", "$", "validUrlPrefixes", "as", "$", "prefix", ")", "{", "if", "(", "\\", "strpos", "(", "$", "value", ",", "$", "prefix", ")", "!=...
Validate that a field is a valid URL by syntax @param string $field @param mixed $value @return bool
[ "Validate", "that", "a", "field", "is", "a", "valid", "URL", "by", "syntax" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L615-L624
train
hail-framework/framework
src/Util/Validator.php
Validator.validateUrlActive
protected function validateUrlActive($field, $value) { foreach (static::$validUrlPrefixes as $prefix) { if (\strpos($value, $prefix) !== false) { $host = \parse_url(\strtolower($value), PHP_URL_HOST); return \checkdnsrr($host, 'A') || \checkdnsrr($host, 'AAAA') || \checkdnsrr($host, 'CNAME'); } } return false; }
php
protected function validateUrlActive($field, $value) { foreach (static::$validUrlPrefixes as $prefix) { if (\strpos($value, $prefix) !== false) { $host = \parse_url(\strtolower($value), PHP_URL_HOST); return \checkdnsrr($host, 'A') || \checkdnsrr($host, 'AAAA') || \checkdnsrr($host, 'CNAME'); } } return false; }
[ "protected", "function", "validateUrlActive", "(", "$", "field", ",", "$", "value", ")", "{", "foreach", "(", "static", "::", "$", "validUrlPrefixes", "as", "$", "prefix", ")", "{", "if", "(", "\\", "strpos", "(", "$", "value", ",", "$", "prefix", ")",...
Validate that a field is an active URL by verifying DNS record @param string $field @param mixed $value @return bool
[ "Validate", "that", "a", "field", "is", "an", "active", "URL", "by", "verifying", "DNS", "record" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L634-L645
train
hail-framework/framework
src/Util/Validator.php
Validator.validateDateFormat
protected function validateDateFormat($field, $value, $params) { $parsed = \date_parse_from_format($params[0], $value); return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0; }
php
protected function validateDateFormat($field, $value, $params) { $parsed = \date_parse_from_format($params[0], $value); return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0; }
[ "protected", "function", "validateDateFormat", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "$", "parsed", "=", "\\", "date_parse_from_format", "(", "$", "params", "[", "0", "]", ",", "$", "value", ")", ";", "return", "$", "parse...
Validate that a field matches a date format @param string $field @param mixed $value @param array $params @internal param array $fields @return bool
[ "Validate", "that", "a", "field", "matches", "a", "date", "format" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L731-L736
train
hail-framework/framework
src/Util/Validator.php
Validator.validateCreditCard
protected function validateCreditCard($field, $value, $params) { /** * I there has been an array of valid cards supplied, or the name of the users card * or the name and an array of valid cards */ if (!empty($params)) { /** * array of valid cards */ if (\is_array($params[0])) { $cards = $params[0]; } elseif (\is_string($params[0])) { $cardType = $params[0]; if (isset($params[1]) && \is_array($params[1])) { $cards = $params[1]; if (!\in_array($cardType, $cards, true)) { return false; } } } } if ($this->creditCardNumberIsValid($value)) { $cardRegex = [ 'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#', 'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#', 'amex' => '#^3[47][0-9]{13}$#', 'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#', 'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#', ]; if (isset($cardType)) { // if we don't have any valid cards specified and the card we've been given isn't in our regex array if (!isset($cards) && !isset($cardRegex[$cardType])) { return false; } // we only need to test against one card type return (\preg_match($cardRegex[$cardType], $value) === 1); } if (isset($cards)) { // if we have cards, check our users card against only the ones we have foreach ($cards as $card) { if ( isset($cardRegex[$card]) && \preg_match($cardRegex[$card], $value) === 1 // if the card is valid, we want to stop looping ) { return true; } } } else { // loop through every card foreach ($cardRegex as $regex) { // until we find a valid one if (\preg_match($regex, $value) === 1) { return true; } } } } // if we've got this far, the card has passed no validation so it's invalid! return false; }
php
protected function validateCreditCard($field, $value, $params) { /** * I there has been an array of valid cards supplied, or the name of the users card * or the name and an array of valid cards */ if (!empty($params)) { /** * array of valid cards */ if (\is_array($params[0])) { $cards = $params[0]; } elseif (\is_string($params[0])) { $cardType = $params[0]; if (isset($params[1]) && \is_array($params[1])) { $cards = $params[1]; if (!\in_array($cardType, $cards, true)) { return false; } } } } if ($this->creditCardNumberIsValid($value)) { $cardRegex = [ 'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#', 'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#', 'amex' => '#^3[47][0-9]{13}$#', 'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#', 'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#', ]; if (isset($cardType)) { // if we don't have any valid cards specified and the card we've been given isn't in our regex array if (!isset($cards) && !isset($cardRegex[$cardType])) { return false; } // we only need to test against one card type return (\preg_match($cardRegex[$cardType], $value) === 1); } if (isset($cards)) { // if we have cards, check our users card against only the ones we have foreach ($cards as $card) { if ( isset($cardRegex[$card]) && \preg_match($cardRegex[$card], $value) === 1 // if the card is valid, we want to stop looping ) { return true; } } } else { // loop through every card foreach ($cardRegex as $regex) { // until we find a valid one if (\preg_match($regex, $value) === 1) { return true; } } } } // if we've got this far, the card has passed no validation so it's invalid! return false; }
[ "protected", "function", "validateCreditCard", "(", "$", "field", ",", "$", "value", ",", "$", "params", ")", "{", "/**\n * I there has been an array of valid cards supplied, or the name of the users card\n * or the name and an array of valid cards\n */", "if", ...
Validate that a field contains a valid credit card optionally filtered by an array @param string $field @param mixed $value @param array $params @return bool
[ "Validate", "that", "a", "field", "contains", "a", "valid", "credit", "card", "optionally", "filtered", "by", "an", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L797-L863
train
hail-framework/framework
src/Util/Validator.php
Validator.data
public function data(array $data, array $fields = []) { // Allows filtering of used input fields against optional second array of field names allowed // This is useful for limiting raw $_POST or $_GET data to only known fields $this->_fields = $fields !== [] ? \array_intersect_key($data, \array_flip($fields)) : $data; return $this; }
php
public function data(array $data, array $fields = []) { // Allows filtering of used input fields against optional second array of field names allowed // This is useful for limiting raw $_POST or $_GET data to only known fields $this->_fields = $fields !== [] ? \array_intersect_key($data, \array_flip($fields)) : $data; return $this; }
[ "public", "function", "data", "(", "array", "$", "data", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "// Allows filtering of used input fields against optional second array of field names allowed", "// This is useful for limiting raw $_POST or $_GET data to only known fie...
Set data for validator @param array $data @param array $fields @return $this
[ "Set", "data", "for", "validator" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L936-L943
train
hail-framework/framework
src/Util/Validator.php
Validator.errors
public function errors(string $field = null) { if ($field !== null) { return $this->_errors[$field] ?? false; } return $this->_errors; }
php
public function errors(string $field = null) { if ($field !== null) { return $this->_errors[$field] ?? false; } return $this->_errors; }
[ "public", "function", "errors", "(", "string", "$", "field", "=", "null", ")", "{", "if", "(", "$", "field", "!==", "null", ")", "{", "return", "$", "this", "->", "_errors", "[", "$", "field", "]", "??", "false", ";", "}", "return", "$", "this", ...
Get array of error messages @param null|string $field @return array|bool
[ "Get", "array", "of", "error", "messages" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L962-L969
train
hail-framework/framework
src/Util/Validator.php
Validator.error
public function error(string $field, string $message, array $params = []) { $message = $this->checkAndSetLabel($field, $message, $params); $values = []; // Printed values need to be in string format foreach ($params as $param) { if (\is_array($param)) { $param = "['" . implode("', '", $param) . "']"; } elseif ($param instanceof \DateTime) { $param = $param->format('Y-m-d'); } elseif (\is_object($param)) { $param = \get_class($param); } // Use custom label instead of field name if set if (\is_string($params[0]) && isset($this->_labels[$param])) { $param = $this->_labels[$param]; } $values[] = $param; } $this->_errors[$field][] = \vsprintf($message, $values); }
php
public function error(string $field, string $message, array $params = []) { $message = $this->checkAndSetLabel($field, $message, $params); $values = []; // Printed values need to be in string format foreach ($params as $param) { if (\is_array($param)) { $param = "['" . implode("', '", $param) . "']"; } elseif ($param instanceof \DateTime) { $param = $param->format('Y-m-d'); } elseif (\is_object($param)) { $param = \get_class($param); } // Use custom label instead of field name if set if (\is_string($params[0]) && isset($this->_labels[$param])) { $param = $this->_labels[$param]; } $values[] = $param; } $this->_errors[$field][] = \vsprintf($message, $values); }
[ "public", "function", "error", "(", "string", "$", "field", ",", "string", "$", "message", ",", "array", "$", "params", "=", "[", "]", ")", "{", "$", "message", "=", "$", "this", "->", "checkAndSetLabel", "(", "$", "field", ",", "$", "message", ",", ...
Add an error to error messages array @param string $field @param string $message @param array $params
[ "Add", "an", "error", "to", "error", "messages", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L978-L1001
train
hail-framework/framework
src/Util/Validator.php
Validator.message
public function message(string $message) { $this->_validations[\count($this->_validations) - 1]['message'] = $message; return $this; }
php
public function message(string $message) { $this->_validations[\count($this->_validations) - 1]['message'] = $message; return $this; }
[ "public", "function", "message", "(", "string", "$", "message", ")", "{", "$", "this", "->", "_validations", "[", "\\", "count", "(", "$", "this", "->", "_validations", ")", "-", "1", "]", "[", "'message'", "]", "=", "$", "message", ";", "return", "$...
Specify validation message to use for error for the last validation rule @param string $message @return $this
[ "Specify", "validation", "message", "to", "use", "for", "error", "for", "the", "last", "validation", "rule" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1010-L1015
train
hail-framework/framework
src/Util/Validator.php
Validator.reset
public function reset() { $this->_fields = []; $this->_errors = []; $this->_validations = []; $this->_labels = []; $this->_skips = []; return $this; }
php
public function reset() { $this->_fields = []; $this->_errors = []; $this->_validations = []; $this->_labels = []; $this->_skips = []; return $this; }
[ "public", "function", "reset", "(", ")", "{", "$", "this", "->", "_fields", "=", "[", "]", ";", "$", "this", "->", "_errors", "=", "[", "]", ";", "$", "this", "->", "_validations", "=", "[", "]", ";", "$", "this", "->", "_labels", "=", "[", "]"...
Reset object properties @return $this
[ "Reset", "object", "properties" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1022-L1031
train
hail-framework/framework
src/Util/Validator.php
Validator.validate
public function validate() { $setToBreak = false; foreach ($this->_validations as $v) { foreach ($v['fields'] as $field) { if (isset($this->_skips[$field])) { if ($this->_skips[$field] === self::SKIP_ALL) { break 2; } if ($this->_skips[$field] === self::SKIP_ONE) { break; } } [$values, $multiple] = $this->getPart($this->_fields, \explode('.', $field)); // Don't validate if the field is not required and the value is empty if (null !== $values && $this->hasRule('optional', $field)) { //Continue with execution below if statement } elseif ( $v['rule'] !== 'accepted' && $v['rule'] !== 'required' && !$this->hasRule('required', $field) && (null === $values || $values === '' || ($multiple && \count($values) === 0)) ) { continue; } // Callback is user-specified or assumed method on class $errors = $this->getRules(); if (isset($errors[$v['rule']])) { $callback = $errors[$v['rule']]; } else { $callback = [$this, 'validate' . \ucfirst($v['rule'])]; } if (!$multiple) { $values = [$values]; } $result = true; foreach ($values as $value) { $result = $result && $callback($field, $value, $v['params'], $this->_fields); } if (!$result) { $this->error($field, $v['message'], $v['params']); if ($this->stopOnFirstFail) { $setToBreak = true; break; } $this->_skips[$field] = $v['skip']; } } if ($setToBreak) { break; } } return \count($this->errors()) === 0; }
php
public function validate() { $setToBreak = false; foreach ($this->_validations as $v) { foreach ($v['fields'] as $field) { if (isset($this->_skips[$field])) { if ($this->_skips[$field] === self::SKIP_ALL) { break 2; } if ($this->_skips[$field] === self::SKIP_ONE) { break; } } [$values, $multiple] = $this->getPart($this->_fields, \explode('.', $field)); // Don't validate if the field is not required and the value is empty if (null !== $values && $this->hasRule('optional', $field)) { //Continue with execution below if statement } elseif ( $v['rule'] !== 'accepted' && $v['rule'] !== 'required' && !$this->hasRule('required', $field) && (null === $values || $values === '' || ($multiple && \count($values) === 0)) ) { continue; } // Callback is user-specified or assumed method on class $errors = $this->getRules(); if (isset($errors[$v['rule']])) { $callback = $errors[$v['rule']]; } else { $callback = [$this, 'validate' . \ucfirst($v['rule'])]; } if (!$multiple) { $values = [$values]; } $result = true; foreach ($values as $value) { $result = $result && $callback($field, $value, $v['params'], $this->_fields); } if (!$result) { $this->error($field, $v['message'], $v['params']); if ($this->stopOnFirstFail) { $setToBreak = true; break; } $this->_skips[$field] = $v['skip']; } } if ($setToBreak) { break; } } return \count($this->errors()) === 0; }
[ "public", "function", "validate", "(", ")", "{", "$", "setToBreak", "=", "false", ";", "foreach", "(", "$", "this", "->", "_validations", "as", "$", "v", ")", "{", "foreach", "(", "$", "v", "[", "'fields'", "]", "as", "$", "field", ")", "{", "if", ...
Run validations and return boolean result @return bool
[ "Run", "validations", "and", "return", "boolean", "result" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1094-L1156
train
hail-framework/framework
src/Util/Validator.php
Validator.onErrorSkipField
public function onErrorSkipField(): self { $this->_validations[\count($this->_validations) - 1]['skip'] = self::SKIP_ONE; return $this; }
php
public function onErrorSkipField(): self { $this->_validations[\count($this->_validations) - 1]['skip'] = self::SKIP_ONE; return $this; }
[ "public", "function", "onErrorSkipField", "(", ")", ":", "self", "{", "$", "this", "->", "_validations", "[", "\\", "count", "(", "$", "this", "->", "_validations", ")", "-", "1", "]", "[", "'skip'", "]", "=", "self", "::", "SKIP_ONE", ";", "return", ...
If the validation for a field fails, skip all other checks for this field. @return static
[ "If", "the", "validation", "for", "a", "field", "fails", "skip", "all", "other", "checks", "for", "this", "field", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1177-L1182
train
hail-framework/framework
src/Util/Validator.php
Validator.onErrorQuit
public function onErrorQuit(): self { $this->_validations[\count($this->_validations) - 1]['skip'] = self::SKIP_ALL; return $this; }
php
public function onErrorQuit(): self { $this->_validations[\count($this->_validations) - 1]['skip'] = self::SKIP_ALL; return $this; }
[ "public", "function", "onErrorQuit", "(", ")", ":", "self", "{", "$", "this", "->", "_validations", "[", "\\", "count", "(", "$", "this", "->", "_validations", ")", "-", "1", "]", "[", "'skip'", "]", "=", "self", "::", "SKIP_ALL", ";", "return", "$",...
If the validation of a field fails, stop the validation process. @return static
[ "If", "the", "validation", "of", "a", "field", "fails", "stop", "the", "validation", "process", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1189-L1194
train
hail-framework/framework
src/Util/Validator.php
Validator.hasRule
protected function hasRule(string $name, string $field): bool { foreach ($this->_validations as $validation) { if ($validation['rule'] === $name && \in_array($field, $validation['fields'], true)) { return true; } } return false; }
php
protected function hasRule(string $name, string $field): bool { foreach ($this->_validations as $validation) { if ($validation['rule'] === $name && \in_array($field, $validation['fields'], true)) { return true; } } return false; }
[ "protected", "function", "hasRule", "(", "string", "$", "name", ",", "string", "$", "field", ")", ":", "bool", "{", "foreach", "(", "$", "this", "->", "_validations", "as", "$", "validation", ")", "{", "if", "(", "$", "validation", "[", "'rule'", "]", ...
Determine whether a field is being validated by the given rule. @param string $name The name of the rule @param string $field The name of the field @return bool
[ "Determine", "whether", "a", "field", "is", "being", "validated", "by", "the", "given", "rule", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1224-L1233
train
hail-framework/framework
src/Util/Validator.php
Validator.addInstanceRule
public function addInstanceRule(string $name, callable $callback, string $message = null): self { static::assertRuleCallback($callback); $this->_instanceRules[$name] = $callback; $this->_instanceRuleMessage[$name] = $message; return $this; }
php
public function addInstanceRule(string $name, callable $callback, string $message = null): self { static::assertRuleCallback($callback); $this->_instanceRules[$name] = $callback; $this->_instanceRuleMessage[$name] = $message; return $this; }
[ "public", "function", "addInstanceRule", "(", "string", "$", "name", ",", "callable", "$", "callback", ",", "string", "$", "message", "=", "null", ")", ":", "self", "{", "static", "::", "assertRuleCallback", "(", "$", "callback", ")", ";", "$", "this", "...
Adds a new validation rule callback that is tied to the current instance only. @param string $name @param callable $callback @param string $message @return $this @throws \InvalidArgumentException
[ "Adds", "a", "new", "validation", "rule", "callback", "that", "is", "tied", "to", "the", "current", "instance", "only", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1253-L1261
train
hail-framework/framework
src/Util/Validator.php
Validator.addRule
public function addRule(string $name, callable $callback, string $message = null): self { if ($message === null) { $message = static::ERROR_DEFAULT; } static::assertRuleCallback($callback); static::$_rules[$name] = $callback; static::$_ruleMessages[$name] = $message; return $this; }
php
public function addRule(string $name, callable $callback, string $message = null): self { if ($message === null) { $message = static::ERROR_DEFAULT; } static::assertRuleCallback($callback); static::$_rules[$name] = $callback; static::$_ruleMessages[$name] = $message; return $this; }
[ "public", "function", "addRule", "(", "string", "$", "name", ",", "callable", "$", "callback", ",", "string", "$", "message", "=", "null", ")", ":", "self", "{", "if", "(", "$", "message", "===", "null", ")", "{", "$", "message", "=", "static", "::",...
Register new validation rule callback @param string $name @param callable $callback @param string $message @return $this @throws \InvalidArgumentException
[ "Register", "new", "validation", "rule", "callback" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1273-L1285
train
hail-framework/framework
src/Util/Validator.php
Validator.hasValidator
public function hasValidator(string $name): bool { $rules = $this->getRules(); return \method_exists($this, 'validate' . \ucfirst($name)) || isset($rules[$name]); }
php
public function hasValidator(string $name): bool { $rules = $this->getRules(); return \method_exists($this, 'validate' . \ucfirst($name)) || isset($rules[$name]); }
[ "public", "function", "hasValidator", "(", "string", "$", "name", ")", ":", "bool", "{", "$", "rules", "=", "$", "this", "->", "getRules", "(", ")", ";", "return", "\\", "method_exists", "(", "$", "this", ",", "'validate'", ".", "\\", "ucfirst", "(", ...
Returns true if either a validator with the given name has been registered or there is a default validator by that name. @param string $name @return bool
[ "Returns", "true", "if", "either", "a", "validator", "with", "the", "given", "name", "has", "been", "registered", "or", "there", "is", "a", "default", "validator", "by", "that", "name", "." ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1316-L1321
train
hail-framework/framework
src/Util/Validator.php
Validator.rule
public function rule($rule, $fields, ...$params) { if (\is_callable($rule) && !(\is_string($rule) && $this->hasValidator($rule)) ) { $name = $this->getUniqueRuleName($fields); $message = $params[0] ?? null; $this->addInstanceRule($name, $rule, $message); $rule = $name; } $errors = $this->getRules(); if (!isset($errors[$rule])) { $ruleMethod = 'validate' . \ucfirst($rule); if (!\method_exists($this, $ruleMethod)) { throw new \InvalidArgumentException("Rule '" . $rule . "' has not been registered with " . __CLASS__ . "::addRule()."); } } // Ensure rule has an accompanying message $messages = $this->getRuleMessages(); $message = $messages[$rule] ?? self::ERROR_DEFAULT; // Ensure message contains field label if (\strpos($message, '{field}') === false) { $message = '{field} ' . $message; } $this->_validations[] = [ 'rule' => $rule, 'fields' => (array) $fields, 'params' => (array) $params, 'message' => '{field} ' . $message, 'skip' => self::SKIP_CONTINUE, ]; return $this; }
php
public function rule($rule, $fields, ...$params) { if (\is_callable($rule) && !(\is_string($rule) && $this->hasValidator($rule)) ) { $name = $this->getUniqueRuleName($fields); $message = $params[0] ?? null; $this->addInstanceRule($name, $rule, $message); $rule = $name; } $errors = $this->getRules(); if (!isset($errors[$rule])) { $ruleMethod = 'validate' . \ucfirst($rule); if (!\method_exists($this, $ruleMethod)) { throw new \InvalidArgumentException("Rule '" . $rule . "' has not been registered with " . __CLASS__ . "::addRule()."); } } // Ensure rule has an accompanying message $messages = $this->getRuleMessages(); $message = $messages[$rule] ?? self::ERROR_DEFAULT; // Ensure message contains field label if (\strpos($message, '{field}') === false) { $message = '{field} ' . $message; } $this->_validations[] = [ 'rule' => $rule, 'fields' => (array) $fields, 'params' => (array) $params, 'message' => '{field} ' . $message, 'skip' => self::SKIP_CONTINUE, ]; return $this; }
[ "public", "function", "rule", "(", "$", "rule", ",", "$", "fields", ",", "...", "$", "params", ")", "{", "if", "(", "\\", "is_callable", "(", "$", "rule", ")", "&&", "!", "(", "\\", "is_string", "(", "$", "rule", ")", "&&", "$", "this", "->", "...
Convenience method to add a single validation rule @param string|callable $rule @param array|string $fields @param mixed ...$params @return $this @throws \InvalidArgumentException
[ "Convenience", "method", "to", "add", "a", "single", "validation", "rule" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1333-L1370
train
hail-framework/framework
src/Util/Validator.php
Validator.rules
public function rules(array $rules) { foreach ($rules as $ruleType => $params) { if (\is_array($params)) { foreach ($params as $innerParams) { $innerParams = (array) $innerParams; $this->rule($ruleType, ...$innerParams); } } else { $this->rule($ruleType, $params); } } return $this; }
php
public function rules(array $rules) { foreach ($rules as $ruleType => $params) { if (\is_array($params)) { foreach ($params as $innerParams) { $innerParams = (array) $innerParams; $this->rule($ruleType, ...$innerParams); } } else { $this->rule($ruleType, $params); } } return $this; }
[ "public", "function", "rules", "(", "array", "$", "rules", ")", "{", "foreach", "(", "$", "rules", "as", "$", "ruleType", "=>", "$", "params", ")", "{", "if", "(", "\\", "is_array", "(", "$", "params", ")", ")", "{", "foreach", "(", "$", "params", ...
Convenience method to add multiple validation rules with an array @param array $rules @return $this @throws \InvalidArgumentException
[ "Convenience", "method", "to", "add", "multiple", "validation", "rules", "with", "an", "array" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1441-L1455
train
hail-framework/framework
src/Util/Validator.php
Validator.withData
public function withData(array $data, array $fields = []) { $clone = clone $this; $clone->_fields = !empty($fields) ? \array_intersect_key($data, \array_flip($fields)) : $data; $clone->_errors = []; return $clone; }
php
public function withData(array $data, array $fields = []) { $clone = clone $this; $clone->_fields = !empty($fields) ? \array_intersect_key($data, \array_flip($fields)) : $data; $clone->_errors = []; return $clone; }
[ "public", "function", "withData", "(", "array", "$", "data", ",", "array", "$", "fields", "=", "[", "]", ")", "{", "$", "clone", "=", "clone", "$", "this", ";", "$", "clone", "->", "_fields", "=", "!", "empty", "(", "$", "fields", ")", "?", "\\",...
Replace data on cloned instance @param array $data @param array $fields @return \Hail\Util\Validator
[ "Replace", "data", "on", "cloned", "instance" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Util/Validator.php#L1465-L1472
train
hail-framework/framework
src/Console/Buffer.php
Buffer.appendLine
public function appendLine($line, $indent = 0) { $this->content .= ($indent ? $this->makeIndent($indent) : $this->indentCache) . $line . $this->newline; }
php
public function appendLine($line, $indent = 0) { $this->content .= ($indent ? $this->makeIndent($indent) : $this->indentCache) . $line . $this->newline; }
[ "public", "function", "appendLine", "(", "$", "line", ",", "$", "indent", "=", "0", ")", "{", "$", "this", "->", "content", ".=", "(", "$", "indent", "?", "$", "this", "->", "makeIndent", "(", "$", "indent", ")", ":", "$", "this", "->", "indentCach...
Append a line with indent to the buffer @param string $line @param int $indent
[ "Append", "a", "line", "with", "indent", "to", "the", "buffer" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Buffer.php#L99-L102
train
hail-framework/framework
src/Console/Buffer.php
Buffer.appendLines
public function appendLines($lines, $indent = 0) { foreach ($lines as $line) { $this->appendLine($line, $indent); } }
php
public function appendLines($lines, $indent = 0) { foreach ($lines as $line) { $this->appendLine($line, $indent); } }
[ "public", "function", "appendLines", "(", "$", "lines", ",", "$", "indent", "=", "0", ")", "{", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "$", "this", "->", "appendLine", "(", "$", "line", ",", "$", "indent", ")", ";", "}", "}" ]
Append multiple lines with indent to the buffer @param string[] $lines @param int $indent
[ "Append", "multiple", "lines", "with", "indent", "to", "the", "buffer" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Buffer.php#L111-L116
train
hail-framework/framework
src/Console/Buffer.php
Buffer.setFormat
public function setFormat($format) { $this->format = $format; if ($this->format === self::FORMAT_UNIX) { $this->newline = "\n"; } elseif ($this->format === self::FORMAT_DOS) { $this->newline = "\r\n"; } }
php
public function setFormat($format) { $this->format = $format; if ($this->format === self::FORMAT_UNIX) { $this->newline = "\n"; } elseif ($this->format === self::FORMAT_DOS) { $this->newline = "\r\n"; } }
[ "public", "function", "setFormat", "(", "$", "format", ")", "{", "$", "this", "->", "format", "=", "$", "format", ";", "if", "(", "$", "this", "->", "format", "===", "self", "::", "FORMAT_UNIX", ")", "{", "$", "this", "->", "newline", "=", "\"\\n\"",...
Set line format @param int $format Buffer::FORMAT_UNIX or Buffer::FORMAT_DOS
[ "Set", "line", "format" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Buffer.php#L175-L183
train
hail-framework/framework
src/Console/Buffer.php
Buffer.appendBuffer
public function appendBuffer(Buffer $buf, $indent = 0) { if ($indent) { $this->setIndent($indent); $lines = $buf->lines(); foreach ($lines as $line) { $this->appendLine($line); } } else { $this->content .= $buf->__toString(); } }
php
public function appendBuffer(Buffer $buf, $indent = 0) { if ($indent) { $this->setIndent($indent); $lines = $buf->lines(); foreach ($lines as $line) { $this->appendLine($line); } } else { $this->content .= $buf->__toString(); } }
[ "public", "function", "appendBuffer", "(", "Buffer", "$", "buf", ",", "$", "indent", "=", "0", ")", "{", "if", "(", "$", "indent", ")", "{", "$", "this", "->", "setIndent", "(", "$", "indent", ")", ";", "$", "lines", "=", "$", "buf", "->", "lines...
Append a buffer object @param Buffer $buf @param int $indent = 0
[ "Append", "a", "buffer", "object" ]
d419e6c098d29ef9b62192b74050e51985b94f90
https://github.com/hail-framework/framework/blob/d419e6c098d29ef9b62192b74050e51985b94f90/src/Console/Buffer.php#L207-L218
train
htmlburger/wpemerge-cli
src/App.php
App.install
public static function install( Event $event ) { $binary_name = 'wpemerge'; $binary = dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $binary_name; $event->getIO()->write( '' ); $process = new Process( $binary . ' install' ); $process->setTimeout( null ); try { $process->setTty( true ); $process->run( function ( $type, $line ) use ( $event ) { $event->getIO()->write( $line ); }); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); $event->getIO()->write( '' ); $event->getIO()->write( 'Use <comment>./vendor/bin/' . $binary_name . ' install</comment> instead.' ); } }
php
public static function install( Event $event ) { $binary_name = 'wpemerge'; $binary = dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'bin' . DIRECTORY_SEPARATOR . $binary_name; $event->getIO()->write( '' ); $process = new Process( $binary . ' install' ); $process->setTimeout( null ); try { $process->setTty( true ); $process->run( function ( $type, $line ) use ( $event ) { $event->getIO()->write( $line ); }); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); $event->getIO()->write( '' ); $event->getIO()->write( 'Use <comment>./vendor/bin/' . $binary_name . ' install</comment> instead.' ); } }
[ "public", "static", "function", "install", "(", "Event", "$", "event", ")", "{", "$", "binary_name", "=", "'wpemerge'", ";", "$", "binary", "=", "dirname", "(", "__DIR__", ")", ".", "DIRECTORY_SEPARATOR", ".", "'bin'", ".", "DIRECTORY_SEPARATOR", ".", "$", ...
Run with the install command. @param Event $event @return void
[ "Run", "with", "the", "install", "command", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L71-L91
train
htmlburger/wpemerge-cli
src/App.php
App.createConfigJson
public static function createConfigJson( Event $event ) { if ( ! defined( 'WPEMERGE_CLI_DIR' ) ) { define( 'WPEMERGE_CLI_DIR', dirname( __DIR__ ) ); } $input = new ArrayInput( [ 'config:create' ] ); $output = new BufferedOutput(); try { $application = static::create(); $command = $application->find('config:create'); $command->run( $input, $output ); $event->getIO()->write( $output->fetch() ); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); } }
php
public static function createConfigJson( Event $event ) { if ( ! defined( 'WPEMERGE_CLI_DIR' ) ) { define( 'WPEMERGE_CLI_DIR', dirname( __DIR__ ) ); } $input = new ArrayInput( [ 'config:create' ] ); $output = new BufferedOutput(); try { $application = static::create(); $command = $application->find('config:create'); $command->run( $input, $output ); $event->getIO()->write( $output->fetch() ); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); } }
[ "public", "static", "function", "createConfigJson", "(", "Event", "$", "event", ")", "{", "if", "(", "!", "defined", "(", "'WPEMERGE_CLI_DIR'", ")", ")", "{", "define", "(", "'WPEMERGE_CLI_DIR'", ",", "dirname", "(", "__DIR__", ")", ")", ";", "}", "$", "...
Create a config.json in the theme root directory. @param Event $event @return void
[ "Create", "a", "config", ".", "json", "in", "the", "theme", "root", "directory", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L99-L115
train
htmlburger/wpemerge-cli
src/App.php
App.installDependencies
public static function installDependencies( Event $event ) { if ( ! defined( 'WPEMERGE_CLI_DIR' ) ) { define( 'WPEMERGE_CLI_DIR', dirname( __DIR__ ) ); } $input = new ArrayInput( [ 'install:dependencies' ] ); $output = new ConsoleOutput(); try { $application = static::create(); $command = $application->find('install:dependencies'); $command->run( $input, $output ); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); } }
php
public static function installDependencies( Event $event ) { if ( ! defined( 'WPEMERGE_CLI_DIR' ) ) { define( 'WPEMERGE_CLI_DIR', dirname( __DIR__ ) ); } $input = new ArrayInput( [ 'install:dependencies' ] ); $output = new ConsoleOutput(); try { $application = static::create(); $command = $application->find('install:dependencies'); $command->run( $input, $output ); } catch ( RuntimeException $e ) { $event->getIO()->write( '<error>' . $e->getMessage() . '</error>' ); } }
[ "public", "static", "function", "installDependencies", "(", "Event", "$", "event", ")", "{", "if", "(", "!", "defined", "(", "'WPEMERGE_CLI_DIR'", ")", ")", "{", "define", "(", "'WPEMERGE_CLI_DIR'", ",", "dirname", "(", "__DIR__", ")", ")", ";", "}", "$", ...
Install dependencies in the theme root directory. @param Event $event @return void
[ "Install", "dependencies", "in", "the", "theme", "root", "directory", "." ]
075f1982b7dd87039a4e7bbc05caf676a10fe862
https://github.com/htmlburger/wpemerge-cli/blob/075f1982b7dd87039a4e7bbc05caf676a10fe862/src/App.php#L123-L138
train