repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
txj123/zilf | src/Zilf/Db/Transaction.php | Transaction.rollBack | public function rollBack()
{
if (!$this->getIsActive()) {
// do nothing if transaction is not active: this could be the transaction is committed
// but the event handler to "commitTransaction" throw an exception
return;
}
$this->_level--;
if ($this->_level === 0) {
Log::debug('Roll back transaction' . __METHOD__);
$this->db->pdo->rollBack();
$this->db->trigger(Connection::EVENT_ROLLBACK_TRANSACTION);
return;
}
$schema = $this->db->getSchema();
if ($schema->supportsSavepoint()) {
Log::debug('Roll back to savepoint ' . $this->_level . __METHOD__);
$schema->rollBackSavepoint('LEVEL' . $this->_level);
} else {
Log::info('Transaction not rolled back: nested transaction not supported' . __METHOD__);
// throw an exception to fail the outer transaction
throw new Exception('Roll back failed: nested transaction not supported.');
}
} | php | public function rollBack()
{
if (!$this->getIsActive()) {
// do nothing if transaction is not active: this could be the transaction is committed
// but the event handler to "commitTransaction" throw an exception
return;
}
$this->_level--;
if ($this->_level === 0) {
Log::debug('Roll back transaction' . __METHOD__);
$this->db->pdo->rollBack();
$this->db->trigger(Connection::EVENT_ROLLBACK_TRANSACTION);
return;
}
$schema = $this->db->getSchema();
if ($schema->supportsSavepoint()) {
Log::debug('Roll back to savepoint ' . $this->_level . __METHOD__);
$schema->rollBackSavepoint('LEVEL' . $this->_level);
} else {
Log::info('Transaction not rolled back: nested transaction not supported' . __METHOD__);
// throw an exception to fail the outer transaction
throw new Exception('Roll back failed: nested transaction not supported.');
}
} | [
"public",
"function",
"rollBack",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getIsActive",
"(",
")",
")",
"{",
"// do nothing if transaction is not active: this could be the transaction is committed",
"// but the event handler to \"commitTransaction\" throw an exception",... | Rolls back a transaction.
@throws Exception if the transaction is not active | [
"Rolls",
"back",
"a",
"transaction",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Transaction.php#L191-L216 |
txj123/zilf | src/Zilf/Db/Transaction.php | Transaction.setIsolationLevel | public function setIsolationLevel($level)
{
if (!$this->getIsActive()) {
throw new Exception('Failed to set isolation level: transaction was inactive.');
}
Log::debug('Setting transaction isolation level to ' . $level . __METHOD__);
$this->db->getSchema()->setTransactionIsolationLevel($level);
} | php | public function setIsolationLevel($level)
{
if (!$this->getIsActive()) {
throw new Exception('Failed to set isolation level: transaction was inactive.');
}
Log::debug('Setting transaction isolation level to ' . $level . __METHOD__);
$this->db->getSchema()->setTransactionIsolationLevel($level);
} | [
"public",
"function",
"setIsolationLevel",
"(",
"$",
"level",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"getIsActive",
"(",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Failed to set isolation level: transaction was inactive.'",
")",
";",
"}",
"Log",
... | Sets the transaction isolation level for this transaction.
This method can be used to set the isolation level while the transaction is already active.
However this is not supported by all DBMS so you might rather specify the isolation level directly
when calling [[begin()]].
@param string $level The transaction isolation level to use for this transaction.
This can be one of [[READ_UNCOMMITTED]], [[READ_COMMITTED]], [[REPEATABLE_READ]] and [[SERIALIZABLE]] but
also a string containing DBMS specific syntax to be used after `SET TRANSACTION ISOLATION LEVEL`.
@throws Exception if the transaction is not active
@see http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels | [
"Sets",
"the",
"transaction",
"isolation",
"level",
"for",
"this",
"transaction",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Transaction.php#L231-L238 |
oxygen-cms/core | src/Html/Toolbar/FormToolbarItem.php | FormToolbarItem.render | public function render(array $arguments = [], $renderer = null) {
$this->runDynamicCallbacks($arguments);
return $this->baseRender($arguments, $renderer);
} | php | public function render(array $arguments = [], $renderer = null) {
$this->runDynamicCallbacks($arguments);
return $this->baseRender($arguments, $renderer);
} | [
"public",
"function",
"render",
"(",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"$",
"renderer",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"runDynamicCallbacks",
"(",
"$",
"arguments",
")",
";",
"return",
"$",
"this",
"->",
"baseRender",
"(",
"$",
... | Renders the object.
Before rendering all 'dynamic callbacks' will be excecuted.
@param array $arguments
@param RendererInterface|callable $renderer
@throws Exception
@return string the rendered object | [
"Renders",
"the",
"object",
".",
"Before",
"rendering",
"all",
"dynamic",
"callbacks",
"will",
"be",
"excecuted",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/FormToolbarItem.php#L52-L56 |
dave-redfern/laravel-doctrine-tenancy | src/Traits/BelongsToTenant.php | BelongsToTenant.belongsToTenant | public function belongsToTenant($tenant, $requireAll = false)
{
if (is_array($tenant)) {
foreach ($tenant as $t) {
$hasTenant = $this->belongsToTenant($t);
if ($hasTenant && !$requireAll) {
return true;
} elseif (!$hasTenant && $requireAll) {
return false;
}
}
return $requireAll;
} else {
if ($this instanceof BelongsToTenantParticipant) {
if (
!is_null($this->getTenantParticipant()) &&
$this->getTenantName($tenant) === $this->getTenantParticipant()->getName()
) {
return true;
}
}
if ($this instanceof BelongsToTenantParticipants) {
foreach ($this->getTenantParticipants() as $t) {
if ($this->getTenantName($tenant) === $t->getName()) {
return true;
}
}
}
return false;
}
} | php | public function belongsToTenant($tenant, $requireAll = false)
{
if (is_array($tenant)) {
foreach ($tenant as $t) {
$hasTenant = $this->belongsToTenant($t);
if ($hasTenant && !$requireAll) {
return true;
} elseif (!$hasTenant && $requireAll) {
return false;
}
}
return $requireAll;
} else {
if ($this instanceof BelongsToTenantParticipant) {
if (
!is_null($this->getTenantParticipant()) &&
$this->getTenantName($tenant) === $this->getTenantParticipant()->getName()
) {
return true;
}
}
if ($this instanceof BelongsToTenantParticipants) {
foreach ($this->getTenantParticipants() as $t) {
if ($this->getTenantName($tenant) === $t->getName()) {
return true;
}
}
}
return false;
}
} | [
"public",
"function",
"belongsToTenant",
"(",
"$",
"tenant",
",",
"$",
"requireAll",
"=",
"false",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"tenant",
")",
")",
"{",
"foreach",
"(",
"$",
"tenant",
"as",
"$",
"t",
")",
"{",
"$",
"hasTenant",
"=",
"... | @param TenantParticipantContract|string|array $tenant
@param boolean $requireAll
@return boolean | [
"@param",
"TenantParticipantContract|string|array",
"$tenant",
"@param",
"boolean",
"$requireAll"
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Traits/BelongsToTenant.php#L41-L74 |
oxygen-cms/core | src/Html/Header/Header.php | Header.fromBlueprint | public static function fromBlueprint(Blueprint $blueprint, $title, array $arguments = [], $type = self::TYPE_MAIN, $fillFromToolbar = 'section') {
if($title instanceof FieldSet) {
$title = $arguments['model']->getAttribute($title->getTitleFieldName());
} else {
if(!is_string($title)) {
throw new \InvalidArgumentException('$title must be either a string or an instance of \Oxygen\Core\Form\FieldSet');
}
}
$object = new static(
$title,
$arguments,
$type
);
// sets a prefix to all the routes in the toolbar
$object->getToolbar()->setPrefix($blueprint->getRouteName());
// fills the toolbar with buttons from the blueprint
$object->getToolbar()->fillFromBlueprint($blueprint, $fillFromToolbar);
return $object;
} | php | public static function fromBlueprint(Blueprint $blueprint, $title, array $arguments = [], $type = self::TYPE_MAIN, $fillFromToolbar = 'section') {
if($title instanceof FieldSet) {
$title = $arguments['model']->getAttribute($title->getTitleFieldName());
} else {
if(!is_string($title)) {
throw new \InvalidArgumentException('$title must be either a string or an instance of \Oxygen\Core\Form\FieldSet');
}
}
$object = new static(
$title,
$arguments,
$type
);
// sets a prefix to all the routes in the toolbar
$object->getToolbar()->setPrefix($blueprint->getRouteName());
// fills the toolbar with buttons from the blueprint
$object->getToolbar()->fillFromBlueprint($blueprint, $fillFromToolbar);
return $object;
} | [
"public",
"static",
"function",
"fromBlueprint",
"(",
"Blueprint",
"$",
"blueprint",
",",
"$",
"title",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
",",
"$",
"type",
"=",
"self",
"::",
"TYPE_MAIN",
",",
"$",
"fillFromToolbar",
"=",
"'section'",
")",
"... | Constructs a Header from a Blueprint.
@param Blueprint $blueprint
@param FieldSet|string $title
@param array $arguments
@param integer $type
@param string $fillFromToolbar
@return Header | [
"Constructs",
"a",
"Header",
"from",
"a",
"Blueprint",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Header/Header.php#L303-L325 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/EmailAddress.php | Zend_Validate_EmailAddress.isValid | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
// Split email address up
if (!preg_match('/^(.+)@([^@]+)$/', $valueString, $matches)) {
$this->_error(self::INVALID);
return false;
}
$this->_localPart = $matches[1];
$this->_hostname = $matches[2];
// Match hostname part
$hostnameResult = $this->hostnameValidator->setTranslator($this->getTranslator())
->isValid($this->_hostname);
if (!$hostnameResult) {
$this->_error(self::INVALID_HOSTNAME);
// Get messages and errors from hostnameValidator
foreach ($this->hostnameValidator->getMessages() as $message) {
$this->_messages[] = $message;
}
foreach ($this->hostnameValidator->getErrors() as $error) {
$this->_errors[] = $error;
}
}
// MX check on hostname via dns_get_record()
if ($this->_validateMx) {
if ($this->validateMxSupported()) {
$result = dns_get_mx($this->_hostname, $mxHosts);
if (count($mxHosts) < 1) {
$hostnameResult = false;
$this->_error(self::INVALID_MX_RECORD);
}
} else {
/**
* MX checks are not supported by this system
*
* @see Zend_Validate_Exception
*/
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception('Internal error: MX checking not available on this system');
}
}
// First try to match the local part on the common dot-atom format
$localResult = false;
// Dot-atom characters are: 1*atext *("." 1*atext)
// atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
// "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
$atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d';
if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
$localResult = true;
} else {
// Try quoted string format
// Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
// qtext: Non white space controls, and the rest of the US-ASCII characters not
// including "\" or the quote character
$noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
$qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
$ws = '\x20\x09';
if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) {
$localResult = true;
} else {
$this->_error(self::DOT_ATOM);
$this->_error(self::QUOTED_STRING);
$this->_error(self::INVALID_LOCAL_PART);
}
}
// If both parts valid, return true
if ($localResult && $hostnameResult) {
return true;
} else {
return false;
}
} | php | public function isValid($value)
{
$valueString = (string) $value;
$this->_setValue($valueString);
// Split email address up
if (!preg_match('/^(.+)@([^@]+)$/', $valueString, $matches)) {
$this->_error(self::INVALID);
return false;
}
$this->_localPart = $matches[1];
$this->_hostname = $matches[2];
// Match hostname part
$hostnameResult = $this->hostnameValidator->setTranslator($this->getTranslator())
->isValid($this->_hostname);
if (!$hostnameResult) {
$this->_error(self::INVALID_HOSTNAME);
// Get messages and errors from hostnameValidator
foreach ($this->hostnameValidator->getMessages() as $message) {
$this->_messages[] = $message;
}
foreach ($this->hostnameValidator->getErrors() as $error) {
$this->_errors[] = $error;
}
}
// MX check on hostname via dns_get_record()
if ($this->_validateMx) {
if ($this->validateMxSupported()) {
$result = dns_get_mx($this->_hostname, $mxHosts);
if (count($mxHosts) < 1) {
$hostnameResult = false;
$this->_error(self::INVALID_MX_RECORD);
}
} else {
/**
* MX checks are not supported by this system
*
* @see Zend_Validate_Exception
*/
include_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception('Internal error: MX checking not available on this system');
}
}
// First try to match the local part on the common dot-atom format
$localResult = false;
// Dot-atom characters are: 1*atext *("." 1*atext)
// atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*",
// "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~"
$atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d';
if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {
$localResult = true;
} else {
// Try quoted string format
// Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE
// qtext: Non white space controls, and the rest of the US-ASCII characters not
// including "\" or the quote character
$noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f';
$qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e';
$ws = '\x20\x09';
if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) {
$localResult = true;
} else {
$this->_error(self::DOT_ATOM);
$this->_error(self::QUOTED_STRING);
$this->_error(self::INVALID_LOCAL_PART);
}
}
// If both parts valid, return true
if ($localResult && $hostnameResult) {
return true;
} else {
return false;
}
} | [
"public",
"function",
"isValid",
"(",
"$",
"value",
")",
"{",
"$",
"valueString",
"=",
"(",
"string",
")",
"$",
"value",
";",
"$",
"this",
"->",
"_setValue",
"(",
"$",
"valueString",
")",
";",
"// Split email address up",
"if",
"(",
"!",
"preg_match",
"(... | Defined by Zend_Validate_Interface
Returns true if and only if $value is a valid email address
according to RFC2822
@link http://www.ietf.org/rfc/rfc2822.txt RFC2822
@link http://www.columbia.edu/kermit/ascii.html US-ASCII characters
@param string $value
@return boolean | [
"Defined",
"by",
"Zend_Validate_Interface"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Validate/EmailAddress.php#L162-L244 |
flashwave/whois-php | src/Whois/Client.php | Client.lookup | public function lookup($target)
{
// Check if IP
if (filter_var($target, FILTER_VALIDATE_IP)) {
return $this->lookupIP($target);
}
// Check if domain
if ($this->verifyDomainName($target)) {
return $this->lookupDomain($target);
}
// Throw an error if both are false
throw new WhoisException('The target supplied does not appear to be a valid IP or domain name.');
} | php | public function lookup($target)
{
// Check if IP
if (filter_var($target, FILTER_VALIDATE_IP)) {
return $this->lookupIP($target);
}
// Check if domain
if ($this->verifyDomainName($target)) {
return $this->lookupDomain($target);
}
// Throw an error if both are false
throw new WhoisException('The target supplied does not appear to be a valid IP or domain name.');
} | [
"public",
"function",
"lookup",
"(",
"$",
"target",
")",
"{",
"// Check if IP",
"if",
"(",
"filter_var",
"(",
"$",
"target",
",",
"FILTER_VALIDATE_IP",
")",
")",
"{",
"return",
"$",
"this",
"->",
"lookupIP",
"(",
"$",
"target",
")",
";",
"}",
"// Check i... | Loop up a target (ip/domain) on whois
@param string $target The target domain/ip.
@throws WhoisException if the given target doesn't validate as an IP or domain.
@return Result The response from the whois server | [
"Loop",
"up",
"a",
"target",
"(",
"ip",
"/",
"domain",
")",
"on",
"whois"
] | train | https://github.com/flashwave/whois-php/blob/0eae1b4c863f8cfaee88bf3abdf2dd6d3d490bf8/src/Whois/Client.php#L39-L53 |
flashwave/whois-php | src/Whois/Client.php | Client.lookupIP | private function lookupIP($address)
{
// Create the responses storage array
$responses = [];
// Query every server in the IP list
foreach ($this->servers->ip as $server) {
// Check if we haven't queried this server yet
if (array_key_exists($server, $responses)) {
continue;
}
// Query the server
$responses[$server] = $this->query($address, $server);
}
// Create a result object
$result = new Result();
// Set target
$result->target = $address;
// Set the type
$result->type = 'ip';
// Set response count
$result->count = count($responses);
// Set responses
$result->responses = array_reverse($responses);
// Return the Result object
return $result;
} | php | private function lookupIP($address)
{
// Create the responses storage array
$responses = [];
// Query every server in the IP list
foreach ($this->servers->ip as $server) {
// Check if we haven't queried this server yet
if (array_key_exists($server, $responses)) {
continue;
}
// Query the server
$responses[$server] = $this->query($address, $server);
}
// Create a result object
$result = new Result();
// Set target
$result->target = $address;
// Set the type
$result->type = 'ip';
// Set response count
$result->count = count($responses);
// Set responses
$result->responses = array_reverse($responses);
// Return the Result object
return $result;
} | [
"private",
"function",
"lookupIP",
"(",
"$",
"address",
")",
"{",
"// Create the responses storage array",
"$",
"responses",
"=",
"[",
"]",
";",
"// Query every server in the IP list",
"foreach",
"(",
"$",
"this",
"->",
"servers",
"->",
"ip",
"as",
"$",
"server",
... | Whois an IP address.
@param string $address The IP address to query.
@return Result The whois results. | [
"Whois",
"an",
"IP",
"address",
"."
] | train | https://github.com/flashwave/whois-php/blob/0eae1b4c863f8cfaee88bf3abdf2dd6d3d490bf8/src/Whois/Client.php#L145-L178 |
flashwave/whois-php | src/Whois/Client.php | Client.query | private function query($target, $server, $port = 43, $timeout = 5)
{
// Create the socket
$sock = @fsockopen($server, $port, $errno, $errstr, $timeout);
// Check for errors
if (!$sock) {
// Throw an exception with the error string
throw new WhoisException($errstr);
}
// Write the target to the socket
fwrite($sock, $target . "\r\n");
// Create storage variable
$response = '';
// Await output
while ($line = fgets($sock)) {
$response .= $line;
}
// Close the socket
fclose($sock);
// Return the response
return $response;
} | php | private function query($target, $server, $port = 43, $timeout = 5)
{
// Create the socket
$sock = @fsockopen($server, $port, $errno, $errstr, $timeout);
// Check for errors
if (!$sock) {
// Throw an exception with the error string
throw new WhoisException($errstr);
}
// Write the target to the socket
fwrite($sock, $target . "\r\n");
// Create storage variable
$response = '';
// Await output
while ($line = fgets($sock)) {
$response .= $line;
}
// Close the socket
fclose($sock);
// Return the response
return $response;
} | [
"private",
"function",
"query",
"(",
"$",
"target",
",",
"$",
"server",
",",
"$",
"port",
"=",
"43",
",",
"$",
"timeout",
"=",
"5",
")",
"{",
"// Create the socket",
"$",
"sock",
"=",
"@",
"fsockopen",
"(",
"$",
"server",
",",
"$",
"port",
",",
"$"... | Query the whois server.
@param string $target The target IP/domain.
@param string $server The server to be queried.
@param int $port The port for the whois server.
@param int $timeout The timeout.
@throws WhoisException if the socket failed to open.
@return string The response from the whois server. | [
"Query",
"the",
"whois",
"server",
"."
] | train | https://github.com/flashwave/whois-php/blob/0eae1b4c863f8cfaee88bf3abdf2dd6d3d490bf8/src/Whois/Client.php#L206-L233 |
dave-redfern/laravel-doctrine-tenancy | src/Http/Middleware/EnsureTenantType.php | EnsureTenantType.handle | public function handle($request, Closure $next, $type)
{
if (!$this->typeResolver->hasType($this->tenant->getTenantCreator(), $type)) {
return redirect()->route('tenant.tenant_type_not_supported', ['type' => $type]);
}
return $next($request);
} | php | public function handle($request, Closure $next, $type)
{
if (!$this->typeResolver->hasType($this->tenant->getTenantCreator(), $type)) {
return redirect()->route('tenant.tenant_type_not_supported', ['type' => $type]);
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
",",
"$",
"type",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"typeResolver",
"->",
"hasType",
"(",
"$",
"this",
"->",
"tenant",
"->",
"getTenantCreator",
"(",
")",
",... | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string $type
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Http/Middleware/EnsureTenantType.php#L68-L75 |
oxygen-cms/core | src/Html/Toolbar/ActionToolbarItem.php | ActionToolbarItem.shouldRender | public function shouldRender(array $arguments = []) {
$callback = $this->shouldRenderCallback;
$result = $callback($this, $arguments);
return $result;
} | php | public function shouldRender(array $arguments = []) {
$callback = $this->shouldRenderCallback;
$result = $callback($this, $arguments);
return $result;
} | [
"public",
"function",
"shouldRender",
"(",
"array",
"$",
"arguments",
"=",
"[",
"]",
")",
"{",
"$",
"callback",
"=",
"$",
"this",
"->",
"shouldRenderCallback",
";",
"$",
"result",
"=",
"$",
"callback",
"(",
"$",
"this",
",",
"$",
"arguments",
")",
";",... | Determines if the button should be rendered.
@param array $arguments
@return boolean | [
"Determines",
"if",
"the",
"button",
"should",
"be",
"rendered",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/ActionToolbarItem.php#L71-L76 |
oxygen-cms/core | src/Html/Toolbar/ActionToolbarItem.php | ActionToolbarItem.shouldRenderBasic | public function shouldRenderBasic(array $arguments) {
if(isset($arguments['evenOnSamePage']) && $arguments['evenOnSamePage'] === true) {
return $this->hasPermissions();
} else {
return $this->hasPermissions() && !$this->linksToCurrentPage($arguments);
}
} | php | public function shouldRenderBasic(array $arguments) {
if(isset($arguments['evenOnSamePage']) && $arguments['evenOnSamePage'] === true) {
return $this->hasPermissions();
} else {
return $this->hasPermissions() && !$this->linksToCurrentPage($arguments);
}
} | [
"public",
"function",
"shouldRenderBasic",
"(",
"array",
"$",
"arguments",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"arguments",
"[",
"'evenOnSamePage'",
"]",
")",
"&&",
"$",
"arguments",
"[",
"'evenOnSamePage'",
"]",
"===",
"true",
")",
"{",
"return",
"$",... | Provides simple shouldRender check, that checks.
@return boolean | [
"Provides",
"simple",
"shouldRender",
"check",
"that",
"checks",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/ActionToolbarItem.php#L107-L113 |
oxygen-cms/core | src/Html/Toolbar/ActionToolbarItem.php | ActionToolbarItem.hasPermissions | public function hasPermissions() {
return $this->action->usesPermissions()
? Auth::user()->hasPermissions($this->action->getPermissions())
: true;
} | php | public function hasPermissions() {
return $this->action->usesPermissions()
? Auth::user()->hasPermissions($this->action->getPermissions())
: true;
} | [
"public",
"function",
"hasPermissions",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"action",
"->",
"usesPermissions",
"(",
")",
"?",
"Auth",
"::",
"user",
"(",
")",
"->",
"hasPermissions",
"(",
"$",
"this",
"->",
"action",
"->",
"getPermissions",
"(",
"... | Determines if the user has the required permissions for the toolbar item.
@return boolean | [
"Determines",
"if",
"the",
"user",
"has",
"the",
"required",
"permissions",
"for",
"the",
"toolbar",
"item",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/ActionToolbarItem.php#L120-L124 |
oxygen-cms/core | src/Html/Toolbar/ActionToolbarItem.php | ActionToolbarItem.linksToCurrentPage | public function linksToCurrentPage(array $arguments) {
return
URL::current() == URL::route($this->action->getName(), $this->action->getRouteParameters($arguments)) &&
Request::method() == $this->action->getMethod();
} | php | public function linksToCurrentPage(array $arguments) {
return
URL::current() == URL::route($this->action->getName(), $this->action->getRouteParameters($arguments)) &&
Request::method() == $this->action->getMethod();
} | [
"public",
"function",
"linksToCurrentPage",
"(",
"array",
"$",
"arguments",
")",
"{",
"return",
"URL",
"::",
"current",
"(",
")",
"==",
"URL",
"::",
"route",
"(",
"$",
"this",
"->",
"action",
"->",
"getName",
"(",
")",
",",
"$",
"this",
"->",
"action",... | Determines if the ActionToolbarItem will link to the current page.
@param array $arguments
@return boolean | [
"Determines",
"if",
"the",
"ActionToolbarItem",
"will",
"link",
"to",
"the",
"current",
"page",
"."
] | train | https://github.com/oxygen-cms/core/blob/8f8349c669771d9a7a719a7b120821e06cb5a20b/src/Html/Toolbar/ActionToolbarItem.php#L132-L136 |
crysalead/sql-dialect | src/Statement/PostgreSql/Select.php | Select.lock | public function lock($mode = 'update')
{
switch (strtolower($mode)) {
case 'update':
$lock = 'FOR UPDATE';
break;
case 'share':
$lock = 'FOR SHARE';
break;
case 'no key update':
$lock = 'FOR NO KEY UPDATE';
break;
case 'key share':
$lock = 'FOR KEY SHARE';
break;
case false:
$lock = false;
break;
default:
throw new SqlException("Invalid PostgreSQL lock mode `'{$mode}'`.");
break;
}
$this->_parts['lock'] = $lock;
return $this;
} | php | public function lock($mode = 'update')
{
switch (strtolower($mode)) {
case 'update':
$lock = 'FOR UPDATE';
break;
case 'share':
$lock = 'FOR SHARE';
break;
case 'no key update':
$lock = 'FOR NO KEY UPDATE';
break;
case 'key share':
$lock = 'FOR KEY SHARE';
break;
case false:
$lock = false;
break;
default:
throw new SqlException("Invalid PostgreSQL lock mode `'{$mode}'`.");
break;
}
$this->_parts['lock'] = $lock;
return $this;
} | [
"public",
"function",
"lock",
"(",
"$",
"mode",
"=",
"'update'",
")",
"{",
"switch",
"(",
"strtolower",
"(",
"$",
"mode",
")",
")",
"{",
"case",
"'update'",
":",
"$",
"lock",
"=",
"'FOR UPDATE'",
";",
"break",
";",
"case",
"'share'",
":",
"$",
"lock"... | Set the lock mode.
@param boolean $mode The lock mode.
@return object Returns `$this`. | [
"Set",
"the",
"lock",
"mode",
"."
] | train | https://github.com/crysalead/sql-dialect/blob/867a768086fb3eb539752671a0dd54b949fe9d79/src/Statement/PostgreSql/Select.php#L17-L41 |
awurth/SlimHelpers | Controller/SecurityTrait.php | SecurityTrait.accessDeniedException | protected function accessDeniedException(Request $request, Response $response, $message = 'Access denied.')
{
return new AccessDeniedException($request, $response, $message);
} | php | protected function accessDeniedException(Request $request, Response $response, $message = 'Access denied.')
{
return new AccessDeniedException($request, $response, $message);
} | [
"protected",
"function",
"accessDeniedException",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"$",
"message",
"=",
"'Access denied.'",
")",
"{",
"return",
"new",
"AccessDeniedException",
"(",
"$",
"request",
",",
"$",
"response",
",",
... | Creates a new AccessDeniedException.
@param Request $request
@param Response $response
@param string $message
@return AccessDeniedException | [
"Creates",
"a",
"new",
"AccessDeniedException",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/SecurityTrait.php#L21-L24 |
awurth/SlimHelpers | Controller/SecurityTrait.php | SecurityTrait.unauthorizedException | protected function unauthorizedException(Request $request, Response $response, $message = 'Unauthorized.')
{
return new UnauthorizedException($request, $response, $message);
} | php | protected function unauthorizedException(Request $request, Response $response, $message = 'Unauthorized.')
{
return new UnauthorizedException($request, $response, $message);
} | [
"protected",
"function",
"unauthorizedException",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"$",
"message",
"=",
"'Unauthorized.'",
")",
"{",
"return",
"new",
"UnauthorizedException",
"(",
"$",
"request",
",",
"$",
"response",
",",
... | Creates a new UnauthorizedException.
@param Request $request
@param Response $response
@param string $message
@return UnauthorizedException | [
"Creates",
"a",
"new",
"UnauthorizedException",
"."
] | train | https://github.com/awurth/SlimHelpers/blob/abaa0e16e285148f4e4c6b2fd0bb176bce6dac36/Controller/SecurityTrait.php#L35-L38 |
txj123/zilf | src/Zilf/System/Application.php | Application.updatePathInfo | public function updatePathInfo($pathinfo)
{
if (is_null($this->pathInfo)) {
$suffix = Zilf::$container->getShare('config')->get('app.url_html_suffix');
if (false === $suffix) {
// 禁止伪静态访问
$this->pathInfo = $pathinfo;
} elseif ($suffix) {
// 去除正常的URL后缀
$this->pathInfo = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo);
} else {
// 允许任何后缀访问
$this->pathInfo = preg_replace('/\.' . $this->ext($pathinfo) . '$/i', '', $pathinfo);
}
}
$this->pathInfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
return $this->pathInfo;
} | php | public function updatePathInfo($pathinfo)
{
if (is_null($this->pathInfo)) {
$suffix = Zilf::$container->getShare('config')->get('app.url_html_suffix');
if (false === $suffix) {
// 禁止伪静态访问
$this->pathInfo = $pathinfo;
} elseif ($suffix) {
// 去除正常的URL后缀
$this->pathInfo = preg_replace('/\.(' . ltrim($suffix, '.') . ')$/i', '', $pathinfo);
} else {
// 允许任何后缀访问
$this->pathInfo = preg_replace('/\.' . $this->ext($pathinfo) . '$/i', '', $pathinfo);
}
}
$this->pathInfo = empty($pathinfo) || '/' == $pathinfo ? '' : ltrim($pathinfo, '/');
return $this->pathInfo;
} | [
"public",
"function",
"updatePathInfo",
"(",
"$",
"pathinfo",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"pathInfo",
")",
")",
"{",
"$",
"suffix",
"=",
"Zilf",
"::",
"$",
"container",
"->",
"getShare",
"(",
"'config'",
")",
"->",
"get",
... | 获取当前请求URL的pathinfo信息(不含URL后缀)
@access public
@return string | [
"获取当前请求URL的pathinfo信息",
"(",
"不含URL后缀",
")"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Application.php#L260-L280 |
txj123/zilf | src/Zilf/System/Application.php | Application.run | public function run()
{
if ($this->is_route == true) {
if ($this->segments instanceof \Closure) {
echo call_user_func($this->segments);
die();
} else {
$class = $this->getBundleUrl();
}
} else {
$class = $this->getUnBundleUrl();
if (!class_exists($class)) {
$this->initDefaultRoute();
$class = $this->getBundleUrl();
}
}
if (!class_exists($class)) {
$message = sprintf('No route found for "%s %s"', Zilf::$container['request']->getMethod(), Zilf::$container['request']->getPathInfo());
if ($referer = Zilf::$container['request']->headers->get('referer')) {
$message .= sprintf(' (from "%s")', $referer);
}
throw new NotFoundHttpException($message);
}
unset($this->segments);
//将参数追加到GET里面
if (!empty($this->params)) {
foreach ($this->params as $key => $row) {
if (is_string($key)) {
$_GET[$key] = $row;
} else {
$_GET['zget' . $key] = $row;
}
}
Zilf::$container->getShare('request')->query->add($_GET);
}
$object = Zilf::$container->build($class, []);
if (method_exists($object, $this->action)) {
$response = call_user_func_array(array($object, $this->action), $this->params);
if (!$response instanceof Response) {
$msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
// the user may have forgotten to return something
if (null === $response) {
$msg .= ' Did you forget to add a return statement somewhere in your controller?';
}
throw new \LogicException($msg);
}
$response->send();
} else {
throw new \Exception('类: ' . $class . ' 调用的方法:' . $this->action . ' 不存在!');
}
} | php | public function run()
{
if ($this->is_route == true) {
if ($this->segments instanceof \Closure) {
echo call_user_func($this->segments);
die();
} else {
$class = $this->getBundleUrl();
}
} else {
$class = $this->getUnBundleUrl();
if (!class_exists($class)) {
$this->initDefaultRoute();
$class = $this->getBundleUrl();
}
}
if (!class_exists($class)) {
$message = sprintf('No route found for "%s %s"', Zilf::$container['request']->getMethod(), Zilf::$container['request']->getPathInfo());
if ($referer = Zilf::$container['request']->headers->get('referer')) {
$message .= sprintf(' (from "%s")', $referer);
}
throw new NotFoundHttpException($message);
}
unset($this->segments);
//将参数追加到GET里面
if (!empty($this->params)) {
foreach ($this->params as $key => $row) {
if (is_string($key)) {
$_GET[$key] = $row;
} else {
$_GET['zget' . $key] = $row;
}
}
Zilf::$container->getShare('request')->query->add($_GET);
}
$object = Zilf::$container->build($class, []);
if (method_exists($object, $this->action)) {
$response = call_user_func_array(array($object, $this->action), $this->params);
if (!$response instanceof Response) {
$msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
// the user may have forgotten to return something
if (null === $response) {
$msg .= ' Did you forget to add a return statement somewhere in your controller?';
}
throw new \LogicException($msg);
}
$response->send();
} else {
throw new \Exception('类: ' . $class . ' 调用的方法:' . $this->action . ' 不存在!');
}
} | [
"public",
"function",
"run",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"is_route",
"==",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"segments",
"instanceof",
"\\",
"Closure",
")",
"{",
"echo",
"call_user_func",
"(",
"$",
"this",
"->",
"segmen... | 执行类
@throws \Exception | [
"执行类"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/System/Application.php#L309-L370 |
omnilight/yii2-phonenumbers | PhoneNumber.php | PhoneNumber.format | public static function format($phone, $format = PhoneNumberFormat::E164, $region = 'RU')
{
return self::phoneUtil()->format(self::phoneUtil()->parse($phone, $region), $format);
} | php | public static function format($phone, $format = PhoneNumberFormat::E164, $region = 'RU')
{
return self::phoneUtil()->format(self::phoneUtil()->parse($phone, $region), $format);
} | [
"public",
"static",
"function",
"format",
"(",
"$",
"phone",
",",
"$",
"format",
"=",
"PhoneNumberFormat",
"::",
"E164",
",",
"$",
"region",
"=",
"'RU'",
")",
"{",
"return",
"self",
"::",
"phoneUtil",
"(",
")",
"->",
"format",
"(",
"self",
"::",
"phone... | Formats number to the desired format
@param $phone
@param int $format
@param string $region
@return string | [
"Formats",
"number",
"to",
"the",
"desired",
"format"
] | train | https://github.com/omnilight/yii2-phonenumbers/blob/01444ef39803b05321f75379198d88af9307f72f/PhoneNumber.php#L22-L25 |
omnilight/yii2-phonenumbers | PhoneNumber.php | PhoneNumber.validate | public static function validate($phone, $region = 'RU')
{
try {
return self::phoneUtil()->isValidNumberForRegion(self::phoneUtil()->parse($phone, $region), $region);
} catch (NumberParseException $e) {
return false;
}
} | php | public static function validate($phone, $region = 'RU')
{
try {
return self::phoneUtil()->isValidNumberForRegion(self::phoneUtil()->parse($phone, $region), $region);
} catch (NumberParseException $e) {
return false;
}
} | [
"public",
"static",
"function",
"validate",
"(",
"$",
"phone",
",",
"$",
"region",
"=",
"'RU'",
")",
"{",
"try",
"{",
"return",
"self",
"::",
"phoneUtil",
"(",
")",
"->",
"isValidNumberForRegion",
"(",
"self",
"::",
"phoneUtil",
"(",
")",
"->",
"parse",
... | Validates number
@param $phone
@param $region
@return bool | [
"Validates",
"number"
] | train | https://github.com/omnilight/yii2-phonenumbers/blob/01444ef39803b05321f75379198d88af9307f72f/PhoneNumber.php#L41-L48 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.setUri | public function setUri($uri)
{
if (is_string($uri)) {
$uri = Zend_Uri::factory($uri);
}
if (!$uri instanceof Zend_Uri_Http) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
}
// We have no ports, set the defaults
if (! $uri->getPort()) {
$uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
}
$this->uri = $uri;
return $this;
} | php | public function setUri($uri)
{
if (is_string($uri)) {
$uri = Zend_Uri::factory($uri);
}
if (!$uri instanceof Zend_Uri_Http) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Passed parameter is not a valid HTTP URI.');
}
// We have no ports, set the defaults
if (! $uri->getPort()) {
$uri->setPort(($uri->getScheme() == 'https' ? 443 : 80));
}
$this->uri = $uri;
return $this;
} | [
"public",
"function",
"setUri",
"(",
"$",
"uri",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"uri",
")",
")",
"{",
"$",
"uri",
"=",
"Zend_Uri",
"::",
"factory",
"(",
"$",
"uri",
")",
";",
"}",
"if",
"(",
"!",
"$",
"uri",
"instanceof",
"Zend_Uri_H... | Set the URI for the next request
@param Zend_Uri_Http|string $uri
@return Zend_Http_Client
@throws Zend_Http_Client_Exception | [
"Set",
"the",
"URI",
"for",
"the",
"next",
"request"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L250-L272 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.getUri | public function getUri($as_string = false)
{
if ($as_string && $this->uri instanceof Zend_Uri_Http) {
return $this->uri->__toString();
} else {
return $this->uri;
}
} | php | public function getUri($as_string = false)
{
if ($as_string && $this->uri instanceof Zend_Uri_Http) {
return $this->uri->__toString();
} else {
return $this->uri;
}
} | [
"public",
"function",
"getUri",
"(",
"$",
"as_string",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"as_string",
"&&",
"$",
"this",
"->",
"uri",
"instanceof",
"Zend_Uri_Http",
")",
"{",
"return",
"$",
"this",
"->",
"uri",
"->",
"__toString",
"(",
")",
";",
... | Get the URI for the next request
@param boolean $as_string If true, will return the URI as a string
@return Zend_Uri_Http|string | [
"Get",
"the",
"URI",
"for",
"the",
"next",
"request"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L280-L287 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.setMethod | public function setMethod($method = self::GET)
{
$regex = '/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/';
if (! preg_match($regex, $method)) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
}
if ($method == self::POST && $this->enctype === null) {
$this->setEncType(self::ENC_URLENCODED);
}
$this->method = $method;
return $this;
} | php | public function setMethod($method = self::GET)
{
$regex = '/^[^\x00-\x1f\x7f-\xff\(\)<>@,;:\\\\"\/\[\]\?={}\s]+$/';
if (! preg_match($regex, $method)) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("'{$method}' is not a valid HTTP request method.");
}
if ($method == self::POST && $this->enctype === null) {
$this->setEncType(self::ENC_URLENCODED);
}
$this->method = $method;
return $this;
} | [
"public",
"function",
"setMethod",
"(",
"$",
"method",
"=",
"self",
"::",
"GET",
")",
"{",
"$",
"regex",
"=",
"'/^[^\\x00-\\x1f\\x7f-\\xff\\(\\)<>@,;:\\\\\\\\\"\\/\\[\\]\\?={}\\s]+$/'",
";",
"if",
"(",
"!",
"preg_match",
"(",
"$",
"regex",
",",
"$",
"method",
")... | Set the next request's method
Validated the passed method and sets it. If we have files set for
POST requests, and the new method is not POST, the files are silently
dropped.
@param string $method
@return Zend_Http_Client
@throws Zend_Http_Client_Exception | [
"Set",
"the",
"next",
"request",
"s",
"method"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L324-L342 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.setParameterGet | public function setParameterGet($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $k => $v) {
$this->_setParameter('GET', $k, $v);
}
} else {
$this->_setParameter('GET', $name, $value);
}
return $this;
} | php | public function setParameterGet($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $k => $v) {
$this->_setParameter('GET', $k, $v);
}
} else {
$this->_setParameter('GET', $name, $value);
}
return $this;
} | [
"public",
"function",
"setParameterGet",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"foreach",
"(",
"$",
"name",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"this",
"->... | Set a GET parameter for the request. Wrapper around _setParameter
@param string|array $name
@param string $value
@return Zend_Http_Client | [
"Set",
"a",
"GET",
"parameter",
"for",
"the",
"request",
".",
"Wrapper",
"around",
"_setParameter"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L433-L444 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.setRawData | public function setRawData($data, $enctype = null)
{
$this->raw_post_data = $data;
$this->setEncType($enctype);
return $this;
} | php | public function setRawData($data, $enctype = null)
{
$this->raw_post_data = $data;
$this->setEncType($enctype);
return $this;
} | [
"public",
"function",
"setRawData",
"(",
"$",
"data",
",",
"$",
"enctype",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"raw_post_data",
"=",
"$",
"data",
";",
"$",
"this",
"->",
"setEncType",
"(",
"$",
"enctype",
")",
";",
"return",
"$",
"this",
";",
... | Set the raw (already encoded) POST data.
This function is here for two reasons:
1. For advanced user who would like to set their own data, already encoded
2. For backwards compatibilty: If someone uses the old post($data) method.
this method will be used to set the encoded data.
@param string $data
@param string $enctype
@return Zend_Http_Client | [
"Set",
"the",
"raw",
"(",
"already",
"encoded",
")",
"POST",
"data",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L728-L734 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.resetParameters | public function resetParameters()
{
// Reset parameter data
$this->paramsGet = array();
$this->paramsPost = array();
$this->files = array();
$this->raw_post_data = null;
// Clear outdated headers
if (isset($this->headers['content-type'])) { unset($this->headers['content-type']);
}
if (isset($this->headers['content-length'])) { unset($this->headers['content-length']);
}
return $this;
} | php | public function resetParameters()
{
// Reset parameter data
$this->paramsGet = array();
$this->paramsPost = array();
$this->files = array();
$this->raw_post_data = null;
// Clear outdated headers
if (isset($this->headers['content-type'])) { unset($this->headers['content-type']);
}
if (isset($this->headers['content-length'])) { unset($this->headers['content-length']);
}
return $this;
} | [
"public",
"function",
"resetParameters",
"(",
")",
"{",
"// Reset parameter data",
"$",
"this",
"->",
"paramsGet",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"paramsPost",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"files",
"=",
"array",
"(",
... | Clear all GET and POST parameters
Should be used to reset the request parameters if the client is
used for several concurrent requests.
@return Zend_Http_Client | [
"Clear",
"all",
"GET",
"and",
"POST",
"parameters"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L744-L759 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.setAdapter | public function setAdapter($adapter)
{
if (is_string($adapter)) {
try {
Zend_Loader::loadClass($adapter);
} catch (Zend_Exception $e) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
}
$adapter = new $adapter;
}
if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
}
$this->adapter = $adapter;
$config = $this->config;
unset($config['adapter']);
$this->adapter->setConfig($config);
} | php | public function setAdapter($adapter)
{
if (is_string($adapter)) {
try {
Zend_Loader::loadClass($adapter);
} catch (Zend_Exception $e) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("Unable to load adapter '$adapter': {$e->getMessage()}");
}
$adapter = new $adapter;
}
if (! $adapter instanceof Zend_Http_Client_Adapter_Interface) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Passed adapter is not a HTTP connection adapter');
}
$this->adapter = $adapter;
$config = $this->config;
unset($config['adapter']);
$this->adapter->setConfig($config);
} | [
"public",
"function",
"setAdapter",
"(",
"$",
"adapter",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"adapter",
")",
")",
"{",
"try",
"{",
"Zend_Loader",
"::",
"loadClass",
"(",
"$",
"adapter",
")",
";",
"}",
"catch",
"(",
"Zend_Exception",
"$",
"e",
... | Load the connection adapter
While this method is not called more than one for a client, it is
seperated from ->request() to preserve logic and readability
@param Zend_Http_Client_Adapter_Interface|string $adapter
@return null
@throws Zend_Http_Client_Exception | [
"Load",
"the",
"connection",
"adapter"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L794-L822 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.request | public function request($method = null)
{
if (! $this->uri instanceof Zend_Uri_Http) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
}
if ($method) { $this->setMethod($method);
}
$this->redirectCounter = 0;
$response = null;
// Make sure the adapter is loaded
if ($this->adapter == null) { $this->setAdapter($this->config['adapter']);
}
// Send the first request. If redirected, continue.
do {
// Clone the URI and add the additional GET parameters to it
$uri = clone $this->uri;
if (! empty($this->paramsGet)) {
$query = $uri->getQuery();
if (! empty($query)) { $query .= '&';
}
$query .= http_build_query($this->paramsGet, null, '&');
$uri->setQuery($query);
}
$body = $this->_prepareBody();
$headers = $this->_prepareHeaders();
// Open the connection, send the request and read the response
$this->adapter->connect(
$uri->getHost(), $uri->getPort(),
($uri->getScheme() == 'https' ? true : false)
);
$this->last_request = $this->adapter->write(
$this->method,
$uri, $this->config['httpversion'], $headers, $body
);
$response = $this->adapter->read();
if (! $response) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
}
$response = Zend_Http_Response::fromString($response);
if ($this->config['storeresponse']) { $this->last_response = $response;
}
// Load cookies into cookie jar
if (isset($this->cookiejar)) { $this->cookiejar->addCookiesFromResponse($response, $uri);
}
// If we got redirected, look for the Location header
if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
// Check whether we send the exact same request again, or drop the parameters
// and send a GET request
if ($response->getStatus() == 303
|| ((! $this->config['strictredirects']) && ($response->getStatus() == 302
|| $response->getStatus() == 301))
) {
$this->resetParameters();
$this->setMethod(self::GET);
}
// If we got a well formed absolute URI
if (Zend_Uri_Http::check($location)) {
$this->setHeaders('host', null);
$this->setUri($location);
} else {
// Split into path and query and set the query
if (strpos($location, '?') !== false) {
list($location, $query) = explode('?', $location, 2);
} else {
$query = '';
}
$this->uri->setQuery($query);
// Else, if we got just an absolute path, set it
if(strpos($location, '/') === 0) {
$this->uri->setPath($location);
// Else, assume we have a relative path
} else {
// Get the current path directory, removing any trailing slashes
$path = $this->uri->getPath();
$path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
$this->uri->setPath($path . '/' . $location);
}
}
++$this->redirectCounter;
} else {
// If we didn't get any location, stop redirecting
break;
}
} while ($this->redirectCounter < $this->config['maxredirects']);
return $response;
} | php | public function request($method = null)
{
if (! $this->uri instanceof Zend_Uri_Http) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');
}
if ($method) { $this->setMethod($method);
}
$this->redirectCounter = 0;
$response = null;
// Make sure the adapter is loaded
if ($this->adapter == null) { $this->setAdapter($this->config['adapter']);
}
// Send the first request. If redirected, continue.
do {
// Clone the URI and add the additional GET parameters to it
$uri = clone $this->uri;
if (! empty($this->paramsGet)) {
$query = $uri->getQuery();
if (! empty($query)) { $query .= '&';
}
$query .= http_build_query($this->paramsGet, null, '&');
$uri->setQuery($query);
}
$body = $this->_prepareBody();
$headers = $this->_prepareHeaders();
// Open the connection, send the request and read the response
$this->adapter->connect(
$uri->getHost(), $uri->getPort(),
($uri->getScheme() == 'https' ? true : false)
);
$this->last_request = $this->adapter->write(
$this->method,
$uri, $this->config['httpversion'], $headers, $body
);
$response = $this->adapter->read();
if (! $response) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('Unable to read response, or response is empty');
}
$response = Zend_Http_Response::fromString($response);
if ($this->config['storeresponse']) { $this->last_response = $response;
}
// Load cookies into cookie jar
if (isset($this->cookiejar)) { $this->cookiejar->addCookiesFromResponse($response, $uri);
}
// If we got redirected, look for the Location header
if ($response->isRedirect() && ($location = $response->getHeader('location'))) {
// Check whether we send the exact same request again, or drop the parameters
// and send a GET request
if ($response->getStatus() == 303
|| ((! $this->config['strictredirects']) && ($response->getStatus() == 302
|| $response->getStatus() == 301))
) {
$this->resetParameters();
$this->setMethod(self::GET);
}
// If we got a well formed absolute URI
if (Zend_Uri_Http::check($location)) {
$this->setHeaders('host', null);
$this->setUri($location);
} else {
// Split into path and query and set the query
if (strpos($location, '?') !== false) {
list($location, $query) = explode('?', $location, 2);
} else {
$query = '';
}
$this->uri->setQuery($query);
// Else, if we got just an absolute path, set it
if(strpos($location, '/') === 0) {
$this->uri->setPath($location);
// Else, assume we have a relative path
} else {
// Get the current path directory, removing any trailing slashes
$path = $this->uri->getPath();
$path = rtrim(substr($path, 0, strrpos($path, '/')), "/");
$this->uri->setPath($path . '/' . $location);
}
}
++$this->redirectCounter;
} else {
// If we didn't get any location, stop redirecting
break;
}
} while ($this->redirectCounter < $this->config['maxredirects']);
return $response;
} | [
"public",
"function",
"request",
"(",
"$",
"method",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"uri",
"instanceof",
"Zend_Uri_Http",
")",
"{",
"/**\n * @see Zend_Http_Client_Exception \n*/",
"include_once",
"'Zend/Http/Client/Exception.php'",
";",
"t... | Send the HTTP request and return an HTTP response object
@param string $method
@return Zend_Http_Response
@throws Zend_Http_Client_Exception | [
"Send",
"the",
"HTTP",
"request",
"and",
"return",
"an",
"HTTP",
"response",
"object"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L831-L945 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client._getParametersRecursive | protected function _getParametersRecursive($parray, $urlencode = false)
{
if (! is_array($parray)) { return $parray;
}
$parameters = array();
foreach ($parray as $name => $value) {
if ($urlencode) { $name = urlencode($name);
}
// If $value is an array, iterate over it
if (is_array($value)) {
$name .= ($urlencode ? '%5B%5D' : '[]');
foreach ($value as $subval) {
if ($urlencode) { $subval = urlencode($subval);
}
$parameters[] = array($name, $subval);
}
} else {
if ($urlencode) { $value = urlencode($value);
}
$parameters[] = array($name, $value);
}
}
return $parameters;
} | php | protected function _getParametersRecursive($parray, $urlencode = false)
{
if (! is_array($parray)) { return $parray;
}
$parameters = array();
foreach ($parray as $name => $value) {
if ($urlencode) { $name = urlencode($name);
}
// If $value is an array, iterate over it
if (is_array($value)) {
$name .= ($urlencode ? '%5B%5D' : '[]');
foreach ($value as $subval) {
if ($urlencode) { $subval = urlencode($subval);
}
$parameters[] = array($name, $subval);
}
} else {
if ($urlencode) { $value = urlencode($value);
}
$parameters[] = array($name, $value);
}
}
return $parameters;
} | [
"protected",
"function",
"_getParametersRecursive",
"(",
"$",
"parray",
",",
"$",
"urlencode",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"parray",
")",
")",
"{",
"return",
"$",
"parray",
";",
"}",
"$",
"parameters",
"=",
"array",
"(... | Helper method that gets a possibly multi-level parameters array (get or
post) and flattens it.
The method returns an array of (key, value) pairs (because keys are not
necessarily unique. If one of the parameters in as array, it will also
add a [] suffix to the key.
@param array $parray The parameters array
@param bool $urlencode Whether to urlencode the name and value
@return array | [
"Helper",
"method",
"that",
"gets",
"a",
"possibly",
"multi",
"-",
"level",
"parameters",
"array",
"(",
"get",
"or",
"post",
")",
"and",
"flattens",
"it",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L1116-L1142 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client._detectFileMimeType | protected function _detectFileMimeType($file)
{
$type = null;
// First try with fileinfo functions
if (function_exists('finfo_open')) {
if (self::$_fileInfoDb === null) {
self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
}
if (self::$_fileInfoDb) {
$type = finfo_file(self::$_fileInfoDb, $file);
}
} elseif (function_exists('mime_content_type')) {
$type = mime_content_type($file);
}
// Fallback to the default application/octet-stream
if (! $type) {
$type = 'application/octet-stream';
}
return $type;
} | php | protected function _detectFileMimeType($file)
{
$type = null;
// First try with fileinfo functions
if (function_exists('finfo_open')) {
if (self::$_fileInfoDb === null) {
self::$_fileInfoDb = @finfo_open(FILEINFO_MIME);
}
if (self::$_fileInfoDb) {
$type = finfo_file(self::$_fileInfoDb, $file);
}
} elseif (function_exists('mime_content_type')) {
$type = mime_content_type($file);
}
// Fallback to the default application/octet-stream
if (! $type) {
$type = 'application/octet-stream';
}
return $type;
} | [
"protected",
"function",
"_detectFileMimeType",
"(",
"$",
"file",
")",
"{",
"$",
"type",
"=",
"null",
";",
"// First try with fileinfo functions",
"if",
"(",
"function_exists",
"(",
"'finfo_open'",
")",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"_fileInfoDb",
"=... | Attempt to detect the MIME type of a file using available extensions
This method will try to detect the MIME type of a file. If the fileinfo
extension is available, it will be used. If not, the mime_magic
extension which is deprected but is still available in many PHP setups
will be tried.
If neither extension is available, the default application/octet-stream
MIME type will be returned
@param string $file File path
@return string MIME type | [
"Attempt",
"to",
"detect",
"the",
"MIME",
"type",
"of",
"a",
"file",
"using",
"available",
"extensions"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L1158-L1182 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.encodeFormData | public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array())
{
$ret = "--{$boundary}\r\n" .
'Content-disposition: form-data; name="' . $name .'"';
if ($filename) { $ret .= '; filename="' . $filename . '"';
}
$ret .= "\r\n";
foreach ($headers as $hname => $hvalue) {
$ret .= "{$hname}: {$hvalue}\r\n";
}
$ret .= "\r\n";
$ret .= "{$value}\r\n";
return $ret;
} | php | public static function encodeFormData($boundary, $name, $value, $filename = null, $headers = array())
{
$ret = "--{$boundary}\r\n" .
'Content-disposition: form-data; name="' . $name .'"';
if ($filename) { $ret .= '; filename="' . $filename . '"';
}
$ret .= "\r\n";
foreach ($headers as $hname => $hvalue) {
$ret .= "{$hname}: {$hvalue}\r\n";
}
$ret .= "\r\n";
$ret .= "{$value}\r\n";
return $ret;
} | [
"public",
"static",
"function",
"encodeFormData",
"(",
"$",
"boundary",
",",
"$",
"name",
",",
"$",
"value",
",",
"$",
"filename",
"=",
"null",
",",
"$",
"headers",
"=",
"array",
"(",
")",
")",
"{",
"$",
"ret",
"=",
"\"--{$boundary}\\r\\n\"",
".",
"'Co... | Encode data to a multipart/form-data part suitable for a POST request.
@param string $boundary
@param string $name
@param mixed $value
@param string $filename
@param array $headers Associative array of optional headers @example ("Content-transfer-encoding" => "binary")
@return string | [
"Encode",
"data",
"to",
"a",
"multipart",
"/",
"form",
"-",
"data",
"part",
"suitable",
"for",
"a",
"POST",
"request",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L1194-L1211 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php | Zend_Http_Client.encodeAuthHeader | public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
{
$authHeader = null;
switch ($type) {
case self::AUTH_BASIC:
// In basic authentication, the user name cannot contain ":"
if (strpos($user, ':') !== false) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
}
$authHeader = 'Basic ' . base64_encode($user . ':' . $password);
break;
//case self::AUTH_DIGEST:
/**
* @todo Implement digest authentication
*/
// break;
default:
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
}
return $authHeader;
} | php | public static function encodeAuthHeader($user, $password, $type = self::AUTH_BASIC)
{
$authHeader = null;
switch ($type) {
case self::AUTH_BASIC:
// In basic authentication, the user name cannot contain ":"
if (strpos($user, ':') !== false) {
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("The user name cannot contain ':' in 'Basic' HTTP authentication");
}
$authHeader = 'Basic ' . base64_encode($user . ':' . $password);
break;
//case self::AUTH_DIGEST:
/**
* @todo Implement digest authentication
*/
// break;
default:
/**
* @see Zend_Http_Client_Exception
*/
include_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception("Not a supported HTTP authentication type: '$type'");
}
return $authHeader;
} | [
"public",
"static",
"function",
"encodeAuthHeader",
"(",
"$",
"user",
",",
"$",
"password",
",",
"$",
"type",
"=",
"self",
"::",
"AUTH_BASIC",
")",
"{",
"$",
"authHeader",
"=",
"null",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"self",
"::",
... | Create a HTTP authentication "Authorization:" header according to the
specified user, password and authentication method.
@see http://www.faqs.org/rfcs/rfc2617.html
@param string $user
@param string $password
@param string $type
@return string
@throws Zend_Http_Client_Exception | [
"Create",
"a",
"HTTP",
"authentication",
"Authorization",
":",
"header",
"according",
"to",
"the",
"specified",
"user",
"password",
"and",
"authentication",
"method",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client.php#L1224-L1257 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.getLines | public function getLines($limit = null, $offset = 0, $filter = null)
{
$lines = clone $this->lines;
if ($filter !== null) {
$logger = isset($filter['logger']) ? $filter['logger'] : null;
$minLevel = isset($filter['level']) ? $filter['level'] : 0;
$text = (isset($filter['text']) && $filter['text'] != '') ? $filter['text'] : null;
$searchMeta = isset($filter['search_meta']) ? ($filter['search_meta']) : true;
foreach ($lines as $line) {
if (
!static::logLineHasLogger($logger, $line)
|| !static::logLineHasMinLevel($minLevel, $line)
|| !static::logLineHasText($text, $line, $searchMeta)
) {
$lines->removeElement($line);
}
}
}
if (null !== $limit) {
return array_values($lines->slice($offset, $limit));
}
return array_values($lines->toArray());
} | php | public function getLines($limit = null, $offset = 0, $filter = null)
{
$lines = clone $this->lines;
if ($filter !== null) {
$logger = isset($filter['logger']) ? $filter['logger'] : null;
$minLevel = isset($filter['level']) ? $filter['level'] : 0;
$text = (isset($filter['text']) && $filter['text'] != '') ? $filter['text'] : null;
$searchMeta = isset($filter['search_meta']) ? ($filter['search_meta']) : true;
foreach ($lines as $line) {
if (
!static::logLineHasLogger($logger, $line)
|| !static::logLineHasMinLevel($minLevel, $line)
|| !static::logLineHasText($text, $line, $searchMeta)
) {
$lines->removeElement($line);
}
}
}
if (null !== $limit) {
return array_values($lines->slice($offset, $limit));
}
return array_values($lines->toArray());
} | [
"public",
"function",
"getLines",
"(",
"$",
"limit",
"=",
"null",
",",
"$",
"offset",
"=",
"0",
",",
"$",
"filter",
"=",
"null",
")",
"{",
"$",
"lines",
"=",
"clone",
"$",
"this",
"->",
"lines",
";",
"if",
"(",
"$",
"filter",
"!==",
"null",
")",
... | Returns log lines, either all or paginated and or filtered.
@param int|null $limit Defines how many lines are returned.
@param int $offset Defines the offset for returning lines. Offset 0 starts at the first line.
@param array|null $filter Filter the log lines before returning and applying pagination. Can contain keys logger,
level, text and searchMeta (should context and extra fields also be searched)
@return array | [
"Returns",
"log",
"lines",
"either",
"all",
"or",
"paginated",
"and",
"or",
"filtered",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L95-L119 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.logLineHasLogger | private static function logLineHasLogger($logger, $line)
{
if ($logger === null) {
return true;
}
return array_key_exists('logger', $line) && $line['logger'] == $logger;
} | php | private static function logLineHasLogger($logger, $line)
{
if ($logger === null) {
return true;
}
return array_key_exists('logger', $line) && $line['logger'] == $logger;
} | [
"private",
"static",
"function",
"logLineHasLogger",
"(",
"$",
"logger",
",",
"$",
"line",
")",
"{",
"if",
"(",
"$",
"logger",
"===",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"array_key_exists",
"(",
"'logger'",
",",
"$",
"line",
")",
"&... | Internal filtering method for determining whether a log line belongs to a specific logger.
@param string $logger
@param array $line
@return bool | [
"Internal",
"filtering",
"method",
"for",
"determining",
"whether",
"a",
"log",
"line",
"belongs",
"to",
"a",
"specific",
"logger",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L129-L136 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.logLineHasMinLevel | private static function logLineHasMinLevel($minLevel, $line)
{
if ($minLevel == 0) {
return true;
}
return array_key_exists('level', $line) && static::getLevelNumber($line['level']) >= $minLevel;
} | php | private static function logLineHasMinLevel($minLevel, $line)
{
if ($minLevel == 0) {
return true;
}
return array_key_exists('level', $line) && static::getLevelNumber($line['level']) >= $minLevel;
} | [
"private",
"static",
"function",
"logLineHasMinLevel",
"(",
"$",
"minLevel",
",",
"$",
"line",
")",
"{",
"if",
"(",
"$",
"minLevel",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"return",
"array_key_exists",
"(",
"'level'",
",",
"$",
"line",
")",
"... | Internal filtering method for determining whether a log line has a specific minimal log level.
@param int $minLevel
@param array $line
@return bool | [
"Internal",
"filtering",
"method",
"for",
"determining",
"whether",
"a",
"log",
"line",
"has",
"a",
"specific",
"minimal",
"log",
"level",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L146-L153 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.logLineHasText | private static function logLineHasText($keyword, $line, $searchMeta = true)
{
if ($keyword === null) {
return true;
}
if (array_key_exists('message', $line) && strpos(strtolower($line['message']), strtolower($keyword)) !== false) {
return true;
}
if (array_key_exists('date', $line) && strpos(strtolower($line['date']), strtolower($keyword)) !== false) {
return true;
}
if ($searchMeta) {
if (array_key_exists('context', $line)) {
$context = $line['context'];
if (array_key_exists(strtolower($keyword), $context)) {
return true;
}
foreach ($context as $content) {
if (strpos(strtolower($content), strtolower($keyword)) !== false) {
return true;
}
}
}
if (array_key_exists('extra', $line)) {
$extra = $line['extra'];
if (array_key_exists($keyword, $extra)) {
return true;
}
foreach ($extra as $content) {
if (strpos(strtolower($content), strtolower($keyword)) !== false) {
return true;
}
}
}
}
return false;
} | php | private static function logLineHasText($keyword, $line, $searchMeta = true)
{
if ($keyword === null) {
return true;
}
if (array_key_exists('message', $line) && strpos(strtolower($line['message']), strtolower($keyword)) !== false) {
return true;
}
if (array_key_exists('date', $line) && strpos(strtolower($line['date']), strtolower($keyword)) !== false) {
return true;
}
if ($searchMeta) {
if (array_key_exists('context', $line)) {
$context = $line['context'];
if (array_key_exists(strtolower($keyword), $context)) {
return true;
}
foreach ($context as $content) {
if (strpos(strtolower($content), strtolower($keyword)) !== false) {
return true;
}
}
}
if (array_key_exists('extra', $line)) {
$extra = $line['extra'];
if (array_key_exists($keyword, $extra)) {
return true;
}
foreach ($extra as $content) {
if (strpos(strtolower($content), strtolower($keyword)) !== false) {
return true;
}
}
}
}
return false;
} | [
"private",
"static",
"function",
"logLineHasText",
"(",
"$",
"keyword",
",",
"$",
"line",
",",
"$",
"searchMeta",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"keyword",
"===",
"null",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"array_key_exists",
"(",... | Internal filtering method for determining whether a log line contains a specific string.
@param string $keyword
@param array $line
@param bool $searchMeta
@return bool | [
"Internal",
"filtering",
"method",
"for",
"determining",
"whether",
"a",
"log",
"line",
"contains",
"a",
"specific",
"string",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L164-L201 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.countLines | public function countLines($filter = null)
{
if ($filter !== null) {
return count($this->getLines(null, 0, $filter));
}
return $this->lines->count();
} | php | public function countLines($filter = null)
{
if ($filter !== null) {
return count($this->getLines(null, 0, $filter));
}
return $this->lines->count();
} | [
"public",
"function",
"countLines",
"(",
"$",
"filter",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"filter",
"!==",
"null",
")",
"{",
"return",
"count",
"(",
"$",
"this",
"->",
"getLines",
"(",
"null",
",",
"0",
",",
"$",
"filter",
")",
")",
";",
"}"... | Returns the number of lines in the log file.
@param array|null $filter
@return int | [
"Returns",
"the",
"number",
"of",
"lines",
"in",
"the",
"log",
"file",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L218-L225 |
Syonix/log-viewer-lib | lib/LogFile.php | LogFile.getLevelNumber | public static function getLevelNumber($level)
{
$levels = Logger::getLevels();
if (!isset($levels[$level])) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', $levels));
}
return $levels[$level];
} | php | public static function getLevelNumber($level)
{
$levels = Logger::getLevels();
if (!isset($levels[$level])) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', $levels));
}
return $levels[$level];
} | [
"public",
"static",
"function",
"getLevelNumber",
"(",
"$",
"level",
")",
"{",
"$",
"levels",
"=",
"Logger",
"::",
"getLevels",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"levels",
"[",
"$",
"level",
"]",
")",
")",
"{",
"throw",
"new",
"Inva... | Returns the associated number for a log level string.
@param string $level
@return int | [
"Returns",
"the",
"associated",
"number",
"for",
"a",
"log",
"level",
"string",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/LogFile.php#L264-L273 |
damonjones/Vebra-PHP-API-Wrapper | lib/YDD/Vebra/TokenStorage/File.php | File.load | protected function load()
{
if (false !== ($token = @file_get_contents($this->getFilename()))) {
$this->token = trim($token);
} else {
throw new \Exception(sprintf('Token could not be loaded from "%s"', $this->getFilename()));
}
} | php | protected function load()
{
if (false !== ($token = @file_get_contents($this->getFilename()))) {
$this->token = trim($token);
} else {
throw new \Exception(sprintf('Token could not be loaded from "%s"', $this->getFilename()));
}
} | [
"protected",
"function",
"load",
"(",
")",
"{",
"if",
"(",
"false",
"!==",
"(",
"$",
"token",
"=",
"@",
"file_get_contents",
"(",
"$",
"this",
"->",
"getFilename",
"(",
")",
")",
")",
")",
"{",
"$",
"this",
"->",
"token",
"=",
"trim",
"(",
"$",
"... | Load the token from a file | [
"Load",
"the",
"token",
"from",
"a",
"file"
] | train | https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/TokenStorage/File.php#L65-L72 |
damonjones/Vebra-PHP-API-Wrapper | lib/YDD/Vebra/TokenStorage/File.php | File.save | protected function save()
{
if (false === ($result = @file_put_contents($this->getFilename(), $this->token))) {
throw new \Exception(sprintf('Token could not be saved to "%s"', $this->getFilename()));
}
} | php | protected function save()
{
if (false === ($result = @file_put_contents($this->getFilename(), $this->token))) {
throw new \Exception(sprintf('Token could not be saved to "%s"', $this->getFilename()));
}
} | [
"protected",
"function",
"save",
"(",
")",
"{",
"if",
"(",
"false",
"===",
"(",
"$",
"result",
"=",
"@",
"file_put_contents",
"(",
"$",
"this",
"->",
"getFilename",
"(",
")",
",",
"$",
"this",
"->",
"token",
")",
")",
")",
"{",
"throw",
"new",
"\\"... | Save the token to a file | [
"Save",
"the",
"token",
"to",
"a",
"file"
] | train | https://github.com/damonjones/Vebra-PHP-API-Wrapper/blob/9de0fb5181a6e4b90700027ffaa6b2e658d279c2/lib/YDD/Vebra/TokenStorage/File.php#L77-L82 |
BusinessMastery/omnipay-mobilpay | src/BusinessMastery/Mobilpay/Message/PurchaseRequest.php | PurchaseRequest.getData | public function getData()
{
$this->validate('amount', 'currency', 'orderId', 'confirmUrl', 'returnUrl', 'details');
$envKey = $envData = null;
$publicKey = $this->getParameter('publicKey');
if (! $publicKey) {
throw new MissingKeyException("Missing public key path parameter");
}
$request = new Card();
$request->signature = $this->getMerchantId();
$request->orderId = $this->getParameter('orderId');
$request->confirmUrl = $this->getParameter('confirmUrl');
$request->returnUrl = $this->getParameter('returnUrl');
$request->params = $this->getParameter('params') ?: [];
if ($this->getParameter('recurrence')) {
$request->recurrence = new Recurrence();
$request->recurrence->payments_no = $this->getParameter('paymentNo');
$request->recurrence->interval_day = $this->getParameter('intervalDay');
}
$request->invoice = new Invoice();
$request->invoice->currency = $this->getParameter('currency');
$request->invoice->amount = $this->getParameter('amount');
$request->invoice->details = $this->getParameter('details');
if ($getBillingAddress = $this->getBillingAddress()) {
$request->invoice->setBillingAddress($this->makeBillingAddress($getBillingAddress));
}
$request->encrypt($this->getParameter('publicKey'));
$data = [
'env_key' => $request->getEnvKey(),
'data' => $request->getEncData()
];
return $data;
} | php | public function getData()
{
$this->validate('amount', 'currency', 'orderId', 'confirmUrl', 'returnUrl', 'details');
$envKey = $envData = null;
$publicKey = $this->getParameter('publicKey');
if (! $publicKey) {
throw new MissingKeyException("Missing public key path parameter");
}
$request = new Card();
$request->signature = $this->getMerchantId();
$request->orderId = $this->getParameter('orderId');
$request->confirmUrl = $this->getParameter('confirmUrl');
$request->returnUrl = $this->getParameter('returnUrl');
$request->params = $this->getParameter('params') ?: [];
if ($this->getParameter('recurrence')) {
$request->recurrence = new Recurrence();
$request->recurrence->payments_no = $this->getParameter('paymentNo');
$request->recurrence->interval_day = $this->getParameter('intervalDay');
}
$request->invoice = new Invoice();
$request->invoice->currency = $this->getParameter('currency');
$request->invoice->amount = $this->getParameter('amount');
$request->invoice->details = $this->getParameter('details');
if ($getBillingAddress = $this->getBillingAddress()) {
$request->invoice->setBillingAddress($this->makeBillingAddress($getBillingAddress));
}
$request->encrypt($this->getParameter('publicKey'));
$data = [
'env_key' => $request->getEnvKey(),
'data' => $request->getEncData()
];
return $data;
} | [
"public",
"function",
"getData",
"(",
")",
"{",
"$",
"this",
"->",
"validate",
"(",
"'amount'",
",",
"'currency'",
",",
"'orderId'",
",",
"'confirmUrl'",
",",
"'returnUrl'",
",",
"'details'",
")",
";",
"$",
"envKey",
"=",
"$",
"envData",
"=",
"null",
";"... | Build encrypted request data
@return array
@throws MissingKeyException
@throws \Exception
@throws \Omnipay\Common\Exception\InvalidRequestException | [
"Build",
"encrypted",
"request",
"data"
] | train | https://github.com/BusinessMastery/omnipay-mobilpay/blob/e9013933e8d12bd69c7def4c88b293f9561ab6e1/src/BusinessMastery/Mobilpay/Message/PurchaseRequest.php#L224-L265 |
BusinessMastery/omnipay-mobilpay | src/BusinessMastery/Mobilpay/Message/PurchaseRequest.php | PurchaseRequest.makeBillingAddress | public function makeBillingAddress(array $parameters = [])
{
$address = new Address();
$address->type = $parameters['type']; // person or company
$address->firstName = $parameters['firstName'];
$address->lastName = $parameters['lastName'];
$address->fiscalNumber = $parameters['fiscalNumber'];
$address->identityNumber = $parameters['identityNumber'];
$address->country = $parameters['country'];
$address->county = $parameters['county'];
$address->city = $parameters['city'];
$address->zipCode = $parameters['zipCode'];
$address->address = $parameters['address'];
$address->email = $parameters['email'];
$address->mobilePhone = $parameters['mobilePhone'];
$address->bank = $parameters['bank'];
$address->iban = $parameters['iban'];
return $address;
} | php | public function makeBillingAddress(array $parameters = [])
{
$address = new Address();
$address->type = $parameters['type']; // person or company
$address->firstName = $parameters['firstName'];
$address->lastName = $parameters['lastName'];
$address->fiscalNumber = $parameters['fiscalNumber'];
$address->identityNumber = $parameters['identityNumber'];
$address->country = $parameters['country'];
$address->county = $parameters['county'];
$address->city = $parameters['city'];
$address->zipCode = $parameters['zipCode'];
$address->address = $parameters['address'];
$address->email = $parameters['email'];
$address->mobilePhone = $parameters['mobilePhone'];
$address->bank = $parameters['bank'];
$address->iban = $parameters['iban'];
return $address;
} | [
"public",
"function",
"makeBillingAddress",
"(",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"address",
"=",
"new",
"Address",
"(",
")",
";",
"$",
"address",
"->",
"type",
"=",
"$",
"parameters",
"[",
"'type'",
"]",
";",
"// person or compa... | @param array $parameters
@return Address | [
"@param",
"array",
"$parameters"
] | train | https://github.com/BusinessMastery/omnipay-mobilpay/blob/e9013933e8d12bd69c7def4c88b293f9561ab6e1/src/BusinessMastery/Mobilpay/Message/PurchaseRequest.php#L273-L293 |
appzcoder/phpcloc | src/Analyzers/DuplicateAnalyzer.php | DuplicateAnalyzer.processLines | protected function processLines(SplFileObject $file)
{
$filename = $file->getPathname();
$lines = [];
$duplicates = [];
foreach ($file as $line) {
$trimLine = trim($line);
$lineNo = ($file->key() + 1);
if (isset($lines[$trimLine])) {
$foundLineNo = $lines[$trimLine];
if (!in_array($foundLineNo, $duplicates)) {
$duplicates[] = $foundLineNo;
}
$duplicates[] = $lineNo;
} else if (strlen($trimLine) > 3) {
// Non duplicate first line
$lines[$trimLine] = $lineNo;
}
}
$totalDuplicates = count($duplicates);
if ($totalDuplicates > 0) {
sort($duplicates);
$duplicatesStr = '';
foreach (array_chunk($duplicates, 10) as $chunk) {
$duplicatesStr .= implode(', ', $chunk) . PHP_EOL;
}
$this->stats[$filename] = [
'file' => $filename,
'duplicate' => $totalDuplicates,
'line_no' => $duplicatesStr,
];
}
} | php | protected function processLines(SplFileObject $file)
{
$filename = $file->getPathname();
$lines = [];
$duplicates = [];
foreach ($file as $line) {
$trimLine = trim($line);
$lineNo = ($file->key() + 1);
if (isset($lines[$trimLine])) {
$foundLineNo = $lines[$trimLine];
if (!in_array($foundLineNo, $duplicates)) {
$duplicates[] = $foundLineNo;
}
$duplicates[] = $lineNo;
} else if (strlen($trimLine) > 3) {
// Non duplicate first line
$lines[$trimLine] = $lineNo;
}
}
$totalDuplicates = count($duplicates);
if ($totalDuplicates > 0) {
sort($duplicates);
$duplicatesStr = '';
foreach (array_chunk($duplicates, 10) as $chunk) {
$duplicatesStr .= implode(', ', $chunk) . PHP_EOL;
}
$this->stats[$filename] = [
'file' => $filename,
'duplicate' => $totalDuplicates,
'line_no' => $duplicatesStr,
];
}
} | [
"protected",
"function",
"processLines",
"(",
"SplFileObject",
"$",
"file",
")",
"{",
"$",
"filename",
"=",
"$",
"file",
"->",
"getPathname",
"(",
")",
";",
"$",
"lines",
"=",
"[",
"]",
";",
"$",
"duplicates",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",... | Process the lines from a file.
@param SplFileObject $file
@return void | [
"Process",
"the",
"lines",
"from",
"a",
"file",
"."
] | train | https://github.com/appzcoder/phpcloc/blob/0fa4b45e490238e7210009e4a1278e7a1c98d0c2/src/Analyzers/DuplicateAnalyzer.php#L64-L101 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Builder/FormBuilder.php | FormBuilder.build | public function build()
{
$formMapper = $this->getMapper();
$model = $this->getModel();
$primaryKey = (new $model)->getKeyName();
/**
* Empty form
*/
$result = new FormResult();
if ($this->getIdentifier() === null) {
foreach ($formMapper->getFields() as $field) {
$clone = clone $field;
$name = $clone->getName();
// Is this a multiple field?
if ($clone->isMultiple()) {
$clone->setValue(['']);
}
$clone->setContext(BaseField::CONTEXT_FORM);
$result->addField($name, $clone);
}
$this->setResult($result);
return;
}
$items = $model::with([]);
$items->where($primaryKey, $this->getIdentifier());
$item = $items->first();
// modifyModelItem hook
if (method_exists($this->getMapper()->getAdmin(), 'modifyModelItem')) {
$item = $this->getMapper()->getAdmin()->modifyModelItem($item);
}
$result = new FormResult;
$result->setIdentifier($item->{$primaryKey});
foreach ($formMapper->getFields() as $field) {
$clone = clone $field;
$name = $clone->getName();
$value = $item->{$name};
if ($clone->hasBefore()) {
$before = $clone->getBefore();
if ($before instanceof Closure) {
$value = $before($value);
} else {
$value = $before;
}
}
// Is this a multiple field?
if ($clone->isMultiple()) {
$value = Value::decode(Config::get('bauhaus::admin.multiple-serializer'), $value);
}
$clone
->setContext(BaseField::CONTEXT_FORM)
->setValue($value);
$result->addField($name, $clone);
}
$this->setResult($result);
} | php | public function build()
{
$formMapper = $this->getMapper();
$model = $this->getModel();
$primaryKey = (new $model)->getKeyName();
/**
* Empty form
*/
$result = new FormResult();
if ($this->getIdentifier() === null) {
foreach ($formMapper->getFields() as $field) {
$clone = clone $field;
$name = $clone->getName();
// Is this a multiple field?
if ($clone->isMultiple()) {
$clone->setValue(['']);
}
$clone->setContext(BaseField::CONTEXT_FORM);
$result->addField($name, $clone);
}
$this->setResult($result);
return;
}
$items = $model::with([]);
$items->where($primaryKey, $this->getIdentifier());
$item = $items->first();
// modifyModelItem hook
if (method_exists($this->getMapper()->getAdmin(), 'modifyModelItem')) {
$item = $this->getMapper()->getAdmin()->modifyModelItem($item);
}
$result = new FormResult;
$result->setIdentifier($item->{$primaryKey});
foreach ($formMapper->getFields() as $field) {
$clone = clone $field;
$name = $clone->getName();
$value = $item->{$name};
if ($clone->hasBefore()) {
$before = $clone->getBefore();
if ($before instanceof Closure) {
$value = $before($value);
} else {
$value = $before;
}
}
// Is this a multiple field?
if ($clone->isMultiple()) {
$value = Value::decode(Config::get('bauhaus::admin.multiple-serializer'), $value);
}
$clone
->setContext(BaseField::CONTEXT_FORM)
->setValue($value);
$result->addField($name, $clone);
}
$this->setResult($result);
} | [
"public",
"function",
"build",
"(",
")",
"{",
"$",
"formMapper",
"=",
"$",
"this",
"->",
"getMapper",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",
"$",
"primaryKey",
"=",
"(",
"new",
"$",
"model",
")",
"->",
"ge... | Build the list data.
@access public
@return mixed|void | [
"Build",
"the",
"list",
"data",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Builder/FormBuilder.php#L99-L168 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Builder/FormBuilder.php | FormBuilder.create | public function create($input)
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$primaryKey = (new $model)->getKeyName();
$this->setInput($input);
// Field pre update
foreach ($mapper->getFields() as $field) {
$field->preUpdate();
$input = $this->getInput();
// Is this a multiple field?
if ($field->isMultiple()) {
$value = Value::encode(Config::get('bauhaus::admin.multiple-serializer'), $input[$field->getName()]);
$this->setInputVariable($field->getName(), $value);
}
if ($field->hasSaving()) {
$saving = $field->getSaving();
$this->setInputVariable($field->getName(), $saving($input[$field->getName()]));
}
}
// Model before create hook
if (method_exists($admin, 'beforeCreate')) {
$admin->beforeCreate($input);
}
// Validate
if (property_exists($model, 'rules')) {
$validator = Validator::make($this->getInput(), $model::$rules);
if ($validator->fails()) {
return $validator;
}
}
// Model create hook
if (method_exists($admin, 'create')) {
$model = $admin->create($this->getInput());
} else {
$model = $model::create($this->getInput());
}
// Set the primary id from the `new` model
$this->setIdentifier($model->{$primaryKey});
// Field post update
foreach ($mapper->getFields() as $field) {
$field->postUpdate($this->getInput());
}
// Model after create hook
if (method_exists($admin, 'afterCreate')) {
$result = $admin->afterCreate($this->getInput());
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | php | public function create($input)
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$primaryKey = (new $model)->getKeyName();
$this->setInput($input);
// Field pre update
foreach ($mapper->getFields() as $field) {
$field->preUpdate();
$input = $this->getInput();
// Is this a multiple field?
if ($field->isMultiple()) {
$value = Value::encode(Config::get('bauhaus::admin.multiple-serializer'), $input[$field->getName()]);
$this->setInputVariable($field->getName(), $value);
}
if ($field->hasSaving()) {
$saving = $field->getSaving();
$this->setInputVariable($field->getName(), $saving($input[$field->getName()]));
}
}
// Model before create hook
if (method_exists($admin, 'beforeCreate')) {
$admin->beforeCreate($input);
}
// Validate
if (property_exists($model, 'rules')) {
$validator = Validator::make($this->getInput(), $model::$rules);
if ($validator->fails()) {
return $validator;
}
}
// Model create hook
if (method_exists($admin, 'create')) {
$model = $admin->create($this->getInput());
} else {
$model = $model::create($this->getInput());
}
// Set the primary id from the `new` model
$this->setIdentifier($model->{$primaryKey});
// Field post update
foreach ($mapper->getFields() as $field) {
$field->postUpdate($this->getInput());
}
// Model after create hook
if (method_exists($admin, 'afterCreate')) {
$result = $admin->afterCreate($this->getInput());
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | [
"public",
"function",
"create",
"(",
"$",
"input",
")",
"{",
"$",
"mapper",
"=",
"$",
"this",
"->",
"getMapper",
"(",
")",
";",
"$",
"admin",
"=",
"$",
"mapper",
"->",
"getAdmin",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"... | Create a new model from input.
@param Input $input
@access public
@return FormBuilder | [
"Create",
"a",
"new",
"model",
"from",
"input",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Builder/FormBuilder.php#L203-L268 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Builder/FormBuilder.php | FormBuilder.update | public function update($input)
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$this->setInput($input);
// Field pre update
foreach ($this->getMapper()->getFields() as $field) {
$field->preUpdate();
// Is this a multiple field?
if ($field->isMultiple()) {
$value = Value::encode(Config::get('bauhaus::admin.multiple-serializer'), $input[$field->getName()]);
$this->setInputVariable($field->getName(), $value);
}
if ($field->hasSaving()) {
$saving = $field->getSaving();
$this->setInputVariable($field->getName(), $saving($input[$field->getName()]));
}
}
// Model before update hook
if (method_exists($admin, 'beforeUpdate')) {
$admin->beforeUpdate($input);
}
// Validate
if (property_exists($model, 'rules')) {
$validator = Validator::make($this->getInput(), $model::$rules);
if ($validator->fails()) {
return $validator;
}
}
// Model update hook
if (method_exists($this->getMapper()->getAdmin(), 'update')) {
$this->getMapper()->getAdmin()->update($this->getInput());
} else {
$model::find($this->getIdentifier())
->update($this->getInput());
}
// Field post update
foreach ($this->getMapper()->getFields() as $field) {
$field->postUpdate($this->getInput());
}
// Model after update hook
if (method_exists($admin, 'afterCreate')) {
$result = $admin->afterUpdate($this->getInput());
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | php | public function update($input)
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$this->setInput($input);
// Field pre update
foreach ($this->getMapper()->getFields() as $field) {
$field->preUpdate();
// Is this a multiple field?
if ($field->isMultiple()) {
$value = Value::encode(Config::get('bauhaus::admin.multiple-serializer'), $input[$field->getName()]);
$this->setInputVariable($field->getName(), $value);
}
if ($field->hasSaving()) {
$saving = $field->getSaving();
$this->setInputVariable($field->getName(), $saving($input[$field->getName()]));
}
}
// Model before update hook
if (method_exists($admin, 'beforeUpdate')) {
$admin->beforeUpdate($input);
}
// Validate
if (property_exists($model, 'rules')) {
$validator = Validator::make($this->getInput(), $model::$rules);
if ($validator->fails()) {
return $validator;
}
}
// Model update hook
if (method_exists($this->getMapper()->getAdmin(), 'update')) {
$this->getMapper()->getAdmin()->update($this->getInput());
} else {
$model::find($this->getIdentifier())
->update($this->getInput());
}
// Field post update
foreach ($this->getMapper()->getFields() as $field) {
$field->postUpdate($this->getInput());
}
// Model after update hook
if (method_exists($admin, 'afterCreate')) {
$result = $admin->afterUpdate($this->getInput());
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | [
"public",
"function",
"update",
"(",
"$",
"input",
")",
"{",
"$",
"mapper",
"=",
"$",
"this",
"->",
"getMapper",
"(",
")",
";",
"$",
"admin",
"=",
"$",
"mapper",
"->",
"getAdmin",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"... | Update a model from input.
@param Input $input
@access public
@return FormBuilder | [
"Update",
"a",
"model",
"from",
"input",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Builder/FormBuilder.php#L278-L338 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Builder/FormBuilder.php | FormBuilder.destroy | public function destroy()
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$model = $model::find($this->getIdentifier());
// Model before delete hook
if (method_exists($admin, 'beforeDelete')) {
$admin->beforeDelete($model);
}
// Model delete hook
if (method_exists($admin, 'deleting')) {
$admin->deleting($model);
} else {
$model->delete();
}
// Model after delete hook
if (method_exists($admin, 'afterDelete')) {
$result = $admin->afterDelete($model);
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | php | public function destroy()
{
$mapper = $this->getMapper();
$admin = $mapper->getAdmin();
$model = $this->getModel();
$model = $model::find($this->getIdentifier());
// Model before delete hook
if (method_exists($admin, 'beforeDelete')) {
$admin->beforeDelete($model);
}
// Model delete hook
if (method_exists($admin, 'deleting')) {
$admin->deleting($model);
} else {
$model->delete();
}
// Model after delete hook
if (method_exists($admin, 'afterDelete')) {
$result = $admin->afterDelete($model);
if ($result instanceof \Illuminate\Http\RedirectResponse) {
$result->send();
}
}
return $this;
} | [
"public",
"function",
"destroy",
"(",
")",
"{",
"$",
"mapper",
"=",
"$",
"this",
"->",
"getMapper",
"(",
")",
";",
"$",
"admin",
"=",
"$",
"mapper",
"->",
"getAdmin",
"(",
")",
";",
"$",
"model",
"=",
"$",
"this",
"->",
"getModel",
"(",
")",
";",... | Destroy a specific item.
@access public
@return FormBuilder | [
"Destroy",
"a",
"specific",
"item",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Builder/FormBuilder.php#L346-L376 |
appzcoder/phpcloc | src/Commands/ClocCommand.php | ClocCommand.execute | public function execute(InputInterface $input, OutputInterface $output)
{
$path = $input->getArgument('path');
$ext = $input->getOption('ext');
$exclude = $input->getOption('exclude');
$stats = array_values((new ClocAnalyzer($path, $ext, $exclude))->stats());
if (count($stats) === 0) {
$output->writeln('No files found.');
return;
}
array_push(
$stats,
new TableSeparator(),
[
'Total',
array_reduce($stats, function ($carry, $item) {
return $carry + $item['files'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['blank'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['comment'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['code'];
}),
]
);
$table = new Table($output);
$table
->setHeaders(['Language', 'files', 'blank', 'comment', 'code'])
->setRows($stats)
;
$table->setColumnWidths([20, 10, 10, 10, 10]);
$table->render();
} | php | public function execute(InputInterface $input, OutputInterface $output)
{
$path = $input->getArgument('path');
$ext = $input->getOption('ext');
$exclude = $input->getOption('exclude');
$stats = array_values((new ClocAnalyzer($path, $ext, $exclude))->stats());
if (count($stats) === 0) {
$output->writeln('No files found.');
return;
}
array_push(
$stats,
new TableSeparator(),
[
'Total',
array_reduce($stats, function ($carry, $item) {
return $carry + $item['files'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['blank'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['comment'];
}),
array_reduce($stats, function ($carry, $item) {
return $carry + $item['code'];
}),
]
);
$table = new Table($output);
$table
->setHeaders(['Language', 'files', 'blank', 'comment', 'code'])
->setRows($stats)
;
$table->setColumnWidths([20, 10, 10, 10, 10]);
$table->render();
} | [
"public",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"path",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'path'",
")",
";",
"$",
"ext",
"=",
"$",
"input",
"->",
"getOption",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/appzcoder/phpcloc/blob/0fa4b45e490238e7210009e4a1278e7a1c98d0c2/src/Commands/ClocCommand.php#L48-L87 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php | phpQueryObjectPlugin_WebBrowser.WebBrowser | public static function WebBrowser($self, $callback = null, $location = null)
{
$self = $self->_clone()->toRoot();
$location = $location
? $location
// TODO use document.location
: $self->document->xhr->getUri(true);
// FIXME tmp
$self->document->WebBrowserCallback = $callback;
if (! $location) {
throw new Exception('Location needed to activate WebBrowser plugin !');
} else {
$self->bind('click', array($location, $callback), array('phpQueryPlugin_WebBrowser', 'hadleClick'));
$self->bind('submit', array($location, $callback), array('phpQueryPlugin_WebBrowser', 'handleSubmit'));
}
} | php | public static function WebBrowser($self, $callback = null, $location = null)
{
$self = $self->_clone()->toRoot();
$location = $location
? $location
// TODO use document.location
: $self->document->xhr->getUri(true);
// FIXME tmp
$self->document->WebBrowserCallback = $callback;
if (! $location) {
throw new Exception('Location needed to activate WebBrowser plugin !');
} else {
$self->bind('click', array($location, $callback), array('phpQueryPlugin_WebBrowser', 'hadleClick'));
$self->bind('submit', array($location, $callback), array('phpQueryPlugin_WebBrowser', 'handleSubmit'));
}
} | [
"public",
"static",
"function",
"WebBrowser",
"(",
"$",
"self",
",",
"$",
"callback",
"=",
"null",
",",
"$",
"location",
"=",
"null",
")",
"{",
"$",
"self",
"=",
"$",
"self",
"->",
"_clone",
"(",
")",
"->",
"toRoot",
"(",
")",
";",
"$",
"location",... | Enter description here...
@param phpQueryObject $self
@todo support 'reset' event | [
"Enter",
"description",
"here",
"..."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php#L19-L34 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php | phpQueryObjectPlugin_WebBrowser.location | public static function location($self, $url = null)
{
// TODO if ! $url return actual location ???
$xhr = isset($self->document->xhr)
? $self->document->xhr
: null;
$xhr = phpQuery::ajax(
array(
'url' => $url,
), $xhr
);
$return = false;
if ($xhr->getLastResponse()->isSuccessful()) {
$return = phpQueryPlugin_WebBrowser::browserReceive($xhr);
if (isset($self->document->WebBrowserCallback)) {
phpQuery::callbackRun(
$self->document->WebBrowserCallback,
array($return)
);
}
}
return $return;
} | php | public static function location($self, $url = null)
{
// TODO if ! $url return actual location ???
$xhr = isset($self->document->xhr)
? $self->document->xhr
: null;
$xhr = phpQuery::ajax(
array(
'url' => $url,
), $xhr
);
$return = false;
if ($xhr->getLastResponse()->isSuccessful()) {
$return = phpQueryPlugin_WebBrowser::browserReceive($xhr);
if (isset($self->document->WebBrowserCallback)) {
phpQuery::callbackRun(
$self->document->WebBrowserCallback,
array($return)
);
}
}
return $return;
} | [
"public",
"static",
"function",
"location",
"(",
"$",
"self",
",",
"$",
"url",
"=",
"null",
")",
"{",
"// TODO if ! $url return actual location ???",
"$",
"xhr",
"=",
"isset",
"(",
"$",
"self",
"->",
"document",
"->",
"xhr",
")",
"?",
"$",
"self",
"->",
... | Method changing browser location.
Fires callback registered with WebBrowser(), if any.
@param $self
@param $url
@return unknown_type | [
"Method",
"changing",
"browser",
"location",
".",
"Fires",
"callback",
"registered",
"with",
"WebBrowser",
"()",
"if",
"any",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php#L74-L96 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php | phpQueryPlugin_WebBrowser.handleSubmit | public static function handleSubmit($e, $callback = null)
{
$node = phpQuery::pq($e->target);
if (!$node->is('form') || !$node->is('[action]')) {
return;
}
// TODO document.location
$xhr = isset($node->document->xhr)
? $node->document->xhr
: null;
$submit = pq($e->relatedTarget)->is(':submit')
? $e->relatedTarget
// will this work ?
// : $node->find(':submit:first')->get(0);
: $node->find('*:submit:first')->get(0);
$data = array();
foreach($node->serializeArray($submit) as $r) {
// XXXt.c maybe $node->not(':submit')->add($sumit) would be better ?
// foreach($node->serializeArray($submit) as $r)
$data[ $r['name'] ] = $r['value'];
}
$options = array(
'type' => $node->attr('method')
? $node->attr('method')
: 'GET',
'url' => resolve_url($e->data[0], $node->attr('action')),
'data' => $data,
'referer' => $node->document->location,
// 'success' => $e->data[1],
);
if ($node->attr('enctype')) {
$options['contentType'] = $node->attr('enctype');
}
$xhr = phpQuery::ajax($options, $xhr);
if ((! $callback || !($callback instanceof Callback)) && $e->data[1]) {
$callback = $e->data[1];
}
if ($xhr->getLastResponse()->isSuccessful() && $callback) {
phpQuery::callbackRun(
$callback, array(
self::browserReceive($xhr)
)
);
}
} | php | public static function handleSubmit($e, $callback = null)
{
$node = phpQuery::pq($e->target);
if (!$node->is('form') || !$node->is('[action]')) {
return;
}
// TODO document.location
$xhr = isset($node->document->xhr)
? $node->document->xhr
: null;
$submit = pq($e->relatedTarget)->is(':submit')
? $e->relatedTarget
// will this work ?
// : $node->find(':submit:first')->get(0);
: $node->find('*:submit:first')->get(0);
$data = array();
foreach($node->serializeArray($submit) as $r) {
// XXXt.c maybe $node->not(':submit')->add($sumit) would be better ?
// foreach($node->serializeArray($submit) as $r)
$data[ $r['name'] ] = $r['value'];
}
$options = array(
'type' => $node->attr('method')
? $node->attr('method')
: 'GET',
'url' => resolve_url($e->data[0], $node->attr('action')),
'data' => $data,
'referer' => $node->document->location,
// 'success' => $e->data[1],
);
if ($node->attr('enctype')) {
$options['contentType'] = $node->attr('enctype');
}
$xhr = phpQuery::ajax($options, $xhr);
if ((! $callback || !($callback instanceof Callback)) && $e->data[1]) {
$callback = $e->data[1];
}
if ($xhr->getLastResponse()->isSuccessful() && $callback) {
phpQuery::callbackRun(
$callback, array(
self::browserReceive($xhr)
)
);
}
} | [
"public",
"static",
"function",
"handleSubmit",
"(",
"$",
"e",
",",
"$",
"callback",
"=",
"null",
")",
"{",
"$",
"node",
"=",
"phpQuery",
"::",
"pq",
"(",
"$",
"e",
"->",
"target",
")",
";",
"if",
"(",
"!",
"$",
"node",
"->",
"is",
"(",
"'form'",... | Enter description here...
@param unknown_type $e
@TODO trigger submit for form after form's submit button has a click event | [
"Enter",
"description",
"here",
"..."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/plugins/WebBrowser.php#L320-L364 |
txj123/zilf | src/Zilf/Console/Scheduling/Event.php | Event.runCommandInBackground | protected function runCommandInBackground()
{
$this->callBeforeCallbacks();
(new Process(
$this->buildCommand(), base_path(), null, null, null
))->run();
} | php | protected function runCommandInBackground()
{
$this->callBeforeCallbacks();
(new Process(
$this->buildCommand(), base_path(), null, null, null
))->run();
} | [
"protected",
"function",
"runCommandInBackground",
"(",
")",
"{",
"$",
"this",
"->",
"callBeforeCallbacks",
"(",
")",
";",
"(",
"new",
"Process",
"(",
"$",
"this",
"->",
"buildCommand",
"(",
")",
",",
"base_path",
"(",
")",
",",
"null",
",",
"null",
",",... | Run the command in the background.
@return void | [
"Run",
"the",
"command",
"in",
"the",
"background",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Console/Scheduling/Event.php#L218-L225 |
txj123/zilf | src/Zilf/Console/Scheduling/Event.php | Event.isDue | public function isDue()
{
if (! $this->runsInMaintenanceMode() && Zilf::$app->isDownForMaintenance()) {
return false;
}
return $this->expressionPasses() &&
$this->runsInEnvironment(Zilf::$app->getEnvironment());
} | php | public function isDue()
{
if (! $this->runsInMaintenanceMode() && Zilf::$app->isDownForMaintenance()) {
return false;
}
return $this->expressionPasses() &&
$this->runsInEnvironment(Zilf::$app->getEnvironment());
} | [
"public",
"function",
"isDue",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"runsInMaintenanceMode",
"(",
")",
"&&",
"Zilf",
"::",
"$",
"app",
"->",
"isDownForMaintenance",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
... | Determine if the given event should run based on the Cron expression.
@return bool | [
"Determine",
"if",
"the",
"given",
"event",
"should",
"run",
"based",
"on",
"the",
"Cron",
"expression",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Console/Scheduling/Event.php#L266-L274 |
txj123/zilf | src/Zilf/Console/Scheduling/Event.php | Event.emailOutputTo | public function emailOutputTo($addresses, $onlyIfOutputExists = false)
{
$this->ensureOutputIsBeingCapturedForEmail();
$addresses = Arr::wrap($addresses);
return $this->then(
function (Mailer $mailer) use ($addresses, $onlyIfOutputExists) {
$this->emailOutput($mailer, $addresses, $onlyIfOutputExists);
}
);
} | php | public function emailOutputTo($addresses, $onlyIfOutputExists = false)
{
$this->ensureOutputIsBeingCapturedForEmail();
$addresses = Arr::wrap($addresses);
return $this->then(
function (Mailer $mailer) use ($addresses, $onlyIfOutputExists) {
$this->emailOutput($mailer, $addresses, $onlyIfOutputExists);
}
);
} | [
"public",
"function",
"emailOutputTo",
"(",
"$",
"addresses",
",",
"$",
"onlyIfOutputExists",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"ensureOutputIsBeingCapturedForEmail",
"(",
")",
";",
"$",
"addresses",
"=",
"Arr",
"::",
"wrap",
"(",
"$",
"addresses",
... | E-mail the results of the scheduled operation.
@param array|mixed $addresses
@param bool $onlyIfOutputExists
@return $this
@throws \LogicException | [
"E",
"-",
"mail",
"the",
"results",
"of",
"the",
"scheduled",
"operation",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Console/Scheduling/Event.php#L372-L383 |
txj123/zilf | src/Zilf/Console/Scheduling/Event.php | Event.nextRunDate | public function nextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
{
return Carbon::instance(
CronExpression::factory(
$this->getExpression()
)->getNextRunDate($currentTime, $nth, $allowCurrentDate)
);
} | php | public function nextRunDate($currentTime = 'now', $nth = 0, $allowCurrentDate = false)
{
return Carbon::instance(
CronExpression::factory(
$this->getExpression()
)->getNextRunDate($currentTime, $nth, $allowCurrentDate)
);
} | [
"public",
"function",
"nextRunDate",
"(",
"$",
"currentTime",
"=",
"'now'",
",",
"$",
"nth",
"=",
"0",
",",
"$",
"allowCurrentDate",
"=",
"false",
")",
"{",
"return",
"Carbon",
"::",
"instance",
"(",
"CronExpression",
"::",
"factory",
"(",
"$",
"this",
"... | Determine the next due date for an event.
@param \DateTime|string $currentTime
@param int $nth
@param bool $allowCurrentDate
@return \Illuminate\Support\Carbon | [
"Determine",
"the",
"next",
"due",
"date",
"for",
"an",
"event",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Console/Scheduling/Event.php#L699-L706 |
txj123/zilf | src/Zilf/Queue/DatabaseQueue.php | DatabaseQueue.pushToDatabase | protected function pushToDatabase($queue, $payload, $delay = 0, $attempts = 0)
{
return $this->database->createCommand()->insert(
$this->table,
$this->buildDatabaseRecord(
$this->getQueue($queue), $payload, $this->availableAt($delay), $attempts
)
)->execute();
} | php | protected function pushToDatabase($queue, $payload, $delay = 0, $attempts = 0)
{
return $this->database->createCommand()->insert(
$this->table,
$this->buildDatabaseRecord(
$this->getQueue($queue), $payload, $this->availableAt($delay), $attempts
)
)->execute();
} | [
"protected",
"function",
"pushToDatabase",
"(",
"$",
"queue",
",",
"$",
"payload",
",",
"$",
"delay",
"=",
"0",
",",
"$",
"attempts",
"=",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"database",
"->",
"createCommand",
"(",
")",
"->",
"insert",
"(",
"... | Push a raw payload to the database with a given delay.
@param string|null $queue
@param string $payload
@param \DateTimeInterface|\DateInterval|int $delay
@param int $attempts
@return mixed | [
"Push",
"a",
"raw",
"payload",
"to",
"the",
"database",
"with",
"a",
"given",
"delay",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/DatabaseQueue.php#L156-L164 |
txj123/zilf | src/Zilf/Queue/DatabaseQueue.php | DatabaseQueue.getNextAvailableJob | protected function getNextAvailableJob($queue)
{
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$sql = 'SELECT * FROM ' . $this->table . ' WHERE queue =\'' . $this->getQueue($queue) . '\'
AND (
(reserved_at is NULL AND available_at <=' . $this->currentTime() . ')
OR
(reserved_at <= ' . $expiration . ')
)
order by id asc limit 1 ';
$job = $this->database->createCommand($sql)->queryOne();
return $job ? new DatabaseJobRecord((object)$job) : null;
} | php | protected function getNextAvailableJob($queue)
{
$expiration = Carbon::now()->subSeconds($this->retryAfter)->getTimestamp();
$sql = 'SELECT * FROM ' . $this->table . ' WHERE queue =\'' . $this->getQueue($queue) . '\'
AND (
(reserved_at is NULL AND available_at <=' . $this->currentTime() . ')
OR
(reserved_at <= ' . $expiration . ')
)
order by id asc limit 1 ';
$job = $this->database->createCommand($sql)->queryOne();
return $job ? new DatabaseJobRecord((object)$job) : null;
} | [
"protected",
"function",
"getNextAvailableJob",
"(",
"$",
"queue",
")",
"{",
"$",
"expiration",
"=",
"Carbon",
"::",
"now",
"(",
")",
"->",
"subSeconds",
"(",
"$",
"this",
"->",
"retryAfter",
")",
"->",
"getTimestamp",
"(",
")",
";",
"$",
"sql",
"=",
"... | Get the next available job for the queue.
@param string|null $queue
@return \Illuminate\Queue\Jobs\DatabaseJobRecord|null | [
"Get",
"the",
"next",
"available",
"job",
"for",
"the",
"queue",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/DatabaseQueue.php#L215-L229 |
txj123/zilf | src/Zilf/Queue/DatabaseQueue.php | DatabaseQueue.marshalJob | protected function marshalJob($queue, $job)
{
$job = $this->markJobAsReserved($job);
return new DatabaseJob(
$this, $job, $this->connectionName, $queue
);
} | php | protected function marshalJob($queue, $job)
{
$job = $this->markJobAsReserved($job);
return new DatabaseJob(
$this, $job, $this->connectionName, $queue
);
} | [
"protected",
"function",
"marshalJob",
"(",
"$",
"queue",
",",
"$",
"job",
")",
"{",
"$",
"job",
"=",
"$",
"this",
"->",
"markJobAsReserved",
"(",
"$",
"job",
")",
";",
"return",
"new",
"DatabaseJob",
"(",
"$",
"this",
",",
"$",
"job",
",",
"$",
"t... | Marshal the reserved job into a DatabaseJob instance.
@param string $queue
@param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
@return \Illuminate\Queue\Jobs\DatabaseJob | [
"Marshal",
"the",
"reserved",
"job",
"into",
"a",
"DatabaseJob",
"instance",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/DatabaseQueue.php#L271-L278 |
txj123/zilf | src/Zilf/Queue/DatabaseQueue.php | DatabaseQueue.markJobAsReserved | protected function markJobAsReserved($job)
{
$this->database->createCommand()->update(
$this->table, [
'reserved_at' => $job->touch(),
'attempts' => $job->increment(),
], [
'id' => $job->id
]
)->execute();
return $job;
} | php | protected function markJobAsReserved($job)
{
$this->database->createCommand()->update(
$this->table, [
'reserved_at' => $job->touch(),
'attempts' => $job->increment(),
], [
'id' => $job->id
]
)->execute();
return $job;
} | [
"protected",
"function",
"markJobAsReserved",
"(",
"$",
"job",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"createCommand",
"(",
")",
"->",
"update",
"(",
"$",
"this",
"->",
"table",
",",
"[",
"'reserved_at'",
"=>",
"$",
"job",
"->",
"touch",
"(",
"... | Mark the given job ID as reserved.
@param \Illuminate\Queue\Jobs\DatabaseJobRecord $job
@return \Illuminate\Queue\Jobs\DatabaseJobRecord | [
"Mark",
"the",
"given",
"job",
"ID",
"as",
"reserved",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/DatabaseQueue.php#L286-L298 |
txj123/zilf | src/Zilf/Queue/DatabaseQueue.php | DatabaseQueue.deleteReserved | public function deleteReserved($queue, $id)
{
$this->database->transaction(
function () use ($id) {
$this->database->createCommand()->delete($this->table, ['id' => $id])->execute();
}
);
} | php | public function deleteReserved($queue, $id)
{
$this->database->transaction(
function () use ($id) {
$this->database->createCommand()->delete($this->table, ['id' => $id])->execute();
}
);
} | [
"public",
"function",
"deleteReserved",
"(",
"$",
"queue",
",",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"transaction",
"(",
"function",
"(",
")",
"use",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"database",
"->",
"createCommand",
... | Delete a reserved job from the queue.
@param string $queue
@param string $id
@return void
@throws \Exception|\Throwable | [
"Delete",
"a",
"reserved",
"job",
"from",
"the",
"queue",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/DatabaseQueue.php#L308-L315 |
quai10/quai10-template | lib/ContactForm.php | ContactForm.getClass | private static function getClass(FormTag $tag, $validation_error)
{
$class = wpcf7_form_controls_class($tag->getType(), 'wpcf7-text');
if (in_array($tag->getBaseType(), ['email', 'url', 'tel'])) {
$class .= ' wpcf7-validates-as-'.$tag->getBaseType();
}
if ($validation_error) {
$class .= ' wpcf7-not-valid';
}
return $class;
} | php | private static function getClass(FormTag $tag, $validation_error)
{
$class = wpcf7_form_controls_class($tag->getType(), 'wpcf7-text');
if (in_array($tag->getBaseType(), ['email', 'url', 'tel'])) {
$class .= ' wpcf7-validates-as-'.$tag->getBaseType();
}
if ($validation_error) {
$class .= ' wpcf7-not-valid';
}
return $class;
} | [
"private",
"static",
"function",
"getClass",
"(",
"FormTag",
"$",
"tag",
",",
"$",
"validation_error",
")",
"{",
"$",
"class",
"=",
"wpcf7_form_controls_class",
"(",
"$",
"tag",
"->",
"getType",
"(",
")",
",",
"'wpcf7-text'",
")",
";",
"if",
"(",
"in_array... | Get input class.
@param FormTag $tag Input tag
@param string $validation_error Validation error
@return string Class | [
"Get",
"input",
"class",
"."
] | train | https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/ContactForm.php#L21-L34 |
quai10/quai10-template | lib/ContactForm.php | ContactForm.getAtts | private static function getAtts(FormTag $tag, $validation_error, $class)
{
$atts = [];
$atts['size'] = $tag->get_size_option('40');
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['minlength'] = $tag->get_minlength_option();
if ($atts['maxlength'] && $atts['minlength'] && $atts['maxlength'] < $atts['minlength']) {
unset($atts['maxlength'], $atts['minlength']);
}
$atts['class'] = $tag->get_class_option($class);
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
if ($tag->has_option('readonly')) {
$atts['readonly'] = 'readonly';
}
if ($tag->is_required()) {
$atts['aria-required'] = 'true';
$atts['required'] = 'true';
}
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$values = $tag->getValues();
$value = (string) reset($values);
if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
$atts['placeholder'] = $value;
$value = '';
}
$value = $tag->get_default_option($value);
$value = wpcf7_get_hangover($tag->getName(), $value);
$atts['value'] = $value;
if (wpcf7_support_html5()) {
$atts['type'] = $tag->getBaseType();
} else {
$atts['type'] = 'text';
}
$atts['name'] = $tag->getName();
return wpcf7_format_atts($atts);
} | php | private static function getAtts(FormTag $tag, $validation_error, $class)
{
$atts = [];
$atts['size'] = $tag->get_size_option('40');
$atts['maxlength'] = $tag->get_maxlength_option();
$atts['minlength'] = $tag->get_minlength_option();
if ($atts['maxlength'] && $atts['minlength'] && $atts['maxlength'] < $atts['minlength']) {
unset($atts['maxlength'], $atts['minlength']);
}
$atts['class'] = $tag->get_class_option($class);
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
if ($tag->has_option('readonly')) {
$atts['readonly'] = 'readonly';
}
if ($tag->is_required()) {
$atts['aria-required'] = 'true';
$atts['required'] = 'true';
}
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$values = $tag->getValues();
$value = (string) reset($values);
if ($tag->has_option('placeholder') || $tag->has_option('watermark')) {
$atts['placeholder'] = $value;
$value = '';
}
$value = $tag->get_default_option($value);
$value = wpcf7_get_hangover($tag->getName(), $value);
$atts['value'] = $value;
if (wpcf7_support_html5()) {
$atts['type'] = $tag->getBaseType();
} else {
$atts['type'] = 'text';
}
$atts['name'] = $tag->getName();
return wpcf7_format_atts($atts);
} | [
"private",
"static",
"function",
"getAtts",
"(",
"FormTag",
"$",
"tag",
",",
"$",
"validation_error",
",",
"$",
"class",
")",
"{",
"$",
"atts",
"=",
"[",
"]",
";",
"$",
"atts",
"[",
"'size'",
"]",
"=",
"$",
"tag",
"->",
"get_size_option",
"(",
"'40'"... | Get input attributes.
@param FormTag $tag Input tag
@param string $validation_error Validation error
@param string $class Class
@return string Attributes | [
"Get",
"input",
"attributes",
"."
] | train | https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/ContactForm.php#L45-L95 |
quai10/quai10-template | lib/ContactForm.php | ContactForm.addCustomFields | public static function addCustomFields($tag)
{
$tag = new FormTag($tag);
if (empty($tag->getType())) {
return '';
}
$validation_error = wpcf7_get_validation_error($tag->getName());
$class = self::getClass($tag, $validation_error);
$atts = self::getAtts($tag, $validation_error, $class);
$html = sprintf(
'<input class="%1$s" %2$s />%3$s',
sanitize_html_class($tag->getName()),
$atts,
$validation_error
);
return $html;
} | php | public static function addCustomFields($tag)
{
$tag = new FormTag($tag);
if (empty($tag->getType())) {
return '';
}
$validation_error = wpcf7_get_validation_error($tag->getName());
$class = self::getClass($tag, $validation_error);
$atts = self::getAtts($tag, $validation_error, $class);
$html = sprintf(
'<input class="%1$s" %2$s />%3$s',
sanitize_html_class($tag->getName()),
$atts,
$validation_error
);
return $html;
} | [
"public",
"static",
"function",
"addCustomFields",
"(",
"$",
"tag",
")",
"{",
"$",
"tag",
"=",
"new",
"FormTag",
"(",
"$",
"tag",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"tag",
"->",
"getType",
"(",
")",
")",
")",
"{",
"return",
"''",
";",
"}",
... | Declare custom field types.
@param array|string $tag Tag | [
"Declare",
"custom",
"field",
"types",
"."
] | train | https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/ContactForm.php#L102-L123 |
quai10/quai10-template | lib/ContactForm.php | ContactForm.addFields | public static function addFields()
{
$tags = ['text', 'text*', 'email', 'email*', 'url', 'url*', 'tel', 'tel*'];
foreach ($tags as $tag) {
//We have to remove tags before replacing them.
wpcf7_remove_form_tag($tag);
}
wpcf7_add_form_tag($tags, [self::class, 'addCustomFields'], true);
} | php | public static function addFields()
{
$tags = ['text', 'text*', 'email', 'email*', 'url', 'url*', 'tel', 'tel*'];
foreach ($tags as $tag) {
//We have to remove tags before replacing them.
wpcf7_remove_form_tag($tag);
}
wpcf7_add_form_tag($tags, [self::class, 'addCustomFields'], true);
} | [
"public",
"static",
"function",
"addFields",
"(",
")",
"{",
"$",
"tags",
"=",
"[",
"'text'",
",",
"'text*'",
",",
"'email'",
",",
"'email*'",
",",
"'url'",
",",
"'url*'",
",",
"'tel'",
",",
"'tel*'",
"]",
";",
"foreach",
"(",
"$",
"tags",
"as",
"$",
... | Customize form fields. | [
"Customize",
"form",
"fields",
"."
] | train | https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/ContactForm.php#L128-L136 |
quai10/quai10-template | lib/ContactForm.php | ContactForm.addCustomSubmitBtn | public static function addCustomSubmitBtn($tag)
{
$tag = new FormTag($tag);
$class = wpcf7_form_controls_class($tag->getType());
$atts = [];
$atts['class'] = $tag->get_class_option($class).' btn';
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
$value = isset($tag->values[0]) ? $tag->values[0] : '';
if (empty($value)) {
$value = __('Send', 'contact-form-7');
}
$atts['type'] = 'submit';
$atts['value'] = $value;
$atts = wpcf7_format_atts($atts);
$html = sprintf('<button type="submit" %1$s>%2$s</button>', $atts, $value);
return $html;
} | php | public static function addCustomSubmitBtn($tag)
{
$tag = new FormTag($tag);
$class = wpcf7_form_controls_class($tag->getType());
$atts = [];
$atts['class'] = $tag->get_class_option($class).' btn';
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option('tabindex', 'int', true);
$value = isset($tag->values[0]) ? $tag->values[0] : '';
if (empty($value)) {
$value = __('Send', 'contact-form-7');
}
$atts['type'] = 'submit';
$atts['value'] = $value;
$atts = wpcf7_format_atts($atts);
$html = sprintf('<button type="submit" %1$s>%2$s</button>', $atts, $value);
return $html;
} | [
"public",
"static",
"function",
"addCustomSubmitBtn",
"(",
"$",
"tag",
")",
"{",
"$",
"tag",
"=",
"new",
"FormTag",
"(",
"$",
"tag",
")",
";",
"$",
"class",
"=",
"wpcf7_form_controls_class",
"(",
"$",
"tag",
"->",
"getType",
"(",
")",
")",
";",
"$",
... | Declare custom submit button.
@param array|string $tag Tag | [
"Declare",
"custom",
"submit",
"button",
"."
] | train | https://github.com/quai10/quai10-template/blob/3e98b7de031f5507831946200081b6cb35b468b7/lib/ContactForm.php#L143-L169 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.daemon | public function daemon($workCommand, $connectionName, $queue, WorkerOptions $options)
{
if ($this->supportsAsyncSignals()) {
$this->listenForSignals();
}
$lastRestart = $this->getTimestampOfLastQueueRestart();
while (true) {
// Before reserving any jobs, we will make sure this queue is not paused and
// if it is we will just pause this worker for a given amount of time and
// make sure we do not need to kill this worker process off completely.
if (!$this->daemonShouldRun($options, $connectionName, $queue)) {
$this->pauseWorker($options, $lastRestart);
continue;
}
// First, we will attempt to get the next job off of the queue. We will also
// register the timeout handler and reset the alarm for this job so it is
// not stuck in a frozen state forever. Then, we can fire off this job.
$job = $this->getNextJob(
$this->manager->connection($connectionName), $queue
);
if ($this->supportsAsyncSignals()) {
$this->registerTimeoutHandler($job, $options);
}
// If the daemon should run (not in maintenance mode, etc.), then we can run
// fire off this job for processing. Otherwise, we will need to sleep the
// worker so no more jobs are processed until they should be processed.
if ($job) {
$this->runJob($workCommand, $job, $connectionName, $options);
} else {
$this->sleep($options->sleep);
}
// Finally, we will check to see if we have exceeded our memory limits or if
// the queue should restart based on other indications. If so, we'll stop
// this worker and let whatever is "monitoring" it restart the process.
$this->stopIfNecessary($options, $lastRestart, $job);
}
} | php | public function daemon($workCommand, $connectionName, $queue, WorkerOptions $options)
{
if ($this->supportsAsyncSignals()) {
$this->listenForSignals();
}
$lastRestart = $this->getTimestampOfLastQueueRestart();
while (true) {
// Before reserving any jobs, we will make sure this queue is not paused and
// if it is we will just pause this worker for a given amount of time and
// make sure we do not need to kill this worker process off completely.
if (!$this->daemonShouldRun($options, $connectionName, $queue)) {
$this->pauseWorker($options, $lastRestart);
continue;
}
// First, we will attempt to get the next job off of the queue. We will also
// register the timeout handler and reset the alarm for this job so it is
// not stuck in a frozen state forever. Then, we can fire off this job.
$job = $this->getNextJob(
$this->manager->connection($connectionName), $queue
);
if ($this->supportsAsyncSignals()) {
$this->registerTimeoutHandler($job, $options);
}
// If the daemon should run (not in maintenance mode, etc.), then we can run
// fire off this job for processing. Otherwise, we will need to sleep the
// worker so no more jobs are processed until they should be processed.
if ($job) {
$this->runJob($workCommand, $job, $connectionName, $options);
} else {
$this->sleep($options->sleep);
}
// Finally, we will check to see if we have exceeded our memory limits or if
// the queue should restart based on other indications. If so, we'll stop
// this worker and let whatever is "monitoring" it restart the process.
$this->stopIfNecessary($options, $lastRestart, $job);
}
} | [
"public",
"function",
"daemon",
"(",
"$",
"workCommand",
",",
"$",
"connectionName",
",",
"$",
"queue",
",",
"WorkerOptions",
"$",
"options",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"supportsAsyncSignals",
"(",
")",
")",
"{",
"$",
"this",
"->",
"listenFo... | Listen to the given queue in a loop.
@param string $connectionName
@param string $queue
@param \Illuminate\Queue\WorkerOptions $options
@return void | [
"Listen",
"to",
"the",
"given",
"queue",
"in",
"a",
"loop",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L85-L128 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.daemonShouldRun | protected function daemonShouldRun(WorkerOptions $options, $connectionName, $queue)
{
return !(($this->manager->isDownForMaintenance() && !$options->force) ||
$this->paused);
} | php | protected function daemonShouldRun(WorkerOptions $options, $connectionName, $queue)
{
return !(($this->manager->isDownForMaintenance() && !$options->force) ||
$this->paused);
} | [
"protected",
"function",
"daemonShouldRun",
"(",
"WorkerOptions",
"$",
"options",
",",
"$",
"connectionName",
",",
"$",
"queue",
")",
"{",
"return",
"!",
"(",
"(",
"$",
"this",
"->",
"manager",
"->",
"isDownForMaintenance",
"(",
")",
"&&",
"!",
"$",
"optio... | Determine if the daemon should process on this iteration.
@param \Illuminate\Queue\WorkerOptions $options
@param string $connectionName
@param string $queue
@return bool | [
"Determine",
"if",
"the",
"daemon",
"should",
"process",
"on",
"this",
"iteration",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L173-L177 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.runNextJob | public function runNextJob($workCommand, $connectionName, $queue, WorkerOptions $options)
{
$job = $this->getNextJob(
$this->manager->connection($connectionName), $queue
);
// If we're able to pull a job off of the stack, we will process it and then return
// from this method. If there is no job on the queue, we will "sleep" the worker
// for the specified number of seconds, then keep processing jobs after sleep.
if ($job) {
return $this->runJob($workCommand, $job, $connectionName, $options);
}
$this->sleep($options->sleep);
} | php | public function runNextJob($workCommand, $connectionName, $queue, WorkerOptions $options)
{
$job = $this->getNextJob(
$this->manager->connection($connectionName), $queue
);
// If we're able to pull a job off of the stack, we will process it and then return
// from this method. If there is no job on the queue, we will "sleep" the worker
// for the specified number of seconds, then keep processing jobs after sleep.
if ($job) {
return $this->runJob($workCommand, $job, $connectionName, $options);
}
$this->sleep($options->sleep);
} | [
"public",
"function",
"runNextJob",
"(",
"$",
"workCommand",
",",
"$",
"connectionName",
",",
"$",
"queue",
",",
"WorkerOptions",
"$",
"options",
")",
"{",
"$",
"job",
"=",
"$",
"this",
"->",
"getNextJob",
"(",
"$",
"this",
"->",
"manager",
"->",
"connec... | Process the next job on the queue.
@param string $connectionName
@param string $queue
@param \Illuminate\Queue\WorkerOptions $options
@return void | [
"Process",
"the",
"next",
"job",
"on",
"the",
"queue",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L221-L235 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.getNextJob | protected function getNextJob($connection, $queue)
{
try {
foreach (explode(',', $queue) as $queue) {
if (!is_null($job = $connection->pop($queue))) {
return $job;
}
}
} catch (Exception $e) {
$this->report($e);
$this->stopWorkerIfLostConnection($e);
$this->sleep(1);
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->report($e);
$this->stopWorkerIfLostConnection($e);
$this->sleep(1);
}
} | php | protected function getNextJob($connection, $queue)
{
try {
foreach (explode(',', $queue) as $queue) {
if (!is_null($job = $connection->pop($queue))) {
return $job;
}
}
} catch (Exception $e) {
$this->report($e);
$this->stopWorkerIfLostConnection($e);
$this->sleep(1);
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->report($e);
$this->stopWorkerIfLostConnection($e);
$this->sleep(1);
}
} | [
"protected",
"function",
"getNextJob",
"(",
"$",
"connection",
",",
"$",
"queue",
")",
"{",
"try",
"{",
"foreach",
"(",
"explode",
"(",
"','",
",",
"$",
"queue",
")",
"as",
"$",
"queue",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"job",
"=",
... | Get the next job from the queue connection.
@param \Illuminate\Contracts\Queue\Queue $connection
@param string $queue
@return \Illuminate\Contracts\Queue\Job|null | [
"Get",
"the",
"next",
"job",
"from",
"the",
"queue",
"connection",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L244-L266 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.runJob | protected function runJob($workCommand, $job, $connectionName, WorkerOptions $options)
{
try {
return $this->process($workCommand, $connectionName, $job, $options);
} catch (Exception $e) {
$this->report($e);
$this->stopWorkerIfLostConnection($e);
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->report($e);
$this->stopWorkerIfLostConnection($e);
}
} | php | protected function runJob($workCommand, $job, $connectionName, WorkerOptions $options)
{
try {
return $this->process($workCommand, $connectionName, $job, $options);
} catch (Exception $e) {
$this->report($e);
$this->stopWorkerIfLostConnection($e);
} catch (Throwable $e) {
$e = new FatalThrowableError($e);
$this->report($e);
$this->stopWorkerIfLostConnection($e);
}
} | [
"protected",
"function",
"runJob",
"(",
"$",
"workCommand",
",",
"$",
"job",
",",
"$",
"connectionName",
",",
"WorkerOptions",
"$",
"options",
")",
"{",
"try",
"{",
"return",
"$",
"this",
"->",
"process",
"(",
"$",
"workCommand",
",",
"$",
"connectionName"... | Process the given job.
@param \Illuminate\Contracts\Queue\Job $job
@param string $connectionName
@param \Illuminate\Queue\WorkerOptions $options
@return void | [
"Process",
"the",
"given",
"job",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L276-L290 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.report | public function report(Exception $e)
{
try {
$logger = Zilf::$container->getShare('log');
} catch (Exception $ex) {
throw $e;
}
$logger->error($e->getMessage(), ['exception' => $e]);
} | php | public function report(Exception $e)
{
try {
$logger = Zilf::$container->getShare('log');
} catch (Exception $ex) {
throw $e;
}
$logger->error($e->getMessage(), ['exception' => $e]);
} | [
"public",
"function",
"report",
"(",
"Exception",
"$",
"e",
")",
"{",
"try",
"{",
"$",
"logger",
"=",
"Zilf",
"::",
"$",
"container",
"->",
"getShare",
"(",
"'log'",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"ex",
")",
"{",
"throw",
"$",
"e",
... | Report or log an exception.
@param \Exception $e
@return mixed
@throws \Exception | [
"Report",
"or",
"log",
"an",
"exception",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L300-L309 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.handleJobException | protected function handleJobException($workCommand, $connectionName, $job, WorkerOptions $options, $e)
{
try {
// First, we will go ahead and mark the job as failed if it will exceed the maximum
// attempts it is allowed to run the next time we process it. If so we will just
// go ahead and mark it as failed now so we do not have to release this again.
if (!$job->hasFailed()) {
$this->markJobAsFailedIfWillExceedMaxAttempts(
$connectionName, $job, (int)$options->maxTries, $e
);
}
if (!isset($this->jobs[$job->resolveName()])) {
$this->jobs[$job->resolveName()] = true;
$this->raiseExceptionOccurredJobEvent(
$workCommand, $connectionName, $job, $e
);
}
} finally {
// If we catch an exception, we will attempt to release the job back onto the queue
// so it is not lost entirely. This'll let the job be retried at a later time by
// another listener (or this same one). We will re-throw this exception after.
if (!$job->isDeleted() && !$job->isReleased() && !$job->hasFailed()) {
$job->release($options->delay);
}
}
throw $e;
} | php | protected function handleJobException($workCommand, $connectionName, $job, WorkerOptions $options, $e)
{
try {
// First, we will go ahead and mark the job as failed if it will exceed the maximum
// attempts it is allowed to run the next time we process it. If so we will just
// go ahead and mark it as failed now so we do not have to release this again.
if (!$job->hasFailed()) {
$this->markJobAsFailedIfWillExceedMaxAttempts(
$connectionName, $job, (int)$options->maxTries, $e
);
}
if (!isset($this->jobs[$job->resolveName()])) {
$this->jobs[$job->resolveName()] = true;
$this->raiseExceptionOccurredJobEvent(
$workCommand, $connectionName, $job, $e
);
}
} finally {
// If we catch an exception, we will attempt to release the job back onto the queue
// so it is not lost entirely. This'll let the job be retried at a later time by
// another listener (or this same one). We will re-throw this exception after.
if (!$job->isDeleted() && !$job->isReleased() && !$job->hasFailed()) {
$job->release($options->delay);
}
}
throw $e;
} | [
"protected",
"function",
"handleJobException",
"(",
"$",
"workCommand",
",",
"$",
"connectionName",
",",
"$",
"job",
",",
"WorkerOptions",
"$",
"options",
",",
"$",
"e",
")",
"{",
"try",
"{",
"// First, we will go ahead and mark the job as failed if it will exceed the m... | Handle an exception that occurred while the job was running.
@param string $connectionName
@param \Illuminate\Contracts\Queue\Job $job
@param \Illuminate\Queue\WorkerOptions $options
@param \Exception $e
@return void
@throws \Exception | [
"Handle",
"an",
"exception",
"that",
"occurred",
"while",
"the",
"job",
"was",
"running",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L372-L403 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.markJobAsFailedIfAlreadyExceedsMaxAttempts | protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries)
{
$maxTries = !is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
$timeoutAt = $job->timeoutAt();
if ($timeoutAt && Carbon::now()->getTimestamp() <= $timeoutAt) {
return;
}
if (!$timeoutAt && ($maxTries === 0 || $job->attempts() <= $maxTries)) {
return;
}
$this->failJob(
$connectionName, $job, $e = new MaxAttemptsExceededException(
$job->resolveName() . ' has been attempted too many times or run too long. The job may have previously timed out.'
)
);
throw $e;
} | php | protected function markJobAsFailedIfAlreadyExceedsMaxAttempts($connectionName, $job, $maxTries)
{
$maxTries = !is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
$timeoutAt = $job->timeoutAt();
if ($timeoutAt && Carbon::now()->getTimestamp() <= $timeoutAt) {
return;
}
if (!$timeoutAt && ($maxTries === 0 || $job->attempts() <= $maxTries)) {
return;
}
$this->failJob(
$connectionName, $job, $e = new MaxAttemptsExceededException(
$job->resolveName() . ' has been attempted too many times or run too long. The job may have previously timed out.'
)
);
throw $e;
} | [
"protected",
"function",
"markJobAsFailedIfAlreadyExceedsMaxAttempts",
"(",
"$",
"connectionName",
",",
"$",
"job",
",",
"$",
"maxTries",
")",
"{",
"$",
"maxTries",
"=",
"!",
"is_null",
"(",
"$",
"job",
"->",
"maxTries",
"(",
")",
")",
"?",
"$",
"job",
"->... | Mark the given job as failed if it has exceeded the maximum allowed attempts.
This will likely be because the job previously exceeded a timeout.
@param string $connectionName
@param \Illuminate\Contracts\Queue\Job $job
@param int $maxTries
@return void | [
"Mark",
"the",
"given",
"job",
"as",
"failed",
"if",
"it",
"has",
"exceeded",
"the",
"maximum",
"allowed",
"attempts",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L415-L436 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.markJobAsFailedIfWillExceedMaxAttempts | protected function markJobAsFailedIfWillExceedMaxAttempts($connectionName, $job, $maxTries, $e)
{
$maxTries = !is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
if ($job->timeoutAt() && $job->timeoutAt() <= Carbon::now()->getTimestamp()) {
$this->failJob($connectionName, $job, $e);
}
if ($maxTries > 0 && $job->attempts() >= $maxTries) {
$this->failJob($connectionName, $job, $e);
}
} | php | protected function markJobAsFailedIfWillExceedMaxAttempts($connectionName, $job, $maxTries, $e)
{
$maxTries = !is_null($job->maxTries()) ? $job->maxTries() : $maxTries;
if ($job->timeoutAt() && $job->timeoutAt() <= Carbon::now()->getTimestamp()) {
$this->failJob($connectionName, $job, $e);
}
if ($maxTries > 0 && $job->attempts() >= $maxTries) {
$this->failJob($connectionName, $job, $e);
}
} | [
"protected",
"function",
"markJobAsFailedIfWillExceedMaxAttempts",
"(",
"$",
"connectionName",
",",
"$",
"job",
",",
"$",
"maxTries",
",",
"$",
"e",
")",
"{",
"$",
"maxTries",
"=",
"!",
"is_null",
"(",
"$",
"job",
"->",
"maxTries",
"(",
")",
")",
"?",
"$... | Mark the given job as failed if it has exceeded the maximum allowed attempts.
@param string $connectionName
@param \Illuminate\Contracts\Queue\Job $job
@param int $maxTries
@param \Exception $e
@return void | [
"Mark",
"the",
"given",
"job",
"as",
"failed",
"if",
"it",
"has",
"exceeded",
"the",
"maximum",
"allowed",
"attempts",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L447-L458 |
txj123/zilf | src/Zilf/Queue/Worker.php | Worker.raiseExceptionOccurredJobEvent | protected function raiseExceptionOccurredJobEvent($workCommand, $connectionName, $job, $e)
{
$workCommand->writeOutput($job, 'failed');
$workCommand->logFailedJob(new JobFailed($connectionName, $job, $e));
} | php | protected function raiseExceptionOccurredJobEvent($workCommand, $connectionName, $job, $e)
{
$workCommand->writeOutput($job, 'failed');
$workCommand->logFailedJob(new JobFailed($connectionName, $job, $e));
} | [
"protected",
"function",
"raiseExceptionOccurredJobEvent",
"(",
"$",
"workCommand",
",",
"$",
"connectionName",
",",
"$",
"job",
",",
"$",
"e",
")",
"{",
"$",
"workCommand",
"->",
"writeOutput",
"(",
"$",
"job",
",",
"'failed'",
")",
";",
"$",
"workCommand",... | Raise the exception occurred queue job event.
@param string $connectionName
@param \Illuminate\Contracts\Queue\Job $job
@param \Exception $e
@return void | [
"Raise",
"the",
"exception",
"occurred",
"queue",
"job",
"event",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Queue/Worker.php#L505-L510 |
Syonix/log-viewer-lib | lib/Config.php | Config.lint | public static function lint($config, $verifyLogFiles = false)
{
$valid = true;
$checks = [];
// Valid YAML
$checks['valid_yaml'] = [
'message' => 'Is a valid YAML file',
];
try {
$config = self::parse($config);
$checks['valid_yaml']['status'] = 'ok';
} catch (\Exception $e) {
$valid = false;
$checks['valid_yaml']['status'] = 'fail';
$checks['valid_yaml']['error'] = $e->getMessage();
}
try {
// Valid structure
$checks['valid_structure'] = self::lintValidProperties($config);
if ($checks['valid_structure']['status'] == 'fail') {
throw new \Exception();
}
// Valid config values
$checks['valid_settings'] = self::lintValidSettingsValues($config);
if ($checks['valid_settings']['status'] == 'fail') {
throw new \Exception();
}
// Validate log collections (each)
$checks['log_collections'] = [
'message' => 'Checking log collections',
];
try {
foreach ($config['logs'] as $logCollectionName => $logCollection) {
$checks['log_collections']['sub_checks'][$logCollectionName] = self::lintLogCollection($logCollectionName, $logCollection);
if ($checks['log_collections']['sub_checks'][$logCollectionName]['status'] == 'fail') {
throw new \Exception();
}
}
foreach ($config['logs'] as $logCollectionName => $logCollection) {
$checks['log_collections']['checks'][$logCollectionName] = self::lintLogCollection($logCollectionName, $logCollection, $verifyLogFiles);
if ($checks['log_collections']['checks'][$logCollectionName]['status'] == 'fail') {
throw new \Exception();
}
}
$checks['log_collections']['status'] = 'ok';
} catch (\Exception $e) {
$checks['log_collections']['status'] = 'fail';
$checks['log_collections']['error'] = $e->getMessage();
$valid = false;
}
} catch (\Exception $e) {
$valid = false;
}
return [
'valid' => $valid,
'checks' => $checks,
];
} | php | public static function lint($config, $verifyLogFiles = false)
{
$valid = true;
$checks = [];
// Valid YAML
$checks['valid_yaml'] = [
'message' => 'Is a valid YAML file',
];
try {
$config = self::parse($config);
$checks['valid_yaml']['status'] = 'ok';
} catch (\Exception $e) {
$valid = false;
$checks['valid_yaml']['status'] = 'fail';
$checks['valid_yaml']['error'] = $e->getMessage();
}
try {
// Valid structure
$checks['valid_structure'] = self::lintValidProperties($config);
if ($checks['valid_structure']['status'] == 'fail') {
throw new \Exception();
}
// Valid config values
$checks['valid_settings'] = self::lintValidSettingsValues($config);
if ($checks['valid_settings']['status'] == 'fail') {
throw new \Exception();
}
// Validate log collections (each)
$checks['log_collections'] = [
'message' => 'Checking log collections',
];
try {
foreach ($config['logs'] as $logCollectionName => $logCollection) {
$checks['log_collections']['sub_checks'][$logCollectionName] = self::lintLogCollection($logCollectionName, $logCollection);
if ($checks['log_collections']['sub_checks'][$logCollectionName]['status'] == 'fail') {
throw new \Exception();
}
}
foreach ($config['logs'] as $logCollectionName => $logCollection) {
$checks['log_collections']['checks'][$logCollectionName] = self::lintLogCollection($logCollectionName, $logCollection, $verifyLogFiles);
if ($checks['log_collections']['checks'][$logCollectionName]['status'] == 'fail') {
throw new \Exception();
}
}
$checks['log_collections']['status'] = 'ok';
} catch (\Exception $e) {
$checks['log_collections']['status'] = 'fail';
$checks['log_collections']['error'] = $e->getMessage();
$valid = false;
}
} catch (\Exception $e) {
$valid = false;
}
return [
'valid' => $valid,
'checks' => $checks,
];
} | [
"public",
"static",
"function",
"lint",
"(",
"$",
"config",
",",
"$",
"verifyLogFiles",
"=",
"false",
")",
"{",
"$",
"valid",
"=",
"true",
";",
"$",
"checks",
"=",
"[",
"]",
";",
"// Valid YAML",
"$",
"checks",
"[",
"'valid_yaml'",
"]",
"=",
"[",
"'m... | Lints a config file for syntactical and semantical correctness.
@param array $config The parsed configuration to lint
@param bool $verifyLogFiles Also verfy whether the log files are accessible
@return array | [
"Lints",
"a",
"config",
"file",
"for",
"syntactical",
"and",
"semantical",
"correctness",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/Config.php#L37-L99 |
Syonix/log-viewer-lib | lib/Config.php | Config.get | public function get($property = null)
{
if ($property === null || $property == '') {
return $this->config;
}
$tree = explode('.', $property);
$node = $this->config;
foreach ($tree as $workingNode) {
if (!array_key_exists($workingNode, $node)) {
$actualNode = null;
foreach ($node as $testNodeKey => $testNode) {
if (\URLify::filter($testNodeKey) == $workingNode) {
$actualNode = $testNodeKey;
}
}
if ($actualNode === null) {
throw new \InvalidArgumentException('The property "'.$property
.'" was not found. Failed while getting node "'.$workingNode.'"');
}
$workingNode = $actualNode;
}
$node = $node[$workingNode];
}
return $node;
} | php | public function get($property = null)
{
if ($property === null || $property == '') {
return $this->config;
}
$tree = explode('.', $property);
$node = $this->config;
foreach ($tree as $workingNode) {
if (!array_key_exists($workingNode, $node)) {
$actualNode = null;
foreach ($node as $testNodeKey => $testNode) {
if (\URLify::filter($testNodeKey) == $workingNode) {
$actualNode = $testNodeKey;
}
}
if ($actualNode === null) {
throw new \InvalidArgumentException('The property "'.$property
.'" was not found. Failed while getting node "'.$workingNode.'"');
}
$workingNode = $actualNode;
}
$node = $node[$workingNode];
}
return $node;
} | [
"public",
"function",
"get",
"(",
"$",
"property",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"property",
"===",
"null",
"||",
"$",
"property",
"==",
"''",
")",
"{",
"return",
"$",
"this",
"->",
"config",
";",
"}",
"$",
"tree",
"=",
"explode",
"(",
"... | Returns a config property if it exists and throws an exception if not.
@param string|null $property Dot-separated property (e.g. "date_format" or "logs.collection.log_file")
@throws \InvalidArgumentException
@return mixed | [
"Returns",
"a",
"config",
"property",
"if",
"it",
"exists",
"and",
"throws",
"an",
"exception",
"if",
"not",
"."
] | train | https://github.com/Syonix/log-viewer-lib/blob/5212208bf2f0174eb5d0408d2d3028db4d478a74/lib/Config.php#L352-L378 |
oscarotero/uploader | src/Uploader.php | Uploader.setDestination | public function setDestination($destination)
{
if ($destination instanceof Closure) {
$this->callbacks['destination'] = $destination;
} else {
$this->options = self::parsePath($destination) + $this->options;
}
return $this;
} | php | public function setDestination($destination)
{
if ($destination instanceof Closure) {
$this->callbacks['destination'] = $destination;
} else {
$this->options = self::parsePath($destination) + $this->options;
}
return $this;
} | [
"public",
"function",
"setDestination",
"(",
"$",
"destination",
")",
"{",
"if",
"(",
"$",
"destination",
"instanceof",
"Closure",
")",
"{",
"$",
"this",
"->",
"callbacks",
"[",
"'destination'",
"]",
"=",
"$",
"destination",
";",
"}",
"else",
"{",
"$",
"... | Set the destination of the file. It includes the directory, filename and extension.
@param string|Closure $destination
@return $this | [
"Set",
"the",
"destination",
"of",
"the",
"file",
".",
"It",
"includes",
"the",
"directory",
"filename",
"and",
"extension",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L161-L170 |
oscarotero/uploader | src/Uploader.php | Uploader.getDestination | public function getDestination($absolute = false)
{
return self::fixPath(($absolute ? '/'.$this->cwd : ''), $this->getDirectory(), $this->getPrefix().$this->getFilename().'.'.$this->getExtension());
} | php | public function getDestination($absolute = false)
{
return self::fixPath(($absolute ? '/'.$this->cwd : ''), $this->getDirectory(), $this->getPrefix().$this->getFilename().'.'.$this->getExtension());
} | [
"public",
"function",
"getDestination",
"(",
"$",
"absolute",
"=",
"false",
")",
"{",
"return",
"self",
"::",
"fixPath",
"(",
"(",
"$",
"absolute",
"?",
"'/'",
".",
"$",
"this",
"->",
"cwd",
":",
"''",
")",
",",
"$",
"this",
"->",
"getDirectory",
"("... | Returns the file destination.
@param bool $absolute Whether or not returns the cwd
@return string | [
"Returns",
"the",
"file",
"destination",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L179-L182 |
oscarotero/uploader | src/Uploader.php | Uploader.with | public function with($original, $adapter = null)
{
$new = clone $this;
$new->original = $original;
$new->adapter = $adapter;
if ($new->adapter === null) {
foreach ($new->adapters as $each) {
if ($each::check($original)) {
$new->adapter = $each;
break;
}
}
}
if ($new->adapter === null || !class_exists($new->adapter)) {
throw new \InvalidArgumentException('No valid adapter found');
}
return $new;
} | php | public function with($original, $adapter = null)
{
$new = clone $this;
$new->original = $original;
$new->adapter = $adapter;
if ($new->adapter === null) {
foreach ($new->adapters as $each) {
if ($each::check($original)) {
$new->adapter = $each;
break;
}
}
}
if ($new->adapter === null || !class_exists($new->adapter)) {
throw new \InvalidArgumentException('No valid adapter found');
}
return $new;
} | [
"public",
"function",
"with",
"(",
"$",
"original",
",",
"$",
"adapter",
"=",
"null",
")",
"{",
"$",
"new",
"=",
"clone",
"$",
"this",
";",
"$",
"new",
"->",
"original",
"=",
"$",
"original",
";",
"$",
"new",
"->",
"adapter",
"=",
"$",
"adapter",
... | Set the original source.
@param mixed $original
@param null|string $adapter
@throws \InvalidArgumentException On error
@return Uploader A new cloned copy with the source and adapter configured | [
"Set",
"the",
"original",
"source",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L260-L280 |
oscarotero/uploader | src/Uploader.php | Uploader.save | public function save()
{
if (!$this->original || empty($this->adapter)) {
throw new \Exception('Original source is not defined');
}
call_user_func("{$this->adapter}::fixDestination", $this, $this->original);
//Execute callbacks
foreach ($this->callbacks as $name => $callback) {
if ($callback) {
if ($name === 'destination') {
$this->setDestination($callback($this));
} else {
$this->options[$name] = $callback($this);
}
}
}
$destination = $this->getDestination(true);
if (!$this->getOverwrite() && is_file($destination)) {
throw new \RuntimeException(sprintf('Cannot override the file "%s"', $destination));
}
if ($this->getCreateDir() && !is_dir(dirname($destination))) {
if (mkdir(dirname($destination), 0777, true) === false) {
throw new \RuntimeException(sprintf('Unable to create the directory "%s"', dirname($destination)));
}
}
call_user_func("{$this->adapter}::save", $this->original, $destination);
return $this;
} | php | public function save()
{
if (!$this->original || empty($this->adapter)) {
throw new \Exception('Original source is not defined');
}
call_user_func("{$this->adapter}::fixDestination", $this, $this->original);
//Execute callbacks
foreach ($this->callbacks as $name => $callback) {
if ($callback) {
if ($name === 'destination') {
$this->setDestination($callback($this));
} else {
$this->options[$name] = $callback($this);
}
}
}
$destination = $this->getDestination(true);
if (!$this->getOverwrite() && is_file($destination)) {
throw new \RuntimeException(sprintf('Cannot override the file "%s"', $destination));
}
if ($this->getCreateDir() && !is_dir(dirname($destination))) {
if (mkdir(dirname($destination), 0777, true) === false) {
throw new \RuntimeException(sprintf('Unable to create the directory "%s"', dirname($destination)));
}
}
call_user_func("{$this->adapter}::save", $this->original, $destination);
return $this;
} | [
"public",
"function",
"save",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"original",
"||",
"empty",
"(",
"$",
"this",
"->",
"adapter",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Original source is not defined'",
")",
";",
"}",
"cal... | Save the file.
@throws \Exception On error
@return $this | [
"Save",
"the",
"file",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L289-L323 |
oscarotero/uploader | src/Uploader.php | Uploader.setOption | protected function setOption($name, $value)
{
if ($value instanceof Closure) {
$this->callbacks[$name] = $value;
} else {
$this->options[$name] = $value;
}
return $this;
} | php | protected function setOption($name, $value)
{
if ($value instanceof Closure) {
$this->callbacks[$name] = $value;
} else {
$this->options[$name] = $value;
}
return $this;
} | [
"protected",
"function",
"setOption",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"instanceof",
"Closure",
")",
"{",
"$",
"this",
"->",
"callbacks",
"[",
"$",
"name",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
... | Saves an option.
@param string $name
@param mixed $value
@return $this | [
"Saves",
"an",
"option",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L333-L342 |
oscarotero/uploader | src/Uploader.php | Uploader.parsePath | public static function parsePath($path)
{
$components = pathinfo($path);
return [
'directory' => isset($components['dirname']) ? self::fixPath($components['dirname']) : null,
'filename' => isset($components['filename']) ? $components['filename'] : null,
'extension' => isset($components['extension']) ? $components['extension'] : null,
];
} | php | public static function parsePath($path)
{
$components = pathinfo($path);
return [
'directory' => isset($components['dirname']) ? self::fixPath($components['dirname']) : null,
'filename' => isset($components['filename']) ? $components['filename'] : null,
'extension' => isset($components['extension']) ? $components['extension'] : null,
];
} | [
"public",
"static",
"function",
"parsePath",
"(",
"$",
"path",
")",
"{",
"$",
"components",
"=",
"pathinfo",
"(",
"$",
"path",
")",
";",
"return",
"[",
"'directory'",
"=>",
"isset",
"(",
"$",
"components",
"[",
"'dirname'",
"]",
")",
"?",
"self",
"::",... | Helper function used to parse a path.
@param string $path
@return array With 3 keys: directory, filename and extension | [
"Helper",
"function",
"used",
"to",
"parse",
"a",
"path",
"."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L351-L360 |
oscarotero/uploader | src/Uploader.php | Uploader.fixPath | private static function fixPath($path)
{
if (func_num_args() > 1) {
return self::fixPath(implode('/', func_get_args()));
}
$replace = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
do {
$path = preg_replace($replace, '/', $path, -1, $n);
} while ($n > 0);
return $path;
} | php | private static function fixPath($path)
{
if (func_num_args() > 1) {
return self::fixPath(implode('/', func_get_args()));
}
$replace = ['#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'];
do {
$path = preg_replace($replace, '/', $path, -1, $n);
} while ($n > 0);
return $path;
} | [
"private",
"static",
"function",
"fixPath",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"func_num_args",
"(",
")",
">",
"1",
")",
"{",
"return",
"self",
"::",
"fixPath",
"(",
"implode",
"(",
"'/'",
",",
"func_get_args",
"(",
")",
")",
")",
";",
"}",
"$"... | Resolve paths with ../, //, etc...
@param string $path
@return string | [
"Resolve",
"paths",
"with",
"..",
"/",
"//",
"etc",
"..."
] | train | https://github.com/oscarotero/uploader/blob/94f1461d324b467e2047568fcc5d88d53ab9ac8f/src/Uploader.php#L369-L382 |
txj123/zilf | src/Zilf/Db/Schema.php | Schema.refresh | public function refresh()
{
/* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
TagDependency::invalidate($cache, $this->getCacheTag());
}
$this->_tableNames = [];
$this->_tableMetadata = [];
} | php | public function refresh()
{
/* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
TagDependency::invalidate($cache, $this->getCacheTag());
}
$this->_tableNames = [];
$this->_tableMetadata = [];
} | [
"public",
"function",
"refresh",
"(",
")",
"{",
"/* @var $cache CacheInterface */",
"$",
"cache",
"=",
"is_string",
"(",
"$",
"this",
"->",
"db",
"->",
"schemaCache",
")",
"?",
"Zilf",
"::",
"$",
"app",
"->",
"get",
"(",
"$",
"this",
"->",
"db",
"->",
... | Refreshes the schema.
This method cleans up all cached table schemas so that they can be re-created later
to reflect the database schema change. | [
"Refreshes",
"the",
"schema",
".",
"This",
"method",
"cleans",
"up",
"all",
"cached",
"table",
"schemas",
"so",
"that",
"they",
"can",
"be",
"re",
"-",
"created",
"later",
"to",
"reflect",
"the",
"database",
"schema",
"change",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Schema.php#L291-L300 |
txj123/zilf | src/Zilf/Db/Schema.php | Schema.refreshTableSchema | public function refreshTableSchema($name)
{
$rawName = $this->getRawTableName($name);
unset($this->_tableMetadata[$rawName]);
$this->_tableNames = [];
/* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
$cache->delete($this->getCacheKey($rawName));
}
} | php | public function refreshTableSchema($name)
{
$rawName = $this->getRawTableName($name);
unset($this->_tableMetadata[$rawName]);
$this->_tableNames = [];
/* @var $cache CacheInterface */
$cache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($this->db->enableSchemaCache && $cache instanceof CacheInterface) {
$cache->delete($this->getCacheKey($rawName));
}
} | [
"public",
"function",
"refreshTableSchema",
"(",
"$",
"name",
")",
"{",
"$",
"rawName",
"=",
"$",
"this",
"->",
"getRawTableName",
"(",
"$",
"name",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"_tableMetadata",
"[",
"$",
"rawName",
"]",
")",
";",
"$",
... | Refreshes the particular table schema.
This method cleans up cached table schema so that it can be re-created later
to reflect the database schema change.
@param string $name table name.
@since 2.0.6 | [
"Refreshes",
"the",
"particular",
"table",
"schema",
".",
"This",
"method",
"cleans",
"up",
"cached",
"table",
"schema",
"so",
"that",
"it",
"can",
"be",
"re",
"-",
"created",
"later",
"to",
"reflect",
"the",
"database",
"schema",
"change",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Schema.php#L310-L320 |
txj123/zilf | src/Zilf/Db/Schema.php | Schema.convertException | public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$exceptionClass = '\Zilf\Db\Exception';
foreach ($this->exceptionMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
} | php | public function convertException(\Exception $e, $rawSql)
{
if ($e instanceof Exception) {
return $e;
}
$exceptionClass = '\Zilf\Db\Exception';
foreach ($this->exceptionMap as $error => $class) {
if (strpos($e->getMessage(), $error) !== false) {
$exceptionClass = $class;
}
}
$message = $e->getMessage() . "\nThe SQL being executed was: $rawSql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
return new $exceptionClass($message, $errorInfo, (int) $e->getCode(), $e);
} | [
"public",
"function",
"convertException",
"(",
"\\",
"Exception",
"$",
"e",
",",
"$",
"rawSql",
")",
"{",
"if",
"(",
"$",
"e",
"instanceof",
"Exception",
")",
"{",
"return",
"$",
"e",
";",
"}",
"$",
"exceptionClass",
"=",
"'\\Zilf\\Db\\Exception'",
";",
... | Converts a DB exception to a more concrete one if possible.
@param \Exception $e
@param string $rawSql SQL that produced exception
@return Exception | [
"Converts",
"a",
"DB",
"exception",
"to",
"a",
"more",
"concrete",
"one",
"if",
"possible",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Schema.php#L678-L693 |
txj123/zilf | src/Zilf/Db/Schema.php | Schema.getTableMetadata | protected function getTableMetadata($name, $type, $refresh)
{
$cache = null;
if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
$schemaCache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($schemaCache instanceof CacheInterface) {
$cache = $schemaCache;
}
}
$rawName = $this->getRawTableName($name);
if (!isset($this->_tableMetadata[$rawName])) {
$this->loadTableMetadataFromCache($cache, $rawName);
}
if ($refresh || !array_key_exists($type, $this->_tableMetadata[$rawName])) {
$this->_tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
$this->saveTableMetadataToCache($cache, $rawName);
}
return $this->_tableMetadata[$rawName][$type];
} | php | protected function getTableMetadata($name, $type, $refresh)
{
$cache = null;
if ($this->db->enableSchemaCache && !in_array($name, $this->db->schemaCacheExclude, true)) {
$schemaCache = is_string($this->db->schemaCache) ? Zilf::$app->get($this->db->schemaCache, false) : $this->db->schemaCache;
if ($schemaCache instanceof CacheInterface) {
$cache = $schemaCache;
}
}
$rawName = $this->getRawTableName($name);
if (!isset($this->_tableMetadata[$rawName])) {
$this->loadTableMetadataFromCache($cache, $rawName);
}
if ($refresh || !array_key_exists($type, $this->_tableMetadata[$rawName])) {
$this->_tableMetadata[$rawName][$type] = $this->{'loadTable' . ucfirst($type)}($rawName);
$this->saveTableMetadataToCache($cache, $rawName);
}
return $this->_tableMetadata[$rawName][$type];
} | [
"protected",
"function",
"getTableMetadata",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"refresh",
")",
"{",
"$",
"cache",
"=",
"null",
";",
"if",
"(",
"$",
"this",
"->",
"db",
"->",
"enableSchemaCache",
"&&",
"!",
"in_array",
"(",
"$",
"name",
",... | Returns the metadata of the given type for the given table.
If there's no metadata in the cache, this method will call
a `'loadTable' . ucfirst($type)` named method with the table name to obtain the metadata.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param string $type metadata type.
@param bool $refresh whether to reload the table metadata even if it is found in the cache.
@return mixed metadata.
@since 2.0.13 | [
"Returns",
"the",
"metadata",
"of",
"the",
"given",
"type",
"for",
"the",
"given",
"table",
".",
"If",
"there",
"s",
"no",
"metadata",
"in",
"the",
"cache",
"this",
"method",
"will",
"call",
"a",
"loadTable",
".",
"ucfirst",
"(",
"$type",
")",
"named",
... | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/Db/Schema.php#L767-L786 |
dave-redfern/laravel-doctrine-tenancy | src/Console/TenantRouteClearCommand.php | TenantRouteClearCommand.fire | public function fire()
{
$this->resolveTenantRoutes($this->argument('domain'));
$this->files->delete($this->laravel->getCachedRoutesPath());
$this->info('Tenant route cache cleared!');
} | php | public function fire()
{
$this->resolveTenantRoutes($this->argument('domain'));
$this->files->delete($this->laravel->getCachedRoutesPath());
$this->info('Tenant route cache cleared!');
} | [
"public",
"function",
"fire",
"(",
")",
"{",
"$",
"this",
"->",
"resolveTenantRoutes",
"(",
"$",
"this",
"->",
"argument",
"(",
"'domain'",
")",
")",
";",
"$",
"this",
"->",
"files",
"->",
"delete",
"(",
"$",
"this",
"->",
"laravel",
"->",
"getCachedRo... | Execute the console command.
@return void | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Console/TenantRouteClearCommand.php#L75-L82 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client/Adapter/Socket.php | Zend_Http_Client_Adapter_Socket.connect | public function connect($host, $port = 80, $secure = false)
{
// If the URI should be accessed via SSL, prepend the Hostname with ssl://
$host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
// If we are connected to the wrong host, disconnect first
if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
if (is_resource($this->socket)) { $this->close();
}
}
// Now, if we are not connected, connect
if (! is_resource($this->socket) || ! $this->config['keepalive']) {
$context = stream_context_create();
if ($secure) {
if ($this->config['sslcert'] !== null) {
if (! stream_context_set_option(
$context, 'ssl', 'local_cert',
$this->config['sslcert']
)
) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
}
}
if ($this->config['sslpassphrase'] !== null) {
if (! stream_context_set_option(
$context, 'ssl', 'passphrase',
$this->config['sslpassphrase']
)
) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
}
}
}
$flags = STREAM_CLIENT_CONNECT;
if ($this->config['persistent']) { $flags |= STREAM_CLIENT_PERSISTENT;
}
$this->socket = @stream_socket_client(
$host . ':' . $port,
$errno,
$errstr,
(int) $this->config['timeout'],
$flags,
$context
);
if (! $this->socket) {
$this->close();
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr
);
}
// Set the stream timeout
if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
}
// Update connected_to
$this->connected_to = array($host, $port);
}
} | php | public function connect($host, $port = 80, $secure = false)
{
// If the URI should be accessed via SSL, prepend the Hostname with ssl://
$host = ($secure ? $this->config['ssltransport'] : 'tcp') . '://' . $host;
// If we are connected to the wrong host, disconnect first
if (($this->connected_to[0] != $host || $this->connected_to[1] != $port)) {
if (is_resource($this->socket)) { $this->close();
}
}
// Now, if we are not connected, connect
if (! is_resource($this->socket) || ! $this->config['keepalive']) {
$context = stream_context_create();
if ($secure) {
if ($this->config['sslcert'] !== null) {
if (! stream_context_set_option(
$context, 'ssl', 'local_cert',
$this->config['sslcert']
)
) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set sslcert option');
}
}
if ($this->config['sslpassphrase'] !== null) {
if (! stream_context_set_option(
$context, 'ssl', 'passphrase',
$this->config['sslpassphrase']
)
) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set sslpassphrase option');
}
}
}
$flags = STREAM_CLIENT_CONNECT;
if ($this->config['persistent']) { $flags |= STREAM_CLIENT_PERSISTENT;
}
$this->socket = @stream_socket_client(
$host . ':' . $port,
$errno,
$errstr,
(int) $this->config['timeout'],
$flags,
$context
);
if (! $this->socket) {
$this->close();
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Unable to Connect to ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr
);
}
// Set the stream timeout
if (! stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
}
// Update connected_to
$this->connected_to = array($host, $port);
}
} | [
"public",
"function",
"connect",
"(",
"$",
"host",
",",
"$",
"port",
"=",
"80",
",",
"$",
"secure",
"=",
"false",
")",
"{",
"// If the URI should be accessed via SSL, prepend the Hostname with ssl://",
"$",
"host",
"=",
"(",
"$",
"secure",
"?",
"$",
"this",
"-... | Connect to the remote server
@param string $host
@param int $port
@param boolean $secure
@param int $timeout | [
"Connect",
"to",
"the",
"remote",
"server"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client/Adapter/Socket.php#L106-L172 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client/Adapter/Socket.php | Zend_Http_Client_Adapter_Socket.read | public function read()
{
// First, read headers only
$response = '';
$gotStatus = false;
while ($line = @fgets($this->socket)) {
$gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
if ($gotStatus) {
$response .= $line;
if (!chop($line)) { break;
}
}
}
$statusCode = Zend_Http_Response::extractCode($response);
// Handle 100 and 101 responses internally by restarting the read again
if ($statusCode == 100 || $statusCode == 101) { return $this->read();
}
/**
* Responses to HEAD requests and 204 or 304 responses are not expected
* to have a body - stop reading here
*/
if ($statusCode == 304 || $statusCode == 204
|| $this->method == Zend_Http_Client::HEAD
) { return $response;
}
// Check headers to see what kind of connection / transfer encoding we have
$headers = Zend_Http_Response::extractHeaders($response);
// if the connection is set to close, just read until socket closes
if (isset($headers['connection']) && $headers['connection'] == 'close') {
while ($buff = @fread($this->socket, 8192)) {
$response .= $buff;
}
$this->close();
// Else, if we got a transfer-encoding header (chunked body)
} elseif (isset($headers['transfer-encoding'])) {
if ($headers['transfer-encoding'] == 'chunked') {
do {
$chunk = '';
$line = @fgets($this->socket);
$chunk .= $line;
$hexchunksize = ltrim(chop($line), '0');
$hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0;
$chunksize = hexdec(chop($line));
if (dechex($chunksize) != $hexchunksize) {
@fclose($this->socket);
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Invalid chunk size "' .
$hexchunksize . '" unable to read chunked body'
);
}
$left_to_read = $chunksize;
while ($left_to_read > 0) {
$line = @fread($this->socket, $left_to_read);
$chunk .= $line;
$left_to_read -= strlen($line);
}
$chunk .= @fgets($this->socket);
$response .= $chunk;
} while ($chunksize > 0);
} else {
throw new Zend_Http_Client_Adapter_Exception(
'Cannot handle "' .
$headers['transfer-encoding'] . '" transfer encoding'
);
}
// Else, if we got the content-length header, read this number of bytes
} elseif (isset($headers['content-length'])) {
$left_to_read = $headers['content-length'];
$chunk = '';
while ($left_to_read > 0) {
$chunk = @fread($this->socket, $left_to_read);
$left_to_read -= strlen($chunk);
$response .= $chunk;
}
// Fallback: just read the response (should not happen)
} else {
while ($buff = @fread($this->socket, 8192)) {
$response .= $buff;
}
$this->close();
}
return $response;
} | php | public function read()
{
// First, read headers only
$response = '';
$gotStatus = false;
while ($line = @fgets($this->socket)) {
$gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
if ($gotStatus) {
$response .= $line;
if (!chop($line)) { break;
}
}
}
$statusCode = Zend_Http_Response::extractCode($response);
// Handle 100 and 101 responses internally by restarting the read again
if ($statusCode == 100 || $statusCode == 101) { return $this->read();
}
/**
* Responses to HEAD requests and 204 or 304 responses are not expected
* to have a body - stop reading here
*/
if ($statusCode == 304 || $statusCode == 204
|| $this->method == Zend_Http_Client::HEAD
) { return $response;
}
// Check headers to see what kind of connection / transfer encoding we have
$headers = Zend_Http_Response::extractHeaders($response);
// if the connection is set to close, just read until socket closes
if (isset($headers['connection']) && $headers['connection'] == 'close') {
while ($buff = @fread($this->socket, 8192)) {
$response .= $buff;
}
$this->close();
// Else, if we got a transfer-encoding header (chunked body)
} elseif (isset($headers['transfer-encoding'])) {
if ($headers['transfer-encoding'] == 'chunked') {
do {
$chunk = '';
$line = @fgets($this->socket);
$chunk .= $line;
$hexchunksize = ltrim(chop($line), '0');
$hexchunksize = strlen($hexchunksize) ? strtolower($hexchunksize) : 0;
$chunksize = hexdec(chop($line));
if (dechex($chunksize) != $hexchunksize) {
@fclose($this->socket);
include_once 'Zend/Http/Client/Adapter/Exception.php';
throw new Zend_Http_Client_Adapter_Exception(
'Invalid chunk size "' .
$hexchunksize . '" unable to read chunked body'
);
}
$left_to_read = $chunksize;
while ($left_to_read > 0) {
$line = @fread($this->socket, $left_to_read);
$chunk .= $line;
$left_to_read -= strlen($line);
}
$chunk .= @fgets($this->socket);
$response .= $chunk;
} while ($chunksize > 0);
} else {
throw new Zend_Http_Client_Adapter_Exception(
'Cannot handle "' .
$headers['transfer-encoding'] . '" transfer encoding'
);
}
// Else, if we got the content-length header, read this number of bytes
} elseif (isset($headers['content-length'])) {
$left_to_read = $headers['content-length'];
$chunk = '';
while ($left_to_read > 0) {
$chunk = @fread($this->socket, $left_to_read);
$left_to_read -= strlen($chunk);
$response .= $chunk;
}
// Fallback: just read the response (should not happen)
} else {
while ($buff = @fread($this->socket, 8192)) {
$response .= $buff;
}
$this->close();
}
return $response;
} | [
"public",
"function",
"read",
"(",
")",
"{",
"// First, read headers only",
"$",
"response",
"=",
"''",
";",
"$",
"gotStatus",
"=",
"false",
";",
"while",
"(",
"$",
"line",
"=",
"@",
"fgets",
"(",
"$",
"this",
"->",
"socket",
")",
")",
"{",
"$",
"got... | Read response from server
@return string | [
"Read",
"response",
"from",
"server"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/Client/Adapter/Socket.php#L230-L328 |
krafthaus/bauhaus | src/KraftHaus/Bauhaus/Field/IdentifierField.php | IdentifierField.render | public function render()
{
return View::make('krafthaus/bauhaus::models.fields._identifier')
->with('model', $this->getAdmin()->getModel())
->with('row', $this->getRowId())
->with('value', $this->getValue());
} | php | public function render()
{
return View::make('krafthaus/bauhaus::models.fields._identifier')
->with('model', $this->getAdmin()->getModel())
->with('row', $this->getRowId())
->with('value', $this->getValue());
} | [
"public",
"function",
"render",
"(",
")",
"{",
"return",
"View",
"::",
"make",
"(",
"'krafthaus/bauhaus::models.fields._identifier'",
")",
"->",
"with",
"(",
"'model'",
",",
"$",
"this",
"->",
"getAdmin",
"(",
")",
"->",
"getModel",
"(",
")",
")",
"->",
"w... | Render the field.
@access public
@return mixed|string | [
"Render",
"the",
"field",
"."
] | train | https://github.com/krafthaus/bauhaus/blob/02b6c5f4f7e5b5748d5300ab037feaff2a84ca80/src/KraftHaus/Bauhaus/Field/IdentifierField.php#L30-L36 |
dave-redfern/laravel-doctrine-tenancy | src/Http/Middleware/TenantRouteResolver.php | TenantRouteResolver.boot | public function boot()
{
foreach ($this->app->make('config')->get('tenancy.multi_site.router.patterns', []) as $name => $pattern) {
Route::pattern($name, $pattern);
}
parent::boot();
} | php | public function boot()
{
foreach ($this->app->make('config')->get('tenancy.multi_site.router.patterns', []) as $name => $pattern) {
Route::pattern($name, $pattern);
}
parent::boot();
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"'config'",
")",
"->",
"get",
"(",
"'tenancy.multi_site.router.patterns'",
",",
"[",
"]",
")",
"as",
"$",
"name",
"=>",
"$",
"pattern",
")",
"{",
... | Define your route model bindings, pattern filters, etc.
@return void | [
"Define",
"your",
"route",
"model",
"bindings",
"pattern",
"filters",
"etc",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Http/Middleware/TenantRouteResolver.php#L119-L126 |
dave-redfern/laravel-doctrine-tenancy | src/Http/Middleware/TenantRouteResolver.php | TenantRouteResolver.map | public function map(Router $router)
{
/** @var Tenant $tenant */
$tenant = $this->app->make('auth.tenant');
$router->group(
['namespace' => $this->namespace],
function ($router) use ($tenant) {
$tries = ['routes'];
if ($tenant->getTenantOwner() instanceof DomainAwareTenantParticipant) {
array_unshift($tries, $tenant->getTenantOwner()->getDomain());
}
if ($tenant->getTenantCreator() instanceof DomainAwareTenantParticipant) {
array_unshift($tries, $tenant->getTenantCreator()->getDomain());
}
foreach ($tries as $file) {
$path = app_path(sprintf('Http/%s.php', $file));
if (file_exists($path)) {
require_once $path;
return;
}
}
throw new \RuntimeException('No routes found in: ' . implode(', ', $tries));
}
);
} | php | public function map(Router $router)
{
/** @var Tenant $tenant */
$tenant = $this->app->make('auth.tenant');
$router->group(
['namespace' => $this->namespace],
function ($router) use ($tenant) {
$tries = ['routes'];
if ($tenant->getTenantOwner() instanceof DomainAwareTenantParticipant) {
array_unshift($tries, $tenant->getTenantOwner()->getDomain());
}
if ($tenant->getTenantCreator() instanceof DomainAwareTenantParticipant) {
array_unshift($tries, $tenant->getTenantCreator()->getDomain());
}
foreach ($tries as $file) {
$path = app_path(sprintf('Http/%s.php', $file));
if (file_exists($path)) {
require_once $path;
return;
}
}
throw new \RuntimeException('No routes found in: ' . implode(', ', $tries));
}
);
} | [
"public",
"function",
"map",
"(",
"Router",
"$",
"router",
")",
"{",
"/** @var Tenant $tenant */",
"$",
"tenant",
"=",
"$",
"this",
"->",
"app",
"->",
"make",
"(",
"'auth.tenant'",
")",
";",
"$",
"router",
"->",
"group",
"(",
"[",
"'namespace'",
"=>",
"$... | Define the routes for the application.
@param \Illuminate\Routing\Router $router
@return void | [
"Define",
"the",
"routes",
"for",
"the",
"application",
"."
] | train | https://github.com/dave-redfern/laravel-doctrine-tenancy/blob/3307fc57ad64d5a4dd5dfb235e19b301661255f9/src/Http/Middleware/TenantRouteResolver.php#L135-L162 |
willemo/flightstats | src/Api/FlightStatus.php | FlightStatus.getFlightStatusById | public function getFlightStatusById($flightId, array $queryParams = [])
{
$endpoint = 'flight/status/' . $flightId;
$response = $this->sendRequest($endpoint, $queryParams);
return $this->parseResponse($response);
} | php | public function getFlightStatusById($flightId, array $queryParams = [])
{
$endpoint = 'flight/status/' . $flightId;
$response = $this->sendRequest($endpoint, $queryParams);
return $this->parseResponse($response);
} | [
"public",
"function",
"getFlightStatusById",
"(",
"$",
"flightId",
",",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"$",
"endpoint",
"=",
"'flight/status/'",
".",
"$",
"flightId",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"sendRequest",
"(",
... | Get the flight status from a flight associated with provided Flight ID.
@param string $flightId FlightStats' Flight ID number for the desired
flight
@param array $queryParams Query parameters to add to the request
@return array The response from the API | [
"Get",
"the",
"flight",
"status",
"from",
"a",
"flight",
"associated",
"with",
"provided",
"Flight",
"ID",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/Api/FlightStatus.php#L37-L44 |
willemo/flightstats | src/Api/FlightStatus.php | FlightStatus.getFlightStatusByArrivalDate | public function getFlightStatusByArrivalDate(
$carrier,
$flight,
DateTime $date,
array $queryParams = []
) {
$endpoint = sprintf(
'flight/status/%s/%s/arr/%s',
$carrier,
$flight,
$date->format('Y/n/j')
);
if (!isset($queryParams['utc'])) {
$queryParams['utc'] = $this->flexClient->getConfig('use_utc_time');
}
$response = $this->sendRequest($endpoint, $queryParams);
return $this->parseResponse($response);
} | php | public function getFlightStatusByArrivalDate(
$carrier,
$flight,
DateTime $date,
array $queryParams = []
) {
$endpoint = sprintf(
'flight/status/%s/%s/arr/%s',
$carrier,
$flight,
$date->format('Y/n/j')
);
if (!isset($queryParams['utc'])) {
$queryParams['utc'] = $this->flexClient->getConfig('use_utc_time');
}
$response = $this->sendRequest($endpoint, $queryParams);
return $this->parseResponse($response);
} | [
"public",
"function",
"getFlightStatusByArrivalDate",
"(",
"$",
"carrier",
",",
"$",
"flight",
",",
"DateTime",
"$",
"date",
",",
"array",
"$",
"queryParams",
"=",
"[",
"]",
")",
"{",
"$",
"endpoint",
"=",
"sprintf",
"(",
"'flight/status/%s/%s/arr/%s'",
",",
... | Get the flight status from a flight that's arriving on the given date.
@param string $carrier The carrier (airline) code
@param integer $flight The flight number
@param DateTime $date The arrival date
@param array $queryParams Query parameters to add to the request
@return array The response from the API | [
"Get",
"the",
"flight",
"status",
"from",
"a",
"flight",
"that",
"s",
"arriving",
"on",
"the",
"given",
"date",
"."
] | train | https://github.com/willemo/flightstats/blob/32ee99110a86a3d418bc15ab7863b89e0ad3a65d/src/Api/FlightStatus.php#L55-L75 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php | Zend_Http_CookieJar.addCookie | public function addCookie($cookie, $ref_uri = null)
{
if (is_string($cookie)) {
$cookie = Zend_Http_Cookie::fromString($cookie, $ref_uri);
}
if ($cookie instanceof Zend_Http_Cookie) {
$domain = $cookie->getDomain();
$path = $cookie->getPath();
if (! isset($this->cookies[$domain])) { $this->cookies[$domain] = array();
}
if (! isset($this->cookies[$domain][$path])) { $this->cookies[$domain][$path] = array();
}
$this->cookies[$domain][$path][$cookie->getName()] = $cookie;
} else {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Supplient argument is not a valid cookie string or object');
}
} | php | public function addCookie($cookie, $ref_uri = null)
{
if (is_string($cookie)) {
$cookie = Zend_Http_Cookie::fromString($cookie, $ref_uri);
}
if ($cookie instanceof Zend_Http_Cookie) {
$domain = $cookie->getDomain();
$path = $cookie->getPath();
if (! isset($this->cookies[$domain])) { $this->cookies[$domain] = array();
}
if (! isset($this->cookies[$domain][$path])) { $this->cookies[$domain][$path] = array();
}
$this->cookies[$domain][$path][$cookie->getName()] = $cookie;
} else {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception('Supplient argument is not a valid cookie string or object');
}
} | [
"public",
"function",
"addCookie",
"(",
"$",
"cookie",
",",
"$",
"ref_uri",
"=",
"null",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"cookie",
")",
")",
"{",
"$",
"cookie",
"=",
"Zend_Http_Cookie",
"::",
"fromString",
"(",
"$",
"cookie",
",",
"$",
"r... | Add a cookie to the jar. Cookie should be passed either as a Zend_Http_Cookie object
or as a string - in which case an object is created from the string.
@param Zend_Http_Cookie|string $cookie
@param Zend_Uri_Http|string $ref_uri Optional reference URI (for domain, path, secure) | [
"Add",
"a",
"cookie",
"to",
"the",
"jar",
".",
"Cookie",
"should",
"be",
"passed",
"either",
"as",
"a",
"Zend_Http_Cookie",
"object",
"or",
"as",
"a",
"string",
"-",
"in",
"which",
"case",
"an",
"object",
"is",
"created",
"from",
"the",
"string",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php#L101-L119 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php | Zend_Http_CookieJar.addCookiesFromResponse | public function addCookiesFromResponse($response, $ref_uri)
{
if (! $response instanceof Zend_Http_Response) {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception(
'$response is expected to be a Response object, ' .
gettype($response) . ' was passed'
);
}
$cookie_hdrs = $response->getHeader('Set-Cookie');
if (is_array($cookie_hdrs)) {
foreach ($cookie_hdrs as $cookie) {
$this->addCookie($cookie, $ref_uri);
}
} elseif (is_string($cookie_hdrs)) {
$this->addCookie($cookie_hdrs, $ref_uri);
}
} | php | public function addCookiesFromResponse($response, $ref_uri)
{
if (! $response instanceof Zend_Http_Response) {
include_once 'Zend/Http/Exception.php';
throw new Zend_Http_Exception(
'$response is expected to be a Response object, ' .
gettype($response) . ' was passed'
);
}
$cookie_hdrs = $response->getHeader('Set-Cookie');
if (is_array($cookie_hdrs)) {
foreach ($cookie_hdrs as $cookie) {
$this->addCookie($cookie, $ref_uri);
}
} elseif (is_string($cookie_hdrs)) {
$this->addCookie($cookie_hdrs, $ref_uri);
}
} | [
"public",
"function",
"addCookiesFromResponse",
"(",
"$",
"response",
",",
"$",
"ref_uri",
")",
"{",
"if",
"(",
"!",
"$",
"response",
"instanceof",
"Zend_Http_Response",
")",
"{",
"include_once",
"'Zend/Http/Exception.php'",
";",
"throw",
"new",
"Zend_Http_Exception... | Parse an HTTP response, adding all the cookies set in that response
to the cookie jar.
@param Zend_Http_Response $response
@param Zend_Uri_Http|string $ref_uri Requested URI | [
"Parse",
"an",
"HTTP",
"response",
"adding",
"all",
"the",
"cookies",
"set",
"in",
"that",
"response",
"to",
"the",
"cookie",
"jar",
"."
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php#L128-L147 |
txj123/zilf | src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php | Zend_Http_CookieJar.getAllCookies | public function getAllCookies($ret_as = self::COOKIE_OBJECT)
{
$cookies = $this->_flattenCookiesArray($this->cookies, $ret_as);
return $cookies;
} | php | public function getAllCookies($ret_as = self::COOKIE_OBJECT)
{
$cookies = $this->_flattenCookiesArray($this->cookies, $ret_as);
return $cookies;
} | [
"public",
"function",
"getAllCookies",
"(",
"$",
"ret_as",
"=",
"self",
"::",
"COOKIE_OBJECT",
")",
"{",
"$",
"cookies",
"=",
"$",
"this",
"->",
"_flattenCookiesArray",
"(",
"$",
"this",
"->",
"cookies",
",",
"$",
"ret_as",
")",
";",
"return",
"$",
"cook... | Get all cookies in the cookie jar as an array
@param int $ret_as Whether to return cookies as objects of Zend_Http_Cookie or as strings
@return array|string | [
"Get",
"all",
"cookies",
"in",
"the",
"cookie",
"jar",
"as",
"an",
"array"
] | train | https://github.com/txj123/zilf/blob/8fc979ae338e850e6f40bfb97d4d57869f9e4480/src/Zilf/DataCrawler/PhpQuery/phpQuery/Zend/Http/CookieJar.php#L155-L159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.