repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
platformsh/platformsh-client-php
src/Model/Subscription.php
Subscription.getOwner
public function getOwner() { $uuid = $this->getProperty('owner'); $url = $this->makeAbsoluteUrl('/api/users', $this->getLink('project')); return Account::get($uuid, $url, $this->client); }
php
public function getOwner() { $uuid = $this->getProperty('owner'); $url = $this->makeAbsoluteUrl('/api/users', $this->getLink('project')); return Account::get($uuid, $url, $this->client); }
[ "public", "function", "getOwner", "(", ")", "{", "$", "uuid", "=", "$", "this", "->", "getProperty", "(", "'owner'", ")", ";", "$", "url", "=", "$", "this", "->", "makeAbsoluteUrl", "(", "'/api/users'", ",", "$", "this", "->", "getLink", "(", "'project'", ")", ")", ";", "return", "Account", "::", "get", "(", "$", "uuid", ",", "$", "url", ",", "$", "this", "->", "client", ")", ";", "}" ]
Get the account for the project's owner. @return Account|false
[ "Get", "the", "account", "for", "the", "project", "s", "owner", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Subscription.php#L133-L138
train
platformsh/platformsh-client-php
src/Model/Subscription.php
Subscription.getProject
public function getProject() { if (!$this->hasLink('project') && !$this->isActive()) { throw new \BadMethodCallException('Inactive subscriptions do not have projects.'); } $url = $this->getLink('project'); return Project::get($url, null, $this->client); }
php
public function getProject() { if (!$this->hasLink('project') && !$this->isActive()) { throw new \BadMethodCallException('Inactive subscriptions do not have projects.'); } $url = $this->getLink('project'); return Project::get($url, null, $this->client); }
[ "public", "function", "getProject", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasLink", "(", "'project'", ")", "&&", "!", "$", "this", "->", "isActive", "(", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'Inactive subscriptions do not have projects.'", ")", ";", "}", "$", "url", "=", "$", "this", "->", "getLink", "(", "'project'", ")", ";", "return", "Project", "::", "get", "(", "$", "url", ",", "null", ",", "$", "this", "->", "client", ")", ";", "}" ]
Get the project associated with this subscription. @return Project|false
[ "Get", "the", "project", "associated", "with", "this", "subscription", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Subscription.php#L145-L152
train
platformsh/platformsh-client-php
src/Model/Activity.php
Activity.wait
public function wait(callable $onPoll = null, callable $onLog = null, $pollInterval = 1) { $log = $this->getProperty('log'); if ($onLog !== null && strlen(trim($log))) { $onLog(trim($log) . "\n"); } $length = strlen($log); $retries = 0; while (!$this->isComplete()) { usleep($pollInterval * 1000000); try { $this->refresh(['timeout' => $pollInterval + 5]); if ($onPoll !== null) { $onPoll($this); } if ($onLog !== null && ($new = substr($this->getProperty('log'), $length))) { $onLog(trim($new) . "\n"); $length += strlen($new); } } catch (ConnectException $e) { // Retry on timeout. if (strpos($e->getMessage(), 'cURL error 28') !== false && $retries <= 5) { $retries++; continue; } throw $e; } } }
php
public function wait(callable $onPoll = null, callable $onLog = null, $pollInterval = 1) { $log = $this->getProperty('log'); if ($onLog !== null && strlen(trim($log))) { $onLog(trim($log) . "\n"); } $length = strlen($log); $retries = 0; while (!$this->isComplete()) { usleep($pollInterval * 1000000); try { $this->refresh(['timeout' => $pollInterval + 5]); if ($onPoll !== null) { $onPoll($this); } if ($onLog !== null && ($new = substr($this->getProperty('log'), $length))) { $onLog(trim($new) . "\n"); $length += strlen($new); } } catch (ConnectException $e) { // Retry on timeout. if (strpos($e->getMessage(), 'cURL error 28') !== false && $retries <= 5) { $retries++; continue; } throw $e; } } }
[ "public", "function", "wait", "(", "callable", "$", "onPoll", "=", "null", ",", "callable", "$", "onLog", "=", "null", ",", "$", "pollInterval", "=", "1", ")", "{", "$", "log", "=", "$", "this", "->", "getProperty", "(", "'log'", ")", ";", "if", "(", "$", "onLog", "!==", "null", "&&", "strlen", "(", "trim", "(", "$", "log", ")", ")", ")", "{", "$", "onLog", "(", "trim", "(", "$", "log", ")", ".", "\"\\n\"", ")", ";", "}", "$", "length", "=", "strlen", "(", "$", "log", ")", ";", "$", "retries", "=", "0", ";", "while", "(", "!", "$", "this", "->", "isComplete", "(", ")", ")", "{", "usleep", "(", "$", "pollInterval", "*", "1000000", ")", ";", "try", "{", "$", "this", "->", "refresh", "(", "[", "'timeout'", "=>", "$", "pollInterval", "+", "5", "]", ")", ";", "if", "(", "$", "onPoll", "!==", "null", ")", "{", "$", "onPoll", "(", "$", "this", ")", ";", "}", "if", "(", "$", "onLog", "!==", "null", "&&", "(", "$", "new", "=", "substr", "(", "$", "this", "->", "getProperty", "(", "'log'", ")", ",", "$", "length", ")", ")", ")", "{", "$", "onLog", "(", "trim", "(", "$", "new", ")", ".", "\"\\n\"", ")", ";", "$", "length", "+=", "strlen", "(", "$", "new", ")", ";", "}", "}", "catch", "(", "ConnectException", "$", "e", ")", "{", "// Retry on timeout.", "if", "(", "strpos", "(", "$", "e", "->", "getMessage", "(", ")", ",", "'cURL error 28'", ")", "!==", "false", "&&", "$", "retries", "<=", "5", ")", "{", "$", "retries", "++", ";", "continue", ";", "}", "throw", "$", "e", ";", "}", "}", "}" ]
Wait for the activity to complete. @todo use the FutureInterface @param callable $onPoll A function that will be called every time the activity is polled for updates. It will be passed one argument: the Activity object. @param callable $onLog A function that will print new activity log messages as they are received. It will be passed one argument: the message as a string. @param int|float $pollInterval The polling interval, in seconds.
[ "Wait", "for", "the", "activity", "to", "complete", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Activity.php#L54-L82
train
platformsh/platformsh-client-php
src/Model/Activity.php
Activity.restore
public function restore($target = null, $branchFrom = null) { if ($this->getProperty('type') !== 'environment.backup') { throw new \BadMethodCallException('Cannot restore activity (wrong type)'); } if (!$this->isComplete()) { throw new \BadMethodCallException('Cannot restore backup (not complete)'); } $options = []; if ($target !== null) { $options['environment_name'] = $target; } if ($branchFrom !== null) { $options['branch_from'] = $branchFrom; } return $this->runLongOperation('restore', 'post', $options); }
php
public function restore($target = null, $branchFrom = null) { if ($this->getProperty('type') !== 'environment.backup') { throw new \BadMethodCallException('Cannot restore activity (wrong type)'); } if (!$this->isComplete()) { throw new \BadMethodCallException('Cannot restore backup (not complete)'); } $options = []; if ($target !== null) { $options['environment_name'] = $target; } if ($branchFrom !== null) { $options['branch_from'] = $branchFrom; } return $this->runLongOperation('restore', 'post', $options); }
[ "public", "function", "restore", "(", "$", "target", "=", "null", ",", "$", "branchFrom", "=", "null", ")", "{", "if", "(", "$", "this", "->", "getProperty", "(", "'type'", ")", "!==", "'environment.backup'", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'Cannot restore activity (wrong type)'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "isComplete", "(", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'Cannot restore backup (not complete)'", ")", ";", "}", "$", "options", "=", "[", "]", ";", "if", "(", "$", "target", "!==", "null", ")", "{", "$", "options", "[", "'environment_name'", "]", "=", "$", "target", ";", "}", "if", "(", "$", "branchFrom", "!==", "null", ")", "{", "$", "options", "[", "'branch_from'", "]", "=", "$", "branchFrom", ";", "}", "return", "$", "this", "->", "runLongOperation", "(", "'restore'", ",", "'post'", ",", "$", "options", ")", ";", "}" ]
Restore the backup associated with this activity. @param string|null $target The name of the target environment to which the backup should be restored (this could be the name of an existing environment, or a new environment). Leave this null to restore to the backup's original environment. @param string|null $branchFrom If a new environment will be created (depending on $target), this specifies the name of the parent branch. @return Activity
[ "Restore", "the", "backup", "associated", "with", "this", "activity", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Activity.php#L119-L137
train
platformsh/platformsh-client-php
src/Model/Activity.php
Activity.getDescription
public function getDescription($html = false) { $description = $this->getProperty('description'); if ($html) { return $description; } return html_entity_decode(strip_tags($description), ENT_QUOTES, 'utf-8'); }
php
public function getDescription($html = false) { $description = $this->getProperty('description'); if ($html) { return $description; } return html_entity_decode(strip_tags($description), ENT_QUOTES, 'utf-8'); }
[ "public", "function", "getDescription", "(", "$", "html", "=", "false", ")", "{", "$", "description", "=", "$", "this", "->", "getProperty", "(", "'description'", ")", ";", "if", "(", "$", "html", ")", "{", "return", "$", "description", ";", "}", "return", "html_entity_decode", "(", "strip_tags", "(", "$", "description", ")", ",", "ENT_QUOTES", ",", "'utf-8'", ")", ";", "}" ]
Get a human-readable description of the activity. The "description" property contains the HTML-formatted description. This method just provides another way to access it, and a way to remove HTML easily. @param bool $html Whether to return HTML. @return string
[ "Get", "a", "human", "-", "readable", "description", "of", "the", "activity", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Activity.php#L150-L158
train
koenpunt/php-inflector
lib/Inflector.php
Inflector.inflections
public static function inflections($block = false){ if($block){ return call_user_func($block, Inflections::instance()); }else{ return Inflections::instance(); } }
php
public static function inflections($block = false){ if($block){ return call_user_func($block, Inflections::instance()); }else{ return Inflections::instance(); } }
[ "public", "static", "function", "inflections", "(", "$", "block", "=", "false", ")", "{", "if", "(", "$", "block", ")", "{", "return", "call_user_func", "(", "$", "block", ",", "Inflections", "::", "instance", "(", ")", ")", ";", "}", "else", "{", "return", "Inflections", "::", "instance", "(", ")", ";", "}", "}" ]
Yields a singleton instance of Inflections so you can specify additional inflector rules. Example: Inflector::inflections(function($inflect){ $inflect->uncountable("rails"); }); @param callable $block @return Inflections @author Koen Punt
[ "Yields", "a", "singleton", "instance", "of", "Inflections", "so", "you", "can", "specify", "additional", "inflector", "rules", "." ]
8bf0655b11d0c9d5a065928a1d4a4c627b0a09c1
https://github.com/koenpunt/php-inflector/blob/8bf0655b11d0c9d5a065928a1d4a4c627b0a09c1/lib/Inflector.php#L31-L37
train
platformsh/platformsh-client-php
src/Model/Type/Duration.php
Duration.stringToSeconds
private static function stringToSeconds($duration) { if (isset(self::$suffixes[substr($duration, -1)])) { $amount = substr($duration, 0, strlen($duration) - 1); $unit = self::$suffixes[substr($duration, -1)]; } else { $unit = 1; $amount = $duration; } if (!is_numeric($amount)) { throw new \InvalidArgumentException('Invalid duration: ' . $duration); } return $unit * $amount; }
php
private static function stringToSeconds($duration) { if (isset(self::$suffixes[substr($duration, -1)])) { $amount = substr($duration, 0, strlen($duration) - 1); $unit = self::$suffixes[substr($duration, -1)]; } else { $unit = 1; $amount = $duration; } if (!is_numeric($amount)) { throw new \InvalidArgumentException('Invalid duration: ' . $duration); } return $unit * $amount; }
[ "private", "static", "function", "stringToSeconds", "(", "$", "duration", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "suffixes", "[", "substr", "(", "$", "duration", ",", "-", "1", ")", "]", ")", ")", "{", "$", "amount", "=", "substr", "(", "$", "duration", ",", "0", ",", "strlen", "(", "$", "duration", ")", "-", "1", ")", ";", "$", "unit", "=", "self", "::", "$", "suffixes", "[", "substr", "(", "$", "duration", ",", "-", "1", ")", "]", ";", "}", "else", "{", "$", "unit", "=", "1", ";", "$", "amount", "=", "$", "duration", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "amount", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid duration: '", ".", "$", "duration", ")", ";", "}", "return", "$", "unit", "*", "$", "amount", ";", "}" ]
Converts a duration string to seconds. @param string $duration @return int|float
[ "Converts", "a", "duration", "string", "to", "seconds", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/Type/Duration.php#L63-L78
train
platformsh/platformsh-client-php
src/Model/ProjectAccess.php
ProjectAccess.getAccount
public function getAccount() { $uuid = $this->getProperty('id'); $url = $this->makeAbsoluteUrl('/api/users'); $account = Account::get($uuid, $url, $this->client); if (!$account) { throw new \Exception("Account not found for user: " . $uuid); } return $account; }
php
public function getAccount() { $uuid = $this->getProperty('id'); $url = $this->makeAbsoluteUrl('/api/users'); $account = Account::get($uuid, $url, $this->client); if (!$account) { throw new \Exception("Account not found for user: " . $uuid); } return $account; }
[ "public", "function", "getAccount", "(", ")", "{", "$", "uuid", "=", "$", "this", "->", "getProperty", "(", "'id'", ")", ";", "$", "url", "=", "$", "this", "->", "makeAbsoluteUrl", "(", "'/api/users'", ")", ";", "$", "account", "=", "Account", "::", "get", "(", "$", "uuid", ",", "$", "url", ",", "$", "this", "->", "client", ")", ";", "if", "(", "!", "$", "account", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Account not found for user: \"", ".", "$", "uuid", ")", ";", "}", "return", "$", "account", ";", "}" ]
Get the account information for this user. @throws \Exception @return Account
[ "Get", "the", "account", "information", "for", "this", "user", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/ProjectAccess.php#L29-L38
train
platformsh/platformsh-client-php
src/Model/ProjectAccess.php
ProjectAccess.getEnvironmentRole
public function getEnvironmentRole(Environment $environment) { $access = $environment->getUser($this->id); return $access ? $access->role : false; }
php
public function getEnvironmentRole(Environment $environment) { $access = $environment->getUser($this->id); return $access ? $access->role : false; }
[ "public", "function", "getEnvironmentRole", "(", "Environment", "$", "environment", ")", "{", "$", "access", "=", "$", "environment", "->", "getUser", "(", "$", "this", "->", "id", ")", ";", "return", "$", "access", "?", "$", "access", "->", "role", ":", "false", ";", "}" ]
Get the user's role on an environment. @param Environment $environment @deprecated use Environment::getUser() instead @return string|false The user's environment role, or false if not found.
[ "Get", "the", "user", "s", "role", "on", "an", "environment", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/ProjectAccess.php#L50-L55
train
platformsh/platformsh-client-php
src/Model/ProjectAccess.php
ProjectAccess.changeEnvironmentRole
public function changeEnvironmentRole(Environment $environment, $newRole) { $access = $environment->getUser($this->id); if ($access) { if ($access->role === $newRole) { throw new \InvalidArgumentException("There is nothing to change"); } return $access->update(['role' => $newRole]); } return $environment->addUser($this->id, $newRole); }
php
public function changeEnvironmentRole(Environment $environment, $newRole) { $access = $environment->getUser($this->id); if ($access) { if ($access->role === $newRole) { throw new \InvalidArgumentException("There is nothing to change"); } return $access->update(['role' => $newRole]); } return $environment->addUser($this->id, $newRole); }
[ "public", "function", "changeEnvironmentRole", "(", "Environment", "$", "environment", ",", "$", "newRole", ")", "{", "$", "access", "=", "$", "environment", "->", "getUser", "(", "$", "this", "->", "id", ")", ";", "if", "(", "$", "access", ")", "{", "if", "(", "$", "access", "->", "role", "===", "$", "newRole", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"There is nothing to change\"", ")", ";", "}", "return", "$", "access", "->", "update", "(", "[", "'role'", "=>", "$", "newRole", "]", ")", ";", "}", "return", "$", "environment", "->", "addUser", "(", "$", "this", "->", "id", ",", "$", "newRole", ")", ";", "}" ]
Change the user's environment-level role. @param Environment $environment @param string $newRole The new role (see EnvironmentAccess::$roles). @return Result
[ "Change", "the", "user", "s", "environment", "-", "level", "role", "." ]
7a0abb5ba796e6498e2364fae7860a0dcf58111c
https://github.com/platformsh/platformsh-client-php/blob/7a0abb5ba796e6498e2364fae7860a0dcf58111c/src/Model/ProjectAccess.php#L65-L77
train
acmephp/ssl
Signer/DataSigner.php
DataSigner.signData
public function signData($data, PrivateKey $privateKey, $algorithm = OPENSSL_ALGO_SHA256, $format = self::FORMAT_DER) { Assert::oneOf($format, [self::FORMAT_ECDSA, self::FORMAT_DER], 'The format %s to sign request does not exists. Available format: %s'); $resource = $privateKey->getResource(); if (!openssl_sign($data, $signature, $resource, $algorithm)) { throw new DataSigningException( sprintf('OpenSSL data signing failed with error: %s', openssl_error_string()) ); } openssl_free_key($resource); switch ($format) { case self::FORMAT_DER: return $signature; case self::FORMAT_ECDSA: switch ($algorithm) { case OPENSSL_ALGO_SHA256: return $this->DERtoECDSA($signature, 64); case OPENSSL_ALGO_SHA384: return $this->DERtoECDSA($signature, 96); case OPENSSL_ALGO_SHA512: return $this->DERtoECDSA($signature, 132); } throw new DataSigningException('Unable to generate a ECDSA signature with the given algorithm'); default: throw new DataSigningException('The given format does exists'); } }
php
public function signData($data, PrivateKey $privateKey, $algorithm = OPENSSL_ALGO_SHA256, $format = self::FORMAT_DER) { Assert::oneOf($format, [self::FORMAT_ECDSA, self::FORMAT_DER], 'The format %s to sign request does not exists. Available format: %s'); $resource = $privateKey->getResource(); if (!openssl_sign($data, $signature, $resource, $algorithm)) { throw new DataSigningException( sprintf('OpenSSL data signing failed with error: %s', openssl_error_string()) ); } openssl_free_key($resource); switch ($format) { case self::FORMAT_DER: return $signature; case self::FORMAT_ECDSA: switch ($algorithm) { case OPENSSL_ALGO_SHA256: return $this->DERtoECDSA($signature, 64); case OPENSSL_ALGO_SHA384: return $this->DERtoECDSA($signature, 96); case OPENSSL_ALGO_SHA512: return $this->DERtoECDSA($signature, 132); } throw new DataSigningException('Unable to generate a ECDSA signature with the given algorithm'); default: throw new DataSigningException('The given format does exists'); } }
[ "public", "function", "signData", "(", "$", "data", ",", "PrivateKey", "$", "privateKey", ",", "$", "algorithm", "=", "OPENSSL_ALGO_SHA256", ",", "$", "format", "=", "self", "::", "FORMAT_DER", ")", "{", "Assert", "::", "oneOf", "(", "$", "format", ",", "[", "self", "::", "FORMAT_ECDSA", ",", "self", "::", "FORMAT_DER", "]", ",", "'The format %s to sign request does not exists. Available format: %s'", ")", ";", "$", "resource", "=", "$", "privateKey", "->", "getResource", "(", ")", ";", "if", "(", "!", "openssl_sign", "(", "$", "data", ",", "$", "signature", ",", "$", "resource", ",", "$", "algorithm", ")", ")", "{", "throw", "new", "DataSigningException", "(", "sprintf", "(", "'OpenSSL data signing failed with error: %s'", ",", "openssl_error_string", "(", ")", ")", ")", ";", "}", "openssl_free_key", "(", "$", "resource", ")", ";", "switch", "(", "$", "format", ")", "{", "case", "self", "::", "FORMAT_DER", ":", "return", "$", "signature", ";", "case", "self", "::", "FORMAT_ECDSA", ":", "switch", "(", "$", "algorithm", ")", "{", "case", "OPENSSL_ALGO_SHA256", ":", "return", "$", "this", "->", "DERtoECDSA", "(", "$", "signature", ",", "64", ")", ";", "case", "OPENSSL_ALGO_SHA384", ":", "return", "$", "this", "->", "DERtoECDSA", "(", "$", "signature", ",", "96", ")", ";", "case", "OPENSSL_ALGO_SHA512", ":", "return", "$", "this", "->", "DERtoECDSA", "(", "$", "signature", ",", "132", ")", ";", "}", "throw", "new", "DataSigningException", "(", "'Unable to generate a ECDSA signature with the given algorithm'", ")", ";", "default", ":", "throw", "new", "DataSigningException", "(", "'The given format does exists'", ")", ";", "}", "}" ]
Generate a signature of the given data using a private key and an algorithm. @param string $data Data to sign @param PrivateKey $privateKey Key used to sign @param int $algorithm Signature algorithm defined by constants OPENSSL_ALGO_* @param string $format Format of the output @return string
[ "Generate", "a", "signature", "of", "the", "given", "data", "using", "a", "private", "key", "and", "an", "algorithm", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Signer/DataSigner.php#L38-L67
train
acmephp/ssl
Signer/DataSigner.php
DataSigner.DERtoECDSA
private function DERtoECDSA($der, $partLength) { $hex = unpack('H*', $der)[1]; if ('30' !== mb_substr($hex, 0, 2, '8bit')) { // SEQUENCE throw new DataSigningException('Invalid signature provided'); } if ('81' === mb_substr($hex, 2, 2, '8bit')) { // LENGTH > 128 $hex = mb_substr($hex, 6, null, '8bit'); } else { $hex = mb_substr($hex, 4, null, '8bit'); } if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Rl = hexdec(mb_substr($hex, 2, 2, '8bit')); $R = $this->retrievePositiveInteger(mb_substr($hex, 4, $Rl * 2, '8bit')); $R = str_pad($R, $partLength, '0', STR_PAD_LEFT); $hex = mb_substr($hex, 4 + $Rl * 2, null, '8bit'); if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Sl = hexdec(mb_substr($hex, 2, 2, '8bit')); $S = $this->retrievePositiveInteger(mb_substr($hex, 4, $Sl * 2, '8bit')); $S = str_pad($S, $partLength, '0', STR_PAD_LEFT); return pack('H*', $R.$S); }
php
private function DERtoECDSA($der, $partLength) { $hex = unpack('H*', $der)[1]; if ('30' !== mb_substr($hex, 0, 2, '8bit')) { // SEQUENCE throw new DataSigningException('Invalid signature provided'); } if ('81' === mb_substr($hex, 2, 2, '8bit')) { // LENGTH > 128 $hex = mb_substr($hex, 6, null, '8bit'); } else { $hex = mb_substr($hex, 4, null, '8bit'); } if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Rl = hexdec(mb_substr($hex, 2, 2, '8bit')); $R = $this->retrievePositiveInteger(mb_substr($hex, 4, $Rl * 2, '8bit')); $R = str_pad($R, $partLength, '0', STR_PAD_LEFT); $hex = mb_substr($hex, 4 + $Rl * 2, null, '8bit'); if ('02' !== mb_substr($hex, 0, 2, '8bit')) { // INTEGER throw new DataSigningException('Invalid signature provided'); } $Sl = hexdec(mb_substr($hex, 2, 2, '8bit')); $S = $this->retrievePositiveInteger(mb_substr($hex, 4, $Sl * 2, '8bit')); $S = str_pad($S, $partLength, '0', STR_PAD_LEFT); return pack('H*', $R.$S); }
[ "private", "function", "DERtoECDSA", "(", "$", "der", ",", "$", "partLength", ")", "{", "$", "hex", "=", "unpack", "(", "'H*'", ",", "$", "der", ")", "[", "1", "]", ";", "if", "(", "'30'", "!==", "mb_substr", "(", "$", "hex", ",", "0", ",", "2", ",", "'8bit'", ")", ")", "{", "// SEQUENCE", "throw", "new", "DataSigningException", "(", "'Invalid signature provided'", ")", ";", "}", "if", "(", "'81'", "===", "mb_substr", "(", "$", "hex", ",", "2", ",", "2", ",", "'8bit'", ")", ")", "{", "// LENGTH > 128", "$", "hex", "=", "mb_substr", "(", "$", "hex", ",", "6", ",", "null", ",", "'8bit'", ")", ";", "}", "else", "{", "$", "hex", "=", "mb_substr", "(", "$", "hex", ",", "4", ",", "null", ",", "'8bit'", ")", ";", "}", "if", "(", "'02'", "!==", "mb_substr", "(", "$", "hex", ",", "0", ",", "2", ",", "'8bit'", ")", ")", "{", "// INTEGER", "throw", "new", "DataSigningException", "(", "'Invalid signature provided'", ")", ";", "}", "$", "Rl", "=", "hexdec", "(", "mb_substr", "(", "$", "hex", ",", "2", ",", "2", ",", "'8bit'", ")", ")", ";", "$", "R", "=", "$", "this", "->", "retrievePositiveInteger", "(", "mb_substr", "(", "$", "hex", ",", "4", ",", "$", "Rl", "*", "2", ",", "'8bit'", ")", ")", ";", "$", "R", "=", "str_pad", "(", "$", "R", ",", "$", "partLength", ",", "'0'", ",", "STR_PAD_LEFT", ")", ";", "$", "hex", "=", "mb_substr", "(", "$", "hex", ",", "4", "+", "$", "Rl", "*", "2", ",", "null", ",", "'8bit'", ")", ";", "if", "(", "'02'", "!==", "mb_substr", "(", "$", "hex", ",", "0", ",", "2", ",", "'8bit'", ")", ")", "{", "// INTEGER", "throw", "new", "DataSigningException", "(", "'Invalid signature provided'", ")", ";", "}", "$", "Sl", "=", "hexdec", "(", "mb_substr", "(", "$", "hex", ",", "2", ",", "2", ",", "'8bit'", ")", ")", ";", "$", "S", "=", "$", "this", "->", "retrievePositiveInteger", "(", "mb_substr", "(", "$", "hex", ",", "4", ",", "$", "Sl", "*", "2", ",", "'8bit'", ")", ")", ";", "$", "S", "=", "str_pad", "(", "$", "S", ",", "$", "partLength", ",", "'0'", ",", "STR_PAD_LEFT", ")", ";", "return", "pack", "(", "'H*'", ",", "$", "R", ".", "$", "S", ")", ";", "}" ]
Convert a DER signature into ECDSA. The code is a copy/paste from another lib (web-token/jwt-core) which is not compatible with php <= 7.0 @see https://github.com/web-token/jwt-core/blob/master/Util/ECSignature.php
[ "Convert", "a", "DER", "signature", "into", "ECDSA", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Signer/DataSigner.php#L76-L104
train
acmephp/ssl
Signer/CertificateRequestSigner.php
CertificateRequestSigner.signCertificateRequest
public function signCertificateRequest(CertificateRequest $certificateRequest) { $csrObject = $this->createCsrWithSANsObject($certificateRequest); if (!$csrObject || !openssl_csr_export($csrObject, $csrExport)) { throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())); } return $csrExport; }
php
public function signCertificateRequest(CertificateRequest $certificateRequest) { $csrObject = $this->createCsrWithSANsObject($certificateRequest); if (!$csrObject || !openssl_csr_export($csrObject, $csrExport)) { throw new CSRSigningException(sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())); } return $csrExport; }
[ "public", "function", "signCertificateRequest", "(", "CertificateRequest", "$", "certificateRequest", ")", "{", "$", "csrObject", "=", "$", "this", "->", "createCsrWithSANsObject", "(", "$", "certificateRequest", ")", ";", "if", "(", "!", "$", "csrObject", "||", "!", "openssl_csr_export", "(", "$", "csrObject", ",", "$", "csrExport", ")", ")", "{", "throw", "new", "CSRSigningException", "(", "sprintf", "(", "'OpenSSL CSR signing failed with error: %s'", ",", "openssl_error_string", "(", ")", ")", ")", ";", "}", "return", "$", "csrExport", ";", "}" ]
Generate a CSR from the given distinguishedName and keyPair. @param CertificateRequest $certificateRequest @return string
[ "Generate", "a", "CSR", "from", "the", "given", "distinguishedName", "and", "keyPair", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Signer/CertificateRequestSigner.php#L32-L41
train
acmephp/ssl
Signer/CertificateRequestSigner.php
CertificateRequestSigner.createCsrWithSANsObject
protected function createCsrWithSANsObject(CertificateRequest $certificateRequest) { $sslConfigTemplate = <<<'EOL' [ req ] distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @req_subject_alt_name [ req_subject_alt_name ] %s EOL; $sslConfigDomains = []; $distinguishedName = $certificateRequest->getDistinguishedName(); $domains = array_merge( [$distinguishedName->getCommonName()], $distinguishedName->getSubjectAlternativeNames() ); foreach (array_values($domains) as $index => $domain) { $sslConfigDomains[] = 'DNS.'.($index + 1).' = '.$domain; } $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains)); $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_'); try { file_put_contents($sslConfigFile, $sslConfigContent); $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource(); $csr = openssl_csr_new( $this->getCSRPayload($distinguishedName), $resource, [ 'digest_alg' => 'sha256', 'config' => $sslConfigFile, ] ); openssl_free_key($resource); if (!$csr) { throw new CSRSigningException( sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string()) ); } return $csr; } finally { unlink($sslConfigFile); } }
php
protected function createCsrWithSANsObject(CertificateRequest $certificateRequest) { $sslConfigTemplate = <<<'EOL' [ req ] distinguished_name = req_distinguished_name req_extensions = v3_req [ req_distinguished_name ] [ v3_req ] basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @req_subject_alt_name [ req_subject_alt_name ] %s EOL; $sslConfigDomains = []; $distinguishedName = $certificateRequest->getDistinguishedName(); $domains = array_merge( [$distinguishedName->getCommonName()], $distinguishedName->getSubjectAlternativeNames() ); foreach (array_values($domains) as $index => $domain) { $sslConfigDomains[] = 'DNS.'.($index + 1).' = '.$domain; } $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains)); $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_'); try { file_put_contents($sslConfigFile, $sslConfigContent); $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource(); $csr = openssl_csr_new( $this->getCSRPayload($distinguishedName), $resource, [ 'digest_alg' => 'sha256', 'config' => $sslConfigFile, ] ); openssl_free_key($resource); if (!$csr) { throw new CSRSigningException( sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string()) ); } return $csr; } finally { unlink($sslConfigFile); } }
[ "protected", "function", "createCsrWithSANsObject", "(", "CertificateRequest", "$", "certificateRequest", ")", "{", "$", "sslConfigTemplate", "=", " <<<'EOL'\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ req_distinguished_name ]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = @req_subject_alt_name\n[ req_subject_alt_name ]\n%s\nEOL", ";", "$", "sslConfigDomains", "=", "[", "]", ";", "$", "distinguishedName", "=", "$", "certificateRequest", "->", "getDistinguishedName", "(", ")", ";", "$", "domains", "=", "array_merge", "(", "[", "$", "distinguishedName", "->", "getCommonName", "(", ")", "]", ",", "$", "distinguishedName", "->", "getSubjectAlternativeNames", "(", ")", ")", ";", "foreach", "(", "array_values", "(", "$", "domains", ")", "as", "$", "index", "=>", "$", "domain", ")", "{", "$", "sslConfigDomains", "[", "]", "=", "'DNS.'", ".", "(", "$", "index", "+", "1", ")", ".", "' = '", ".", "$", "domain", ";", "}", "$", "sslConfigContent", "=", "sprintf", "(", "$", "sslConfigTemplate", ",", "implode", "(", "\"\\n\"", ",", "$", "sslConfigDomains", ")", ")", ";", "$", "sslConfigFile", "=", "tempnam", "(", "sys_get_temp_dir", "(", ")", ",", "'acmephp_'", ")", ";", "try", "{", "file_put_contents", "(", "$", "sslConfigFile", ",", "$", "sslConfigContent", ")", ";", "$", "resource", "=", "$", "certificateRequest", "->", "getKeyPair", "(", ")", "->", "getPrivateKey", "(", ")", "->", "getResource", "(", ")", ";", "$", "csr", "=", "openssl_csr_new", "(", "$", "this", "->", "getCSRPayload", "(", "$", "distinguishedName", ")", ",", "$", "resource", ",", "[", "'digest_alg'", "=>", "'sha256'", ",", "'config'", "=>", "$", "sslConfigFile", ",", "]", ")", ";", "openssl_free_key", "(", "$", "resource", ")", ";", "if", "(", "!", "$", "csr", ")", "{", "throw", "new", "CSRSigningException", "(", "sprintf", "(", "'OpenSSL CSR signing failed with error: %s'", ",", "openssl_error_string", "(", ")", ")", ")", ";", "}", "return", "$", "csr", ";", "}", "finally", "{", "unlink", "(", "$", "sslConfigFile", ")", ";", "}", "}" ]
Generate a CSR object with SANs from the given distinguishedName and keyPair. @param CertificateRequest $certificateRequest @return mixed
[ "Generate", "a", "CSR", "object", "with", "SANs", "from", "the", "given", "distinguishedName", "and", "keyPair", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Signer/CertificateRequestSigner.php#L50-L105
train
acmephp/ssl
Signer/CertificateRequestSigner.php
CertificateRequestSigner.getCSRPayload
private function getCSRPayload(DistinguishedName $distinguishedName) { $payload = []; if (null !== $countryName = $distinguishedName->getCountryName()) { $payload['countryName'] = $countryName; } if (null !== $stateOrProvinceName = $distinguishedName->getStateOrProvinceName()) { $payload['stateOrProvinceName'] = $stateOrProvinceName; } if (null !== $localityName = $distinguishedName->getLocalityName()) { $payload['localityName'] = $localityName; } if (null !== $OrganizationName = $distinguishedName->getOrganizationName()) { $payload['organizationName'] = $OrganizationName; } if (null !== $organizationUnitName = $distinguishedName->getOrganizationalUnitName()) { $payload['organizationalUnitName'] = $organizationUnitName; } if (null !== $commonName = $distinguishedName->getCommonName()) { $payload['commonName'] = $commonName; } if (null !== $emailAddress = $distinguishedName->getEmailAddress()) { $payload['emailAddress'] = $emailAddress; } return $payload; }
php
private function getCSRPayload(DistinguishedName $distinguishedName) { $payload = []; if (null !== $countryName = $distinguishedName->getCountryName()) { $payload['countryName'] = $countryName; } if (null !== $stateOrProvinceName = $distinguishedName->getStateOrProvinceName()) { $payload['stateOrProvinceName'] = $stateOrProvinceName; } if (null !== $localityName = $distinguishedName->getLocalityName()) { $payload['localityName'] = $localityName; } if (null !== $OrganizationName = $distinguishedName->getOrganizationName()) { $payload['organizationName'] = $OrganizationName; } if (null !== $organizationUnitName = $distinguishedName->getOrganizationalUnitName()) { $payload['organizationalUnitName'] = $organizationUnitName; } if (null !== $commonName = $distinguishedName->getCommonName()) { $payload['commonName'] = $commonName; } if (null !== $emailAddress = $distinguishedName->getEmailAddress()) { $payload['emailAddress'] = $emailAddress; } return $payload; }
[ "private", "function", "getCSRPayload", "(", "DistinguishedName", "$", "distinguishedName", ")", "{", "$", "payload", "=", "[", "]", ";", "if", "(", "null", "!==", "$", "countryName", "=", "$", "distinguishedName", "->", "getCountryName", "(", ")", ")", "{", "$", "payload", "[", "'countryName'", "]", "=", "$", "countryName", ";", "}", "if", "(", "null", "!==", "$", "stateOrProvinceName", "=", "$", "distinguishedName", "->", "getStateOrProvinceName", "(", ")", ")", "{", "$", "payload", "[", "'stateOrProvinceName'", "]", "=", "$", "stateOrProvinceName", ";", "}", "if", "(", "null", "!==", "$", "localityName", "=", "$", "distinguishedName", "->", "getLocalityName", "(", ")", ")", "{", "$", "payload", "[", "'localityName'", "]", "=", "$", "localityName", ";", "}", "if", "(", "null", "!==", "$", "OrganizationName", "=", "$", "distinguishedName", "->", "getOrganizationName", "(", ")", ")", "{", "$", "payload", "[", "'organizationName'", "]", "=", "$", "OrganizationName", ";", "}", "if", "(", "null", "!==", "$", "organizationUnitName", "=", "$", "distinguishedName", "->", "getOrganizationalUnitName", "(", ")", ")", "{", "$", "payload", "[", "'organizationalUnitName'", "]", "=", "$", "organizationUnitName", ";", "}", "if", "(", "null", "!==", "$", "commonName", "=", "$", "distinguishedName", "->", "getCommonName", "(", ")", ")", "{", "$", "payload", "[", "'commonName'", "]", "=", "$", "commonName", ";", "}", "if", "(", "null", "!==", "$", "emailAddress", "=", "$", "distinguishedName", "->", "getEmailAddress", "(", ")", ")", "{", "$", "payload", "[", "'emailAddress'", "]", "=", "$", "emailAddress", ";", "}", "return", "$", "payload", ";", "}" ]
Retrieves a CSR payload from the given distinguished name. @param DistinguishedName $distinguishedName @return array
[ "Retrieves", "a", "CSR", "payload", "from", "the", "given", "distinguished", "name", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Signer/CertificateRequestSigner.php#L114-L140
train
acmephp/ssl
Generator/KeyPairGenerator.php
KeyPairGenerator.generateKeyPair
public function generateKeyPair($keyOption = null) { if (null === $keyOption) { $keyOption = new RsaKeyOption(); } if (\is_int($keyOption)) { @trigger_error('Passing a keySize to "generateKeyPair" is deprecated since version 1.1 and will be removed in 2.0. Pass an instance of KeyOption instead', E_USER_DEPRECATED); $keyOption = new RsaKeyOption($keyOption); } Assert::isInstanceOf($keyOption, KeyOption::class); try { $privateKey = $this->generator->generatePrivateKey($keyOption); } catch (KeyGenerationException $e) { throw new KeyPairGenerationException('Fail to generate a KeyPair with the given options', 0, $e); } return new KeyPair( $privateKey->getPublicKey(), $privateKey ); }
php
public function generateKeyPair($keyOption = null) { if (null === $keyOption) { $keyOption = new RsaKeyOption(); } if (\is_int($keyOption)) { @trigger_error('Passing a keySize to "generateKeyPair" is deprecated since version 1.1 and will be removed in 2.0. Pass an instance of KeyOption instead', E_USER_DEPRECATED); $keyOption = new RsaKeyOption($keyOption); } Assert::isInstanceOf($keyOption, KeyOption::class); try { $privateKey = $this->generator->generatePrivateKey($keyOption); } catch (KeyGenerationException $e) { throw new KeyPairGenerationException('Fail to generate a KeyPair with the given options', 0, $e); } return new KeyPair( $privateKey->getPublicKey(), $privateKey ); }
[ "public", "function", "generateKeyPair", "(", "$", "keyOption", "=", "null", ")", "{", "if", "(", "null", "===", "$", "keyOption", ")", "{", "$", "keyOption", "=", "new", "RsaKeyOption", "(", ")", ";", "}", "if", "(", "\\", "is_int", "(", "$", "keyOption", ")", ")", "{", "@", "trigger_error", "(", "'Passing a keySize to \"generateKeyPair\" is deprecated since version 1.1 and will be removed in 2.0. Pass an instance of KeyOption instead'", ",", "E_USER_DEPRECATED", ")", ";", "$", "keyOption", "=", "new", "RsaKeyOption", "(", "$", "keyOption", ")", ";", "}", "Assert", "::", "isInstanceOf", "(", "$", "keyOption", ",", "KeyOption", "::", "class", ")", ";", "try", "{", "$", "privateKey", "=", "$", "this", "->", "generator", "->", "generatePrivateKey", "(", "$", "keyOption", ")", ";", "}", "catch", "(", "KeyGenerationException", "$", "e", ")", "{", "throw", "new", "KeyPairGenerationException", "(", "'Fail to generate a KeyPair with the given options'", ",", "0", ",", "$", "e", ")", ";", "}", "return", "new", "KeyPair", "(", "$", "privateKey", "->", "getPublicKey", "(", ")", ",", "$", "privateKey", ")", ";", "}" ]
Generate KeyPair. @param KeyOption $keyOption configuration of the key to generate @throws KeyPairGenerationException when OpenSSL failed to generate keys @return KeyPair
[ "Generate", "KeyPair", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Generator/KeyPairGenerator.php#L54-L75
train
acmephp/ssl
Parser/KeyParser.php
KeyParser.parse
public function parse(Key $key) { try { $resource = $key->getResource(); } catch (KeyFormatException $e) { throw new KeyParsingException('Fail to load resource for key', 0, $e); } $rawData = openssl_pkey_get_details($resource); openssl_free_key($resource); if (!\is_array($rawData)) { throw new KeyParsingException(sprintf('Fail to parse key with error: %s', openssl_error_string())); } foreach (['type', 'key', 'bits'] as $requiredKey) { if (!isset($rawData[$requiredKey])) { throw new KeyParsingException(sprintf('Missing expected key "%s" in OpenSSL key', $requiredKey)); } } $details = []; if (OPENSSL_KEYTYPE_RSA === $rawData['type']) { $details = $rawData['rsa']; } elseif (OPENSSL_KEYTYPE_DSA === $rawData['type']) { $details = $rawData['dsa']; } elseif (OPENSSL_KEYTYPE_DH === $rawData['type']) { $details = $rawData['dh']; } elseif (OPENSSL_KEYTYPE_EC === $rawData['type']) { $details = $rawData['ec']; } return new ParsedKey($key, $rawData['key'], $rawData['bits'], $rawData['type'], $details); }
php
public function parse(Key $key) { try { $resource = $key->getResource(); } catch (KeyFormatException $e) { throw new KeyParsingException('Fail to load resource for key', 0, $e); } $rawData = openssl_pkey_get_details($resource); openssl_free_key($resource); if (!\is_array($rawData)) { throw new KeyParsingException(sprintf('Fail to parse key with error: %s', openssl_error_string())); } foreach (['type', 'key', 'bits'] as $requiredKey) { if (!isset($rawData[$requiredKey])) { throw new KeyParsingException(sprintf('Missing expected key "%s" in OpenSSL key', $requiredKey)); } } $details = []; if (OPENSSL_KEYTYPE_RSA === $rawData['type']) { $details = $rawData['rsa']; } elseif (OPENSSL_KEYTYPE_DSA === $rawData['type']) { $details = $rawData['dsa']; } elseif (OPENSSL_KEYTYPE_DH === $rawData['type']) { $details = $rawData['dh']; } elseif (OPENSSL_KEYTYPE_EC === $rawData['type']) { $details = $rawData['ec']; } return new ParsedKey($key, $rawData['key'], $rawData['bits'], $rawData['type'], $details); }
[ "public", "function", "parse", "(", "Key", "$", "key", ")", "{", "try", "{", "$", "resource", "=", "$", "key", "->", "getResource", "(", ")", ";", "}", "catch", "(", "KeyFormatException", "$", "e", ")", "{", "throw", "new", "KeyParsingException", "(", "'Fail to load resource for key'", ",", "0", ",", "$", "e", ")", ";", "}", "$", "rawData", "=", "openssl_pkey_get_details", "(", "$", "resource", ")", ";", "openssl_free_key", "(", "$", "resource", ")", ";", "if", "(", "!", "\\", "is_array", "(", "$", "rawData", ")", ")", "{", "throw", "new", "KeyParsingException", "(", "sprintf", "(", "'Fail to parse key with error: %s'", ",", "openssl_error_string", "(", ")", ")", ")", ";", "}", "foreach", "(", "[", "'type'", ",", "'key'", ",", "'bits'", "]", "as", "$", "requiredKey", ")", "{", "if", "(", "!", "isset", "(", "$", "rawData", "[", "$", "requiredKey", "]", ")", ")", "{", "throw", "new", "KeyParsingException", "(", "sprintf", "(", "'Missing expected key \"%s\" in OpenSSL key'", ",", "$", "requiredKey", ")", ")", ";", "}", "}", "$", "details", "=", "[", "]", ";", "if", "(", "OPENSSL_KEYTYPE_RSA", "===", "$", "rawData", "[", "'type'", "]", ")", "{", "$", "details", "=", "$", "rawData", "[", "'rsa'", "]", ";", "}", "elseif", "(", "OPENSSL_KEYTYPE_DSA", "===", "$", "rawData", "[", "'type'", "]", ")", "{", "$", "details", "=", "$", "rawData", "[", "'dsa'", "]", ";", "}", "elseif", "(", "OPENSSL_KEYTYPE_DH", "===", "$", "rawData", "[", "'type'", "]", ")", "{", "$", "details", "=", "$", "rawData", "[", "'dh'", "]", ";", "}", "elseif", "(", "OPENSSL_KEYTYPE_EC", "===", "$", "rawData", "[", "'type'", "]", ")", "{", "$", "details", "=", "$", "rawData", "[", "'ec'", "]", ";", "}", "return", "new", "ParsedKey", "(", "$", "key", ",", "$", "rawData", "[", "'key'", "]", ",", "$", "rawData", "[", "'bits'", "]", ",", "$", "rawData", "[", "'type'", "]", ",", "$", "details", ")", ";", "}" ]
Parse the key. @param Key $key @return ParsedKey
[ "Parse", "the", "key", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Parser/KeyParser.php#L33-L67
train
acmephp/ssl
Parser/CertificateParser.php
CertificateParser.parse
public function parse(Certificate $certificate) { $rawData = openssl_x509_parse($certificate->getPEM()); if (!\is_array($rawData)) { throw new CertificateParsingException( sprintf('Fail to parse certificate with error: %s', openssl_error_string()) ); } if (!isset($rawData['subject']['CN'])) { throw new CertificateParsingException('Missing expected key "subject.cn" in certificate'); } if (!isset($rawData['serialNumber'])) { throw new CertificateParsingException('Missing expected key "serialNumber" in certificate'); } if (!isset($rawData['validFrom_time_t'])) { throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate'); } if (!isset($rawData['validTo_time_t'])) { throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate'); } $subjectAlternativeName = []; if (isset($rawData['extensions']['subjectAltName'])) { $subjectAlternativeName = array_map( function ($item) { return explode(':', trim($item), 2)[1]; }, array_filter( explode( ',', $rawData['extensions']['subjectAltName'] ), function ($item) { return false !== strpos($item, ':'); } ) ); } return new ParsedCertificate( $certificate, $rawData['subject']['CN'], isset($rawData['issuer']['CN']) ? $rawData['issuer']['CN'] : null, $rawData['subject'] === $rawData['issuer'], new \DateTime('@'.$rawData['validFrom_time_t']), new \DateTime('@'.$rawData['validTo_time_t']), $rawData['serialNumber'], $subjectAlternativeName ); }
php
public function parse(Certificate $certificate) { $rawData = openssl_x509_parse($certificate->getPEM()); if (!\is_array($rawData)) { throw new CertificateParsingException( sprintf('Fail to parse certificate with error: %s', openssl_error_string()) ); } if (!isset($rawData['subject']['CN'])) { throw new CertificateParsingException('Missing expected key "subject.cn" in certificate'); } if (!isset($rawData['serialNumber'])) { throw new CertificateParsingException('Missing expected key "serialNumber" in certificate'); } if (!isset($rawData['validFrom_time_t'])) { throw new CertificateParsingException('Missing expected key "validFrom_time_t" in certificate'); } if (!isset($rawData['validTo_time_t'])) { throw new CertificateParsingException('Missing expected key "validTo_time_t" in certificate'); } $subjectAlternativeName = []; if (isset($rawData['extensions']['subjectAltName'])) { $subjectAlternativeName = array_map( function ($item) { return explode(':', trim($item), 2)[1]; }, array_filter( explode( ',', $rawData['extensions']['subjectAltName'] ), function ($item) { return false !== strpos($item, ':'); } ) ); } return new ParsedCertificate( $certificate, $rawData['subject']['CN'], isset($rawData['issuer']['CN']) ? $rawData['issuer']['CN'] : null, $rawData['subject'] === $rawData['issuer'], new \DateTime('@'.$rawData['validFrom_time_t']), new \DateTime('@'.$rawData['validTo_time_t']), $rawData['serialNumber'], $subjectAlternativeName ); }
[ "public", "function", "parse", "(", "Certificate", "$", "certificate", ")", "{", "$", "rawData", "=", "openssl_x509_parse", "(", "$", "certificate", "->", "getPEM", "(", ")", ")", ";", "if", "(", "!", "\\", "is_array", "(", "$", "rawData", ")", ")", "{", "throw", "new", "CertificateParsingException", "(", "sprintf", "(", "'Fail to parse certificate with error: %s'", ",", "openssl_error_string", "(", ")", ")", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "rawData", "[", "'subject'", "]", "[", "'CN'", "]", ")", ")", "{", "throw", "new", "CertificateParsingException", "(", "'Missing expected key \"subject.cn\" in certificate'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "rawData", "[", "'serialNumber'", "]", ")", ")", "{", "throw", "new", "CertificateParsingException", "(", "'Missing expected key \"serialNumber\" in certificate'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "rawData", "[", "'validFrom_time_t'", "]", ")", ")", "{", "throw", "new", "CertificateParsingException", "(", "'Missing expected key \"validFrom_time_t\" in certificate'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "rawData", "[", "'validTo_time_t'", "]", ")", ")", "{", "throw", "new", "CertificateParsingException", "(", "'Missing expected key \"validTo_time_t\" in certificate'", ")", ";", "}", "$", "subjectAlternativeName", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "rawData", "[", "'extensions'", "]", "[", "'subjectAltName'", "]", ")", ")", "{", "$", "subjectAlternativeName", "=", "array_map", "(", "function", "(", "$", "item", ")", "{", "return", "explode", "(", "':'", ",", "trim", "(", "$", "item", ")", ",", "2", ")", "[", "1", "]", ";", "}", ",", "array_filter", "(", "explode", "(", "','", ",", "$", "rawData", "[", "'extensions'", "]", "[", "'subjectAltName'", "]", ")", ",", "function", "(", "$", "item", ")", "{", "return", "false", "!==", "strpos", "(", "$", "item", ",", "':'", ")", ";", "}", ")", ")", ";", "}", "return", "new", "ParsedCertificate", "(", "$", "certificate", ",", "$", "rawData", "[", "'subject'", "]", "[", "'CN'", "]", ",", "isset", "(", "$", "rawData", "[", "'issuer'", "]", "[", "'CN'", "]", ")", "?", "$", "rawData", "[", "'issuer'", "]", "[", "'CN'", "]", ":", "null", ",", "$", "rawData", "[", "'subject'", "]", "===", "$", "rawData", "[", "'issuer'", "]", ",", "new", "\\", "DateTime", "(", "'@'", ".", "$", "rawData", "[", "'validFrom_time_t'", "]", ")", ",", "new", "\\", "DateTime", "(", "'@'", ".", "$", "rawData", "[", "'validTo_time_t'", "]", ")", ",", "$", "rawData", "[", "'serialNumber'", "]", ",", "$", "subjectAlternativeName", ")", ";", "}" ]
Parse the certificate. @param Certificate $certificate @return ParsedCertificate
[ "Parse", "the", "certificate", "." ]
c322ce61dd399fc451f733ee11873907d1f030a1
https://github.com/acmephp/ssl/blob/c322ce61dd399fc451f733ee11873907d1f030a1/Parser/CertificateParser.php#L32-L84
train
Prezent/soap-client
src/Extension/WSAddressing.php
WSAddressing.onWsdlResponse
public function onWsdlResponse(WsdlResponseEvent $event) { $xpath = new \DOMXPath($event->getWsdl()); $xpath->registerNamespace('wsaw', self::NS_WSAW); // This is a pretty dumb check. Just see if a wsaw:Addressing or wsaw:UsingAddressing tag exists if ($xpath->query('//wsaw:Addressing')->length || $xpath->query('//wsaw:UsingAddressing')->length) { $this->wsaEnabled = true; } }
php
public function onWsdlResponse(WsdlResponseEvent $event) { $xpath = new \DOMXPath($event->getWsdl()); $xpath->registerNamespace('wsaw', self::NS_WSAW); // This is a pretty dumb check. Just see if a wsaw:Addressing or wsaw:UsingAddressing tag exists if ($xpath->query('//wsaw:Addressing')->length || $xpath->query('//wsaw:UsingAddressing')->length) { $this->wsaEnabled = true; } }
[ "public", "function", "onWsdlResponse", "(", "WsdlResponseEvent", "$", "event", ")", "{", "$", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "event", "->", "getWsdl", "(", ")", ")", ";", "$", "xpath", "->", "registerNamespace", "(", "'wsaw'", ",", "self", "::", "NS_WSAW", ")", ";", "// This is a pretty dumb check. Just see if a wsaw:Addressing or wsaw:UsingAddressing tag exists", "if", "(", "$", "xpath", "->", "query", "(", "'//wsaw:Addressing'", ")", "->", "length", "||", "$", "xpath", "->", "query", "(", "'//wsaw:UsingAddressing'", ")", "->", "length", ")", "{", "$", "this", "->", "wsaEnabled", "=", "true", ";", "}", "}" ]
Parse the WSDL to check if WS-Addressing should be enabled @param WsdlResponseEvent $event @return void
[ "Parse", "the", "WSDL", "to", "check", "if", "WS", "-", "Addressing", "should", "be", "enabled" ]
4713398e44372b218e2eccd1f7d5ca070f803681
https://github.com/Prezent/soap-client/blob/4713398e44372b218e2eccd1f7d5ca070f803681/src/Extension/WSAddressing.php#L75-L84
train
Prezent/soap-client
src/Extension/WSAddressing.php
WSAddressing.onRequest
public function onRequest(RequestEvent $event) { if (!$this->wsaEnabled) { return; } $request = $event->getRequest(); $envelope = $request->documentElement; $soapNS = $envelope->namespaceURI; $xpath = new \DOMXPath($event->getRequest()); $xpath->registerNamespace('soap', $soapNS); $xpath->registerNamespace('wsa', self::NS_WSA); // Add WSA namespace to envelope $envelope->setAttributeNS(self::NS_XMLNS, 'xmlns:wsa', self::NS_WSA); // Find or create header $headers = $xpath->query('//soap:Envelope/soap:Header'); $header = $headers->item(0); if (!$header) { $header = $request->createElementNS($soapNS, $envelope->prefix . ':Header'); $envelope->insertBefore($header, $envelope->firstChild); } // Add MessageID $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:MessageID', 'uuid:' . Uuid::uuid4())); // Add Action $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Action', $event->getAction())); // Add To $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:To', $event->getLocation())); // Add From if (false !== $this->getFrom()) { // use anonymous when set to true, given address otherwise $fromAddress = $this->getFrom() === true ? self::ANONYMOUS : $this->getFrom(); $from = $request->createElementNS(self::NS_WSA, 'wsa:From'); $from->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Address', $fromAddress)); $header->appendChild($from); } // Add ReplyTo if (!$event->isOneWay()) { $address = $this->address ?: self::ANONYMOUS; $replyTo = $request->createElementNS(self::NS_WSA, 'wsa:ReplyTo'); $replyTo->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Address', $address)); $header->appendChild($replyTo); } }
php
public function onRequest(RequestEvent $event) { if (!$this->wsaEnabled) { return; } $request = $event->getRequest(); $envelope = $request->documentElement; $soapNS = $envelope->namespaceURI; $xpath = new \DOMXPath($event->getRequest()); $xpath->registerNamespace('soap', $soapNS); $xpath->registerNamespace('wsa', self::NS_WSA); // Add WSA namespace to envelope $envelope->setAttributeNS(self::NS_XMLNS, 'xmlns:wsa', self::NS_WSA); // Find or create header $headers = $xpath->query('//soap:Envelope/soap:Header'); $header = $headers->item(0); if (!$header) { $header = $request->createElementNS($soapNS, $envelope->prefix . ':Header'); $envelope->insertBefore($header, $envelope->firstChild); } // Add MessageID $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:MessageID', 'uuid:' . Uuid::uuid4())); // Add Action $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Action', $event->getAction())); // Add To $header->appendChild($request->createElementNS(self::NS_WSA, 'wsa:To', $event->getLocation())); // Add From if (false !== $this->getFrom()) { // use anonymous when set to true, given address otherwise $fromAddress = $this->getFrom() === true ? self::ANONYMOUS : $this->getFrom(); $from = $request->createElementNS(self::NS_WSA, 'wsa:From'); $from->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Address', $fromAddress)); $header->appendChild($from); } // Add ReplyTo if (!$event->isOneWay()) { $address = $this->address ?: self::ANONYMOUS; $replyTo = $request->createElementNS(self::NS_WSA, 'wsa:ReplyTo'); $replyTo->appendChild($request->createElementNS(self::NS_WSA, 'wsa:Address', $address)); $header->appendChild($replyTo); } }
[ "public", "function", "onRequest", "(", "RequestEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "wsaEnabled", ")", "{", "return", ";", "}", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";", "$", "envelope", "=", "$", "request", "->", "documentElement", ";", "$", "soapNS", "=", "$", "envelope", "->", "namespaceURI", ";", "$", "xpath", "=", "new", "\\", "DOMXPath", "(", "$", "event", "->", "getRequest", "(", ")", ")", ";", "$", "xpath", "->", "registerNamespace", "(", "'soap'", ",", "$", "soapNS", ")", ";", "$", "xpath", "->", "registerNamespace", "(", "'wsa'", ",", "self", "::", "NS_WSA", ")", ";", "// Add WSA namespace to envelope", "$", "envelope", "->", "setAttributeNS", "(", "self", "::", "NS_XMLNS", ",", "'xmlns:wsa'", ",", "self", "::", "NS_WSA", ")", ";", "// Find or create header", "$", "headers", "=", "$", "xpath", "->", "query", "(", "'//soap:Envelope/soap:Header'", ")", ";", "$", "header", "=", "$", "headers", "->", "item", "(", "0", ")", ";", "if", "(", "!", "$", "header", ")", "{", "$", "header", "=", "$", "request", "->", "createElementNS", "(", "$", "soapNS", ",", "$", "envelope", "->", "prefix", ".", "':Header'", ")", ";", "$", "envelope", "->", "insertBefore", "(", "$", "header", ",", "$", "envelope", "->", "firstChild", ")", ";", "}", "// Add MessageID", "$", "header", "->", "appendChild", "(", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:MessageID'", ",", "'uuid:'", ".", "Uuid", "::", "uuid4", "(", ")", ")", ")", ";", "// Add Action", "$", "header", "->", "appendChild", "(", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:Action'", ",", "$", "event", "->", "getAction", "(", ")", ")", ")", ";", "// Add To", "$", "header", "->", "appendChild", "(", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:To'", ",", "$", "event", "->", "getLocation", "(", ")", ")", ")", ";", "// Add From", "if", "(", "false", "!==", "$", "this", "->", "getFrom", "(", ")", ")", "{", "// use anonymous when set to true, given address otherwise", "$", "fromAddress", "=", "$", "this", "->", "getFrom", "(", ")", "===", "true", "?", "self", "::", "ANONYMOUS", ":", "$", "this", "->", "getFrom", "(", ")", ";", "$", "from", "=", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:From'", ")", ";", "$", "from", "->", "appendChild", "(", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:Address'", ",", "$", "fromAddress", ")", ")", ";", "$", "header", "->", "appendChild", "(", "$", "from", ")", ";", "}", "// Add ReplyTo", "if", "(", "!", "$", "event", "->", "isOneWay", "(", ")", ")", "{", "$", "address", "=", "$", "this", "->", "address", "?", ":", "self", "::", "ANONYMOUS", ";", "$", "replyTo", "=", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:ReplyTo'", ")", ";", "$", "replyTo", "->", "appendChild", "(", "$", "request", "->", "createElementNS", "(", "self", "::", "NS_WSA", ",", "'wsa:Address'", ",", "$", "address", ")", ")", ";", "$", "header", "->", "appendChild", "(", "$", "replyTo", ")", ";", "}", "}" ]
Add WS-Addressing headers to the request @param RequestEvent $event @return void
[ "Add", "WS", "-", "Addressing", "headers", "to", "the", "request" ]
4713398e44372b218e2eccd1f7d5ca070f803681
https://github.com/Prezent/soap-client/blob/4713398e44372b218e2eccd1f7d5ca070f803681/src/Extension/WSAddressing.php#L92-L145
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.enableTotp
public function enableTotp(Request $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); if (! $secret = array_get($twoFactor, 'totp.secret')) { $twoFactor['totp'] = [ 'enabled' => false, 'secret' => $secret = $totpProvider->generateSecretKey(), ]; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); } $qrCode = $totpProvider->getQRCodeInline(config('app.name'), $currentUser->email, $secret); return view('cortex/auth::adminarea.pages.account-twofactor-totp', compact('secret', 'qrCode', 'twoFactor')); }
php
public function enableTotp(Request $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); if (! $secret = array_get($twoFactor, 'totp.secret')) { $twoFactor['totp'] = [ 'enabled' => false, 'secret' => $secret = $totpProvider->generateSecretKey(), ]; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); } $qrCode = $totpProvider->getQRCodeInline(config('app.name'), $currentUser->email, $secret); return view('cortex/auth::adminarea.pages.account-twofactor-totp', compact('secret', 'qrCode', 'twoFactor')); }
[ "public", "function", "enableTotp", "(", "Request", "$", "request", ",", "Google2FA", "$", "totpProvider", ")", "{", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "$", "twoFactor", "=", "$", "currentUser", "->", "getTwoFactor", "(", ")", ";", "if", "(", "!", "$", "secret", "=", "array_get", "(", "$", "twoFactor", ",", "'totp.secret'", ")", ")", "{", "$", "twoFactor", "[", "'totp'", "]", "=", "[", "'enabled'", "=>", "false", ",", "'secret'", "=>", "$", "secret", "=", "$", "totpProvider", "->", "generateSecretKey", "(", ")", ",", "]", ";", "$", "currentUser", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "}", "$", "qrCode", "=", "$", "totpProvider", "->", "getQRCodeInline", "(", "config", "(", "'app.name'", ")", ",", "$", "currentUser", "->", "email", ",", "$", "secret", ")", ";", "return", "view", "(", "'cortex/auth::adminarea.pages.account-twofactor-totp'", ",", "compact", "(", "'secret'", ",", "'qrCode'", ",", "'twoFactor'", ")", ")", ";", "}" ]
Enable TwoFactor TOTP authentication. @param \Illuminate\Http\Request $request @param \PragmaRX\Google2FA\Google2FA $totpProvider @return \Illuminate\View\View
[ "Enable", "TwoFactor", "TOTP", "authentication", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L38-L55
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.updateTotp
public function updateTotp(AccountTwoFactorTotpProcessRequest $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $secret = array_get($twoFactor, 'totp.secret'); $backup = array_get($twoFactor, 'totp.backup'); $backupAt = array_get($twoFactor, 'totp.backup_at'); if ($totpProvider->verifyKey($secret, $request->get('token'))) { $twoFactor['totp'] = [ 'enabled' => true, 'secret' => $secret, 'backup' => $backup ?? $this->generateTotpBackups(), 'backup_at' => $backupAt ?? now()->toDateTimeString(), ]; // Update TwoFactor settings $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.enabled')], ]); } return intend([ 'back' => true, 'withErrors' => ['token' => trans('cortex/auth::messages.verification.twofactor.totp.invalid_token')], ]); }
php
public function updateTotp(AccountTwoFactorTotpProcessRequest $request, Google2FA $totpProvider) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $secret = array_get($twoFactor, 'totp.secret'); $backup = array_get($twoFactor, 'totp.backup'); $backupAt = array_get($twoFactor, 'totp.backup_at'); if ($totpProvider->verifyKey($secret, $request->get('token'))) { $twoFactor['totp'] = [ 'enabled' => true, 'secret' => $secret, 'backup' => $backup ?? $this->generateTotpBackups(), 'backup_at' => $backupAt ?? now()->toDateTimeString(), ]; // Update TwoFactor settings $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.enabled')], ]); } return intend([ 'back' => true, 'withErrors' => ['token' => trans('cortex/auth::messages.verification.twofactor.totp.invalid_token')], ]); }
[ "public", "function", "updateTotp", "(", "AccountTwoFactorTotpProcessRequest", "$", "request", ",", "Google2FA", "$", "totpProvider", ")", "{", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "$", "twoFactor", "=", "$", "currentUser", "->", "getTwoFactor", "(", ")", ";", "$", "secret", "=", "array_get", "(", "$", "twoFactor", ",", "'totp.secret'", ")", ";", "$", "backup", "=", "array_get", "(", "$", "twoFactor", ",", "'totp.backup'", ")", ";", "$", "backupAt", "=", "array_get", "(", "$", "twoFactor", ",", "'totp.backup_at'", ")", ";", "if", "(", "$", "totpProvider", "->", "verifyKey", "(", "$", "secret", ",", "$", "request", "->", "get", "(", "'token'", ")", ")", ")", "{", "$", "twoFactor", "[", "'totp'", "]", "=", "[", "'enabled'", "=>", "true", ",", "'secret'", "=>", "$", "secret", ",", "'backup'", "=>", "$", "backup", "??", "$", "this", "->", "generateTotpBackups", "(", ")", ",", "'backup_at'", "=>", "$", "backupAt", "??", "now", "(", ")", "->", "toDateTimeString", "(", ")", ",", "]", ";", "// Update TwoFactor settings", "$", "currentUser", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.totp.enabled'", ")", "]", ",", "]", ")", ";", "}", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'withErrors'", "=>", "[", "'token'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.totp.invalid_token'", ")", "]", ",", "]", ")", ";", "}" ]
Process the TwoFactor TOTP enable form. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorTotpProcessRequest $request @param \PragmaRX\Google2FA\Google2FA $totpProvider @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Process", "the", "TwoFactor", "TOTP", "enable", "form", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L86-L115
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.backupTotp
public function backupTotp(AccountTwoFactorTotpBackupRequest $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['totp']['backup'] = $this->generateTotpBackups(); $twoFactor['totp']['backup_at'] = now()->toDateTimeString(); $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.rebackup')], ]); }
php
public function backupTotp(AccountTwoFactorTotpBackupRequest $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['totp']['backup'] = $this->generateTotpBackups(); $twoFactor['totp']['backup_at'] = now()->toDateTimeString(); $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.totp.rebackup')], ]); }
[ "public", "function", "backupTotp", "(", "AccountTwoFactorTotpBackupRequest", "$", "request", ")", "{", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "$", "twoFactor", "=", "$", "currentUser", "->", "getTwoFactor", "(", ")", ";", "$", "twoFactor", "[", "'totp'", "]", "[", "'backup'", "]", "=", "$", "this", "->", "generateTotpBackups", "(", ")", ";", "$", "twoFactor", "[", "'totp'", "]", "[", "'backup_at'", "]", "=", "now", "(", ")", "->", "toDateTimeString", "(", ")", ";", "$", "currentUser", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.totp.rebackup'", ")", "]", ",", "]", ")", ";", "}" ]
Process the TwoFactor OTP backup. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorTotpBackupRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Process", "the", "TwoFactor", "OTP", "backup", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L124-L137
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.enablePhone
public function enablePhone(AccountTwoFactorPhoneRequest $request) { $currentUser = $request->user($this->getGuard()); $currentUser->routeNotificationForAuthy(); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = true; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.enabled')], ]); }
php
public function enablePhone(AccountTwoFactorPhoneRequest $request) { $currentUser = $request->user($this->getGuard()); $currentUser->routeNotificationForAuthy(); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = true; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.enabled')], ]); }
[ "public", "function", "enablePhone", "(", "AccountTwoFactorPhoneRequest", "$", "request", ")", "{", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "$", "currentUser", "->", "routeNotificationForAuthy", "(", ")", ";", "$", "twoFactor", "=", "$", "currentUser", "->", "getTwoFactor", "(", ")", ";", "$", "twoFactor", "[", "'phone'", "]", "[", "'enabled'", "]", "=", "true", ";", "$", "currentUser", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.phone.enabled'", ")", "]", ",", "]", ")", ";", "}" ]
Enable TwoFactor Phone authentication. @param \Cortex\Auth\Http\Requests\Adminarea\AccountTwoFactorPhoneRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Enable", "TwoFactor", "Phone", "authentication", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L146-L159
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.disablePhone
public function disablePhone(Request $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = false; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.disabled')], ]); }
php
public function disablePhone(Request $request) { $currentUser = $request->user($this->getGuard()); $twoFactor = $currentUser->getTwoFactor(); $twoFactor['phone']['enabled'] = false; $currentUser->fill(['two_factor' => $twoFactor])->forceSave(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.verification.twofactor.phone.disabled')], ]); }
[ "public", "function", "disablePhone", "(", "Request", "$", "request", ")", "{", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "$", "twoFactor", "=", "$", "currentUser", "->", "getTwoFactor", "(", ")", ";", "$", "twoFactor", "[", "'phone'", "]", "[", "'enabled'", "]", "=", "false", ";", "$", "currentUser", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.phone.disabled'", ")", "]", ",", "]", ")", ";", "}" ]
Disable TwoFactor Phone authentication. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Disable", "TwoFactor", "Phone", "authentication", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L168-L180
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountTwoFactorController.php
AccountTwoFactorController.generateTotpBackups
protected function generateTotpBackups(): array { $backup = []; for ($x = 0; $x <= 9; $x++) { $backup[] = str_pad((string) random_int(0, 9999999999), 10, '0', STR_PAD_BOTH); } return $backup; }
php
protected function generateTotpBackups(): array { $backup = []; for ($x = 0; $x <= 9; $x++) { $backup[] = str_pad((string) random_int(0, 9999999999), 10, '0', STR_PAD_BOTH); } return $backup; }
[ "protected", "function", "generateTotpBackups", "(", ")", ":", "array", "{", "$", "backup", "=", "[", "]", ";", "for", "(", "$", "x", "=", "0", ";", "$", "x", "<=", "9", ";", "$", "x", "++", ")", "{", "$", "backup", "[", "]", "=", "str_pad", "(", "(", "string", ")", "random_int", "(", "0", ",", "9999999999", ")", ",", "10", ",", "'0'", ",", "STR_PAD_BOTH", ")", ";", "}", "return", "$", "backup", ";", "}" ]
Generate TwoFactor OTP backup codes. @return array
[ "Generate", "TwoFactor", "OTP", "backup", "codes", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountTwoFactorController.php#L187-L196
train
Riimu/Kit-PHPEncoder
src/Encoder/IntegerEncoder.php
IntegerEncoder.encodeDecimal
public function encodeDecimal($integer, $options) { if ($integer === 1 << (\PHP_INT_SIZE * 8 - 1)) { return sprintf('(int)%s%d', $options['whitespace'] ? ' ' : '', $integer); } return var_export($integer, true); }
php
public function encodeDecimal($integer, $options) { if ($integer === 1 << (\PHP_INT_SIZE * 8 - 1)) { return sprintf('(int)%s%d', $options['whitespace'] ? ' ' : '', $integer); } return var_export($integer, true); }
[ "public", "function", "encodeDecimal", "(", "$", "integer", ",", "$", "options", ")", "{", "if", "(", "$", "integer", "===", "1", "<<", "(", "\\", "PHP_INT_SIZE", "*", "8", "-", "1", ")", ")", "{", "return", "sprintf", "(", "'(int)%s%d'", ",", "$", "options", "[", "'whitespace'", "]", "?", "' '", ":", "''", ",", "$", "integer", ")", ";", "}", "return", "var_export", "(", "$", "integer", ",", "true", ")", ";", "}" ]
Encodes an integer into decimal representation. @param int $integer The integer to encode @param array $options The integer encoding options @return string The PHP code representation for the integer
[ "Encodes", "an", "integer", "into", "decimal", "representation", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/IntegerEncoder.php#L89-L96
train
Riimu/Kit-PHPEncoder
src/Encoder/IntegerEncoder.php
IntegerEncoder.encodeHexadecimal
public function encodeHexadecimal($integer, $options) { if ($options['hex.capitalize']) { return sprintf('%s0x%X', $this->sign($integer), abs($integer)); } return sprintf('%s0x%x', $this->sign($integer), abs($integer)); }
php
public function encodeHexadecimal($integer, $options) { if ($options['hex.capitalize']) { return sprintf('%s0x%X', $this->sign($integer), abs($integer)); } return sprintf('%s0x%x', $this->sign($integer), abs($integer)); }
[ "public", "function", "encodeHexadecimal", "(", "$", "integer", ",", "$", "options", ")", "{", "if", "(", "$", "options", "[", "'hex.capitalize'", "]", ")", "{", "return", "sprintf", "(", "'%s0x%X'", ",", "$", "this", "->", "sign", "(", "$", "integer", ")", ",", "abs", "(", "$", "integer", ")", ")", ";", "}", "return", "sprintf", "(", "'%s0x%x'", ",", "$", "this", "->", "sign", "(", "$", "integer", ")", ",", "abs", "(", "$", "integer", ")", ")", ";", "}" ]
Encodes an integer into hexadecimal representation. @param int $integer The integer to encode @param array $options The integer encoding options @return string The PHP code representation for the integer
[ "Encodes", "an", "integer", "into", "hexadecimal", "representation", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/IntegerEncoder.php#L104-L111
train
rinvex/languages
src/Language.php
Language.getCulture
public function getCulture($culture = null): ?array { return $this->getCultures()[$culture] ?? (! empty($this->getCultures()) ? current($this->getCultures()) : null); }
php
public function getCulture($culture = null): ?array { return $this->getCultures()[$culture] ?? (! empty($this->getCultures()) ? current($this->getCultures()) : null); }
[ "public", "function", "getCulture", "(", "$", "culture", "=", "null", ")", ":", "?", "array", "{", "return", "$", "this", "->", "getCultures", "(", ")", "[", "$", "culture", "]", "??", "(", "!", "empty", "(", "$", "this", "->", "getCultures", "(", ")", ")", "?", "current", "(", "$", "this", "->", "getCultures", "(", ")", ")", ":", "null", ")", ";", "}" ]
Get the given culture. @param string|null $culture @return array|null
[ "Get", "the", "given", "culture", "." ]
b4026ed41cb1950132c8061e80e549c2d3aa763f
https://github.com/rinvex/languages/blob/b4026ed41cb1950132c8061e80e549c2d3aa763f/src/Language.php#L283-L286
train
rinvex/laravel-menus
src/Models/MenuGenerator.php
MenuGenerator.divider
public function divider(int $order = null, array $attributes = []): MenuItem { return $this->add(['type' => 'divider', 'order' => $order, 'attributes' => $attributes]); }
php
public function divider(int $order = null, array $attributes = []): MenuItem { return $this->add(['type' => 'divider', 'order' => $order, 'attributes' => $attributes]); }
[ "public", "function", "divider", "(", "int", "$", "order", "=", "null", ",", "array", "$", "attributes", "=", "[", "]", ")", ":", "MenuItem", "{", "return", "$", "this", "->", "add", "(", "[", "'type'", "=>", "'divider'", ",", "'order'", "=>", "$", "order", ",", "'attributes'", "=>", "$", "attributes", "]", ")", ";", "}" ]
Add new divider item. @param int $order @param array $attributes @return \Rinvex\Menus\Models\MenuItem
[ "Add", "new", "divider", "item", "." ]
3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce
https://github.com/rinvex/laravel-menus/blob/3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce/src/Models/MenuGenerator.php#L338-L341
train
SimpleBus/RabbitMQBundleBridge
src/RabbitMQPublisher.php
RabbitMQPublisher.publish
public function publish($message) { $serializedMessage = $this->serializer->wrapAndSerialize($message); $routingKey = $this->routingKeyResolver->resolveRoutingKeyFor($message); $additionalProperties = $this->additionalPropertiesResolver->resolveAdditionalPropertiesFor($message); $this->producer->publish($serializedMessage, $routingKey, $additionalProperties); }
php
public function publish($message) { $serializedMessage = $this->serializer->wrapAndSerialize($message); $routingKey = $this->routingKeyResolver->resolveRoutingKeyFor($message); $additionalProperties = $this->additionalPropertiesResolver->resolveAdditionalPropertiesFor($message); $this->producer->publish($serializedMessage, $routingKey, $additionalProperties); }
[ "public", "function", "publish", "(", "$", "message", ")", "{", "$", "serializedMessage", "=", "$", "this", "->", "serializer", "->", "wrapAndSerialize", "(", "$", "message", ")", ";", "$", "routingKey", "=", "$", "this", "->", "routingKeyResolver", "->", "resolveRoutingKeyFor", "(", "$", "message", ")", ";", "$", "additionalProperties", "=", "$", "this", "->", "additionalPropertiesResolver", "->", "resolveAdditionalPropertiesFor", "(", "$", "message", ")", ";", "$", "this", "->", "producer", "->", "publish", "(", "$", "serializedMessage", ",", "$", "routingKey", ",", "$", "additionalProperties", ")", ";", "}" ]
Publish the given Message by serializing it and handing it over to a RabbitMQ producer @{inheritdoc}
[ "Publish", "the", "given", "Message", "by", "serializing", "it", "and", "handing", "it", "over", "to", "a", "RabbitMQ", "producer" ]
89dfcfd355bec78bbae0d558f2796e4b0b79e170
https://github.com/SimpleBus/RabbitMQBundleBridge/blob/89dfcfd355bec78bbae0d558f2796e4b0b79e170/src/RabbitMQPublisher.php#L57-L64
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/SocialAuthenticationController.php
SocialAuthenticationController.handleProviderCallback
public function handleProviderCallback(Request $request, string $provider) { $providerUser = Socialite::driver($provider)->user(); $fullName = explode(' ', $providerUser->name); $attributes = [ 'id' => $providerUser->id, 'email' => $providerUser->email, 'username' => $providerUser->nickname ?? trim(mb_strstr($providerUser->email, '@', true)), 'given_name' => current($fullName), 'family_name' => end($fullName), ]; switch ($provider) { case 'twitter': $attributes['title'] = $providerUser->user['description']; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'github': $attributes['title'] = $providerUser->user['bio']; $attributes['profile_picture'] = $providerUser->avatar; break; case 'facebook': $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'linkedin': $attributes['title'] = $providerUser->headline; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'google': $attributes['title'] = $providerUser->tagline; $attributes['profile_picture'] = $providerUser->avatar_original; break; } if (! ($localUser = $this->getLocalUser($provider, $providerUser->id))) { $localUser = $this->createLocalUser($provider, $attributes); } auth()->guard($this->getGuard())->login($localUser, true); return intend([ 'intended' => route('adminarea.home'), 'with' => ['success' => trans('cortex/auth::messages.auth.login')], ]); }
php
public function handleProviderCallback(Request $request, string $provider) { $providerUser = Socialite::driver($provider)->user(); $fullName = explode(' ', $providerUser->name); $attributes = [ 'id' => $providerUser->id, 'email' => $providerUser->email, 'username' => $providerUser->nickname ?? trim(mb_strstr($providerUser->email, '@', true)), 'given_name' => current($fullName), 'family_name' => end($fullName), ]; switch ($provider) { case 'twitter': $attributes['title'] = $providerUser->user['description']; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'github': $attributes['title'] = $providerUser->user['bio']; $attributes['profile_picture'] = $providerUser->avatar; break; case 'facebook': $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'linkedin': $attributes['title'] = $providerUser->headline; $attributes['profile_picture'] = $providerUser->avatar_original; break; case 'google': $attributes['title'] = $providerUser->tagline; $attributes['profile_picture'] = $providerUser->avatar_original; break; } if (! ($localUser = $this->getLocalUser($provider, $providerUser->id))) { $localUser = $this->createLocalUser($provider, $attributes); } auth()->guard($this->getGuard())->login($localUser, true); return intend([ 'intended' => route('adminarea.home'), 'with' => ['success' => trans('cortex/auth::messages.auth.login')], ]); }
[ "public", "function", "handleProviderCallback", "(", "Request", "$", "request", ",", "string", "$", "provider", ")", "{", "$", "providerUser", "=", "Socialite", "::", "driver", "(", "$", "provider", ")", "->", "user", "(", ")", ";", "$", "fullName", "=", "explode", "(", "' '", ",", "$", "providerUser", "->", "name", ")", ";", "$", "attributes", "=", "[", "'id'", "=>", "$", "providerUser", "->", "id", ",", "'email'", "=>", "$", "providerUser", "->", "email", ",", "'username'", "=>", "$", "providerUser", "->", "nickname", "??", "trim", "(", "mb_strstr", "(", "$", "providerUser", "->", "email", ",", "'@'", ",", "true", ")", ")", ",", "'given_name'", "=>", "current", "(", "$", "fullName", ")", ",", "'family_name'", "=>", "end", "(", "$", "fullName", ")", ",", "]", ";", "switch", "(", "$", "provider", ")", "{", "case", "'twitter'", ":", "$", "attributes", "[", "'title'", "]", "=", "$", "providerUser", "->", "user", "[", "'description'", "]", ";", "$", "attributes", "[", "'profile_picture'", "]", "=", "$", "providerUser", "->", "avatar_original", ";", "break", ";", "case", "'github'", ":", "$", "attributes", "[", "'title'", "]", "=", "$", "providerUser", "->", "user", "[", "'bio'", "]", ";", "$", "attributes", "[", "'profile_picture'", "]", "=", "$", "providerUser", "->", "avatar", ";", "break", ";", "case", "'facebook'", ":", "$", "attributes", "[", "'profile_picture'", "]", "=", "$", "providerUser", "->", "avatar_original", ";", "break", ";", "case", "'linkedin'", ":", "$", "attributes", "[", "'title'", "]", "=", "$", "providerUser", "->", "headline", ";", "$", "attributes", "[", "'profile_picture'", "]", "=", "$", "providerUser", "->", "avatar_original", ";", "break", ";", "case", "'google'", ":", "$", "attributes", "[", "'title'", "]", "=", "$", "providerUser", "->", "tagline", ";", "$", "attributes", "[", "'profile_picture'", "]", "=", "$", "providerUser", "->", "avatar_original", ";", "break", ";", "}", "if", "(", "!", "(", "$", "localUser", "=", "$", "this", "->", "getLocalUser", "(", "$", "provider", ",", "$", "providerUser", "->", "id", ")", ")", ")", "{", "$", "localUser", "=", "$", "this", "->", "createLocalUser", "(", "$", "provider", ",", "$", "attributes", ")", ";", "}", "auth", "(", ")", "->", "guard", "(", "$", "this", "->", "getGuard", "(", ")", ")", "->", "login", "(", "$", "localUser", ",", "true", ")", ";", "return", "intend", "(", "[", "'intended'", "=>", "route", "(", "'adminarea.home'", ")", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.auth.login'", ")", "]", ",", "]", ")", ";", "}" ]
Obtain the user information from Provider. @param \Illuminate\Http\Request $request @param string $provider @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Obtain", "the", "user", "information", "from", "Provider", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/SocialAuthenticationController.php#L35-L80
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/SocialAuthenticationController.php
SocialAuthenticationController.getLocalUser
protected function getLocalUser(string $provider, string $providerUserId) { return app('cortex.auth.admin')->whereHas('socialites', function (Builder $builder) use ($provider, $providerUserId) { $builder->where('provider', $provider)->where('provider_uid', $providerUserId); })->first(); }
php
protected function getLocalUser(string $provider, string $providerUserId) { return app('cortex.auth.admin')->whereHas('socialites', function (Builder $builder) use ($provider, $providerUserId) { $builder->where('provider', $provider)->where('provider_uid', $providerUserId); })->first(); }
[ "protected", "function", "getLocalUser", "(", "string", "$", "provider", ",", "string", "$", "providerUserId", ")", "{", "return", "app", "(", "'cortex.auth.admin'", ")", "->", "whereHas", "(", "'socialites'", ",", "function", "(", "Builder", "$", "builder", ")", "use", "(", "$", "provider", ",", "$", "providerUserId", ")", "{", "$", "builder", "->", "where", "(", "'provider'", ",", "$", "provider", ")", "->", "where", "(", "'provider_uid'", ",", "$", "providerUserId", ")", ";", "}", ")", "->", "first", "(", ")", ";", "}" ]
Get local user for the given provider. @param string $provider @param string $providerUserId @return \Illuminate\Database\Eloquent\Model|null
[ "Get", "local", "user", "for", "the", "given", "provider", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/SocialAuthenticationController.php#L90-L95
train
joomla-framework/authentication
src/Password/Argon2iHandler.php
Argon2iHandler.isSupported
public static function isSupported() { // Check for native PHP engine support in the password extension if (version_compare(PHP_VERSION, '7.2', '>=') && \defined('PASSWORD_ARGON2I')) { return true; } // Check if the sodium_compat polyfill is installed and look for compatibility through that if (class_exists('\\ParagonIE_Sodium_Compat') && method_exists('\\ParagonIE_Sodium_Compat', 'crypto_pwhash_is_available')) { return \ParagonIE_Sodium_Compat::crypto_pwhash_is_available(); } // Check for support from the (lib)sodium extension return \function_exists('sodium_crypto_pwhash_str') || \extension_loaded('libsodium'); }
php
public static function isSupported() { // Check for native PHP engine support in the password extension if (version_compare(PHP_VERSION, '7.2', '>=') && \defined('PASSWORD_ARGON2I')) { return true; } // Check if the sodium_compat polyfill is installed and look for compatibility through that if (class_exists('\\ParagonIE_Sodium_Compat') && method_exists('\\ParagonIE_Sodium_Compat', 'crypto_pwhash_is_available')) { return \ParagonIE_Sodium_Compat::crypto_pwhash_is_available(); } // Check for support from the (lib)sodium extension return \function_exists('sodium_crypto_pwhash_str') || \extension_loaded('libsodium'); }
[ "public", "static", "function", "isSupported", "(", ")", "{", "// Check for native PHP engine support in the password extension", "if", "(", "version_compare", "(", "PHP_VERSION", ",", "'7.2'", ",", "'>='", ")", "&&", "\\", "defined", "(", "'PASSWORD_ARGON2I'", ")", ")", "{", "return", "true", ";", "}", "// Check if the sodium_compat polyfill is installed and look for compatibility through that", "if", "(", "class_exists", "(", "'\\\\ParagonIE_Sodium_Compat'", ")", "&&", "method_exists", "(", "'\\\\ParagonIE_Sodium_Compat'", ",", "'crypto_pwhash_is_available'", ")", ")", "{", "return", "\\", "ParagonIE_Sodium_Compat", "::", "crypto_pwhash_is_available", "(", ")", ";", "}", "// Check for support from the (lib)sodium extension", "return", "\\", "function_exists", "(", "'sodium_crypto_pwhash_str'", ")", "||", "\\", "extension_loaded", "(", "'libsodium'", ")", ";", "}" ]
Check that the password handler is supported in this environment @return boolean @since 1.2.0
[ "Check", "that", "the", "password", "handler", "is", "supported", "in", "this", "environment" ]
5bf7ec56bddce28c3eb5b11b4b326709249324fb
https://github.com/joomla-framework/authentication/blob/5bf7ec56bddce28c3eb5b11b4b326709249324fb/src/Password/Argon2iHandler.php#L73-L89
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AuthenticationController.php
AuthenticationController.login
public function login(AuthenticationRequest $request) { // Prepare variables $loginField = get_login_field($request->input($this->username())); $credentials = [ 'is_active' => true, $loginField => $request->input('loginfield'), 'password' => $request->input('password'), ]; // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } if (auth()->guard($this->getGuard())->attempt($credentials, $request->filled('remember'))) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); }
php
public function login(AuthenticationRequest $request) { // Prepare variables $loginField = get_login_field($request->input($this->username())); $credentials = [ 'is_active' => true, $loginField => $request->input('loginfield'), 'password' => $request->input('password'), ]; // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } if (auth()->guard($this->getGuard())->attempt($credentials, $request->filled('remember'))) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. $this->incrementLoginAttempts($request); return $this->sendFailedLoginResponse($request); }
[ "public", "function", "login", "(", "AuthenticationRequest", "$", "request", ")", "{", "// Prepare variables", "$", "loginField", "=", "get_login_field", "(", "$", "request", "->", "input", "(", "$", "this", "->", "username", "(", ")", ")", ")", ";", "$", "credentials", "=", "[", "'is_active'", "=>", "true", ",", "$", "loginField", "=>", "$", "request", "->", "input", "(", "'loginfield'", ")", ",", "'password'", "=>", "$", "request", "->", "input", "(", "'password'", ")", ",", "]", ";", "// If the class is using the ThrottlesLogins trait, we can automatically throttle", "// the login attempts for this application. We'll key this by the username and", "// the IP address of the client making these requests into this application.", "if", "(", "$", "this", "->", "hasTooManyLoginAttempts", "(", "$", "request", ")", ")", "{", "$", "this", "->", "fireLockoutEvent", "(", "$", "request", ")", ";", "return", "$", "this", "->", "sendLockoutResponse", "(", "$", "request", ")", ";", "}", "if", "(", "auth", "(", ")", "->", "guard", "(", "$", "this", "->", "getGuard", "(", ")", ")", "->", "attempt", "(", "$", "credentials", ",", "$", "request", "->", "filled", "(", "'remember'", ")", ")", ")", "{", "return", "$", "this", "->", "sendLoginResponse", "(", "$", "request", ")", ";", "}", "// If the login attempt was unsuccessful we will increment the number of attempts", "// to login and redirect the user back to the login form. Of course, when this", "// user surpasses their maximum number of attempts they will get locked out.", "$", "this", "->", "incrementLoginAttempts", "(", "$", "request", ")", ";", "return", "$", "this", "->", "sendFailedLoginResponse", "(", "$", "request", ")", ";", "}" ]
Process to the login form. @param \Cortex\Auth\Http\Requests\Adminarea\AuthenticationRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Process", "to", "the", "login", "form", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AuthenticationController.php#L54-L83
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AuthenticationController.php
AuthenticationController.processLogout
protected function processLogout(Request $request): void { auth()->guard($this->getGuard())->logout(); $request->session()->invalidate(); }
php
protected function processLogout(Request $request): void { auth()->guard($this->getGuard())->logout(); $request->session()->invalidate(); }
[ "protected", "function", "processLogout", "(", "Request", "$", "request", ")", ":", "void", "{", "auth", "(", ")", "->", "guard", "(", "$", "this", "->", "getGuard", "(", ")", ")", "->", "logout", "(", ")", ";", "$", "request", "->", "session", "(", ")", "->", "invalidate", "(", ")", ";", "}" ]
Process logout. @param \Illuminate\Http\Request $request @return void
[ "Process", "logout", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AuthenticationController.php#L185-L190
train
rinvex/cortex-auth
src/Providers/AuthServiceProvider.php
AuthServiceProvider.overrideMiddleware
protected function overrideMiddleware(Router $router): void { // Append middleware to the 'web' middlware group $router->pushMiddlewareToGroup('web', UpdateLastActivity::class); // Override route middleware on the fly $router->aliasMiddleware('reauthenticate', Reauthenticate::class); $router->aliasMiddleware('guest', RedirectIfAuthenticated::class); }
php
protected function overrideMiddleware(Router $router): void { // Append middleware to the 'web' middlware group $router->pushMiddlewareToGroup('web', UpdateLastActivity::class); // Override route middleware on the fly $router->aliasMiddleware('reauthenticate', Reauthenticate::class); $router->aliasMiddleware('guest', RedirectIfAuthenticated::class); }
[ "protected", "function", "overrideMiddleware", "(", "Router", "$", "router", ")", ":", "void", "{", "// Append middleware to the 'web' middlware group", "$", "router", "->", "pushMiddlewareToGroup", "(", "'web'", ",", "UpdateLastActivity", "::", "class", ")", ";", "// Override route middleware on the fly", "$", "router", "->", "aliasMiddleware", "(", "'reauthenticate'", ",", "Reauthenticate", "::", "class", ")", ";", "$", "router", "->", "aliasMiddleware", "(", "'guest'", ",", "RedirectIfAuthenticated", "::", "class", ")", ";", "}" ]
Override middleware. @param \Illuminate\Routing\Router $router @return void
[ "Override", "middleware", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Providers/AuthServiceProvider.php#L232-L240
train
rinvex/laravel-menus
src/Models/MenuItem.php
MenuItem.ifCan
public function ifCan(string $ability, $params = null, $guard = null) { $this->hideCallbacks->push(function () use ($ability, $params, $guard) { return ! optional(auth()->guard($guard)->user())->can($ability, $params); }); return $this; }
php
public function ifCan(string $ability, $params = null, $guard = null) { $this->hideCallbacks->push(function () use ($ability, $params, $guard) { return ! optional(auth()->guard($guard)->user())->can($ability, $params); }); return $this; }
[ "public", "function", "ifCan", "(", "string", "$", "ability", ",", "$", "params", "=", "null", ",", "$", "guard", "=", "null", ")", "{", "$", "this", "->", "hideCallbacks", "->", "push", "(", "function", "(", ")", "use", "(", "$", "ability", ",", "$", "params", ",", "$", "guard", ")", "{", "return", "!", "optional", "(", "auth", "(", ")", "->", "guard", "(", "$", "guard", ")", "->", "user", "(", ")", ")", "->", "can", "(", "$", "ability", ",", "$", "params", ")", ";", "}", ")", ";", "return", "$", "this", ";", "}" ]
Set authorization callback for current menu item. @param string $ability @param mixed $params @param string $guard @return $this
[ "Set", "authorization", "callback", "for", "current", "menu", "item", "." ]
3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce
https://github.com/rinvex/laravel-menus/blob/3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce/src/Models/MenuItem.php#L254-L261
train
rinvex/laravel-menus
src/Models/MenuItem.php
MenuItem.activateOnRoute
public function activateOnRoute(string $route) { $this->activeWhen = function () use ($route) { return str_contains(Route::currentRouteName(), $route); }; return $this; }
php
public function activateOnRoute(string $route) { $this->activeWhen = function () use ($route) { return str_contains(Route::currentRouteName(), $route); }; return $this; }
[ "public", "function", "activateOnRoute", "(", "string", "$", "route", ")", "{", "$", "this", "->", "activeWhen", "=", "function", "(", ")", "use", "(", "$", "route", ")", "{", "return", "str_contains", "(", "Route", "::", "currentRouteName", "(", ")", ",", "$", "route", ")", ";", "}", ";", "return", "$", "this", ";", "}" ]
Set active callback on the given route. @param string $route @return $this
[ "Set", "active", "callback", "on", "the", "given", "route", "." ]
3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce
https://github.com/rinvex/laravel-menus/blob/3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce/src/Models/MenuItem.php#L362-L369
train
rinvex/laravel-menus
src/Models/MenuItem.php
MenuItem.add
protected function add(array $properties = []) { $properties['attributes']['id'] = $properties['attributes']['id'] ?? md5(json_encode($properties)); $this->childs->push($item = new static($properties)); return $item; }
php
protected function add(array $properties = []) { $properties['attributes']['id'] = $properties['attributes']['id'] ?? md5(json_encode($properties)); $this->childs->push($item = new static($properties)); return $item; }
[ "protected", "function", "add", "(", "array", "$", "properties", "=", "[", "]", ")", "{", "$", "properties", "[", "'attributes'", "]", "[", "'id'", "]", "=", "$", "properties", "[", "'attributes'", "]", "[", "'id'", "]", "??", "md5", "(", "json_encode", "(", "$", "properties", ")", ")", ";", "$", "this", "->", "childs", "->", "push", "(", "$", "item", "=", "new", "static", "(", "$", "properties", ")", ")", ";", "return", "$", "item", ";", "}" ]
Add new child item. @param array $properties @return static
[ "Add", "new", "child", "item", "." ]
3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce
https://github.com/rinvex/laravel-menus/blob/3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce/src/Models/MenuItem.php#L378-L384
train
rinvex/laravel-menus
src/Models/MenuItem.php
MenuItem.hasActiveStateFromChilds
protected function hasActiveStateFromChilds(): bool { return $this->getChilds()->contains(function (MenuItem $child) { return ($child->hasChilds() && $child->hasActiveStateFromChilds()) || ($child->route && $child->hasActiveStateFromRoute()) || $child->isActive() || $child->hasActiveStateFromUrl(); }) ?? false; }
php
protected function hasActiveStateFromChilds(): bool { return $this->getChilds()->contains(function (MenuItem $child) { return ($child->hasChilds() && $child->hasActiveStateFromChilds()) || ($child->route && $child->hasActiveStateFromRoute()) || $child->isActive() || $child->hasActiveStateFromUrl(); }) ?? false; }
[ "protected", "function", "hasActiveStateFromChilds", "(", ")", ":", "bool", "{", "return", "$", "this", "->", "getChilds", "(", ")", "->", "contains", "(", "function", "(", "MenuItem", "$", "child", ")", "{", "return", "(", "$", "child", "->", "hasChilds", "(", ")", "&&", "$", "child", "->", "hasActiveStateFromChilds", "(", ")", ")", "||", "(", "$", "child", "->", "route", "&&", "$", "child", "->", "hasActiveStateFromRoute", "(", ")", ")", "||", "$", "child", "->", "isActive", "(", ")", "||", "$", "child", "->", "hasActiveStateFromUrl", "(", ")", ";", "}", ")", "??", "false", ";", "}" ]
Check if the item has active state from childs. @return bool
[ "Check", "if", "the", "item", "has", "active", "state", "from", "childs", "." ]
3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce
https://github.com/rinvex/laravel-menus/blob/3da5d0cd89a3c9f9568aeb2cf278dbd643abd8ce/src/Models/MenuItem.php#L411-L418
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.isClassName
private function isClassName($value, array $options) { if (preg_match('/^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\\\\(?1))*$/', $value) !== 1) { return false; } return array_intersect(iterator_to_array($this->iterateNamespaces($value)), $options['string.classes']) !== []; }
php
private function isClassName($value, array $options) { if (preg_match('/^([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\\\\(?1))*$/', $value) !== 1) { return false; } return array_intersect(iterator_to_array($this->iterateNamespaces($value)), $options['string.classes']) !== []; }
[ "private", "function", "isClassName", "(", "$", "value", ",", "array", "$", "options", ")", "{", "if", "(", "preg_match", "(", "'/^([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)(\\\\\\\\(?1))*$/'", ",", "$", "value", ")", "!==", "1", ")", "{", "return", "false", ";", "}", "return", "array_intersect", "(", "iterator_to_array", "(", "$", "this", "->", "iterateNamespaces", "(", "$", "value", ")", ")", ",", "$", "options", "[", "'string.classes'", "]", ")", "!==", "[", "]", ";", "}" ]
Tests if the given value is a string that could be encoded as a class name constant. @param string $value The string to test @param array $options The string encoding options @return bool True if string can be encoded as class constant, false if not
[ "Tests", "if", "the", "given", "value", "is", "a", "string", "that", "could", "be", "encoded", "as", "a", "class", "name", "constant", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L53-L60
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.getClassName
private function getClassName($value, array $options) { foreach ($this->iterateNamespaces($value) as $partial) { if (isset($options['string.imports'][$partial])) { $trimmed = substr($value, \strlen(rtrim($partial, '\\'))); return ltrim(sprintf('%s%s::class', rtrim($options['string.imports'][$partial], '\\'), $trimmed), '\\'); } } return sprintf('\\%s::class', $value); }
php
private function getClassName($value, array $options) { foreach ($this->iterateNamespaces($value) as $partial) { if (isset($options['string.imports'][$partial])) { $trimmed = substr($value, \strlen(rtrim($partial, '\\'))); return ltrim(sprintf('%s%s::class', rtrim($options['string.imports'][$partial], '\\'), $trimmed), '\\'); } } return sprintf('\\%s::class', $value); }
[ "private", "function", "getClassName", "(", "$", "value", ",", "array", "$", "options", ")", "{", "foreach", "(", "$", "this", "->", "iterateNamespaces", "(", "$", "value", ")", "as", "$", "partial", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'string.imports'", "]", "[", "$", "partial", "]", ")", ")", "{", "$", "trimmed", "=", "substr", "(", "$", "value", ",", "\\", "strlen", "(", "rtrim", "(", "$", "partial", ",", "'\\\\'", ")", ")", ")", ";", "return", "ltrim", "(", "sprintf", "(", "'%s%s::class'", ",", "rtrim", "(", "$", "options", "[", "'string.imports'", "]", "[", "$", "partial", "]", ",", "'\\\\'", ")", ",", "$", "trimmed", ")", ",", "'\\\\'", ")", ";", "}", "}", "return", "sprintf", "(", "'\\\\%s::class'", ",", "$", "value", ")", ";", "}" ]
Encodes the given string as a class name constant based on used imports. @param string $value The string to encode @param array $options The string encoding options @return string The class constant PHP code representation
[ "Encodes", "the", "given", "string", "as", "a", "class", "name", "constant", "based", "on", "used", "imports", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L68-L78
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.iterateNamespaces
private function iterateNamespaces($value) { yield $value; $parts = explode('\\', '\\' . $value); $count = \count($parts); for ($i = 1; $i < $count; $i++) { yield ltrim(implode('\\', \array_slice($parts, 0, -$i)), '\\') . '\\'; } }
php
private function iterateNamespaces($value) { yield $value; $parts = explode('\\', '\\' . $value); $count = \count($parts); for ($i = 1; $i < $count; $i++) { yield ltrim(implode('\\', \array_slice($parts, 0, -$i)), '\\') . '\\'; } }
[ "private", "function", "iterateNamespaces", "(", "$", "value", ")", "{", "yield", "$", "value", ";", "$", "parts", "=", "explode", "(", "'\\\\'", ",", "'\\\\'", ".", "$", "value", ")", ";", "$", "count", "=", "\\", "count", "(", "$", "parts", ")", ";", "for", "(", "$", "i", "=", "1", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "yield", "ltrim", "(", "implode", "(", "'\\\\'", ",", "\\", "array_slice", "(", "$", "parts", ",", "0", ",", "-", "$", "i", ")", ")", ",", "'\\\\'", ")", ".", "'\\\\'", ";", "}", "}" ]
Iterates over the variations of the namespace for the given class name. @param string $value The class name to iterate over @return \Generator|string[] The namespace parts of the string
[ "Iterates", "over", "the", "variations", "of", "the", "namespace", "for", "the", "given", "class", "name", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L85-L95
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.getComplexString
private function getComplexString($value, array $options) { if ($this->isBinaryString($value, $options)) { return $this->encodeBinaryString($value); } if ($options['string.escape']) { return $this->getDoubleQuotedString($value, $options); } return $this->getSingleQuotedString($value); }
php
private function getComplexString($value, array $options) { if ($this->isBinaryString($value, $options)) { return $this->encodeBinaryString($value); } if ($options['string.escape']) { return $this->getDoubleQuotedString($value, $options); } return $this->getSingleQuotedString($value); }
[ "private", "function", "getComplexString", "(", "$", "value", ",", "array", "$", "options", ")", "{", "if", "(", "$", "this", "->", "isBinaryString", "(", "$", "value", ",", "$", "options", ")", ")", "{", "return", "$", "this", "->", "encodeBinaryString", "(", "$", "value", ")", ";", "}", "if", "(", "$", "options", "[", "'string.escape'", "]", ")", "{", "return", "$", "this", "->", "getDoubleQuotedString", "(", "$", "value", ",", "$", "options", ")", ";", "}", "return", "$", "this", "->", "getSingleQuotedString", "(", "$", "value", ")", ";", "}" ]
Returns the PHP code representation for the string that is not just simple ascii characters. @param string $value The string to encode @param array $options The string encoding options @return string The PHP code representation for the complex string
[ "Returns", "the", "PHP", "code", "representation", "for", "the", "string", "that", "is", "not", "just", "simple", "ascii", "characters", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L103-L114
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.getDoubleQuotedString
private function getDoubleQuotedString($string, $options) { $string = strtr($string, [ "\n" => '\n', "\r" => '\r', "\t" => '\t', '$' => '\$', '"' => '\"', '\\' => '\\\\', ]); if ($options['string.utf8']) { $string = $this->encodeUtf8($string, $options); } $hexFormat = function ($matches) use ($options) { return sprintf($options['hex.capitalize'] ? '\x%02X' : '\x%02x', \ord($matches[0])); }; return sprintf('"%s"', preg_replace_callback('/[^\x20-\x7E]/', $hexFormat, $string)); }
php
private function getDoubleQuotedString($string, $options) { $string = strtr($string, [ "\n" => '\n', "\r" => '\r', "\t" => '\t', '$' => '\$', '"' => '\"', '\\' => '\\\\', ]); if ($options['string.utf8']) { $string = $this->encodeUtf8($string, $options); } $hexFormat = function ($matches) use ($options) { return sprintf($options['hex.capitalize'] ? '\x%02X' : '\x%02x', \ord($matches[0])); }; return sprintf('"%s"', preg_replace_callback('/[^\x20-\x7E]/', $hexFormat, $string)); }
[ "private", "function", "getDoubleQuotedString", "(", "$", "string", ",", "$", "options", ")", "{", "$", "string", "=", "strtr", "(", "$", "string", ",", "[", "\"\\n\"", "=>", "'\\n'", ",", "\"\\r\"", "=>", "'\\r'", ",", "\"\\t\"", "=>", "'\\t'", ",", "'$'", "=>", "'\\$'", ",", "'\"'", "=>", "'\\\"'", ",", "'\\\\'", "=>", "'\\\\\\\\'", ",", "]", ")", ";", "if", "(", "$", "options", "[", "'string.utf8'", "]", ")", "{", "$", "string", "=", "$", "this", "->", "encodeUtf8", "(", "$", "string", ",", "$", "options", ")", ";", "}", "$", "hexFormat", "=", "function", "(", "$", "matches", ")", "use", "(", "$", "options", ")", "{", "return", "sprintf", "(", "$", "options", "[", "'hex.capitalize'", "]", "?", "'\\x%02X'", ":", "'\\x%02x'", ",", "\\", "ord", "(", "$", "matches", "[", "0", "]", ")", ")", ";", "}", ";", "return", "sprintf", "(", "'\"%s\"'", ",", "preg_replace_callback", "(", "'/[^\\x20-\\x7E]/'", ",", "$", "hexFormat", ",", "$", "string", ")", ")", ";", "}" ]
Returns the string wrapped in double quotes and all but print characters escaped. @param string $string String to wrap and escape @param array $options The string encoding options @return string The string wrapped in double quotes and escape correctly
[ "Returns", "the", "string", "wrapped", "in", "double", "quotes", "and", "all", "but", "print", "characters", "escaped", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L170-L190
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.encodeUtf8
private function encodeUtf8($string, $options) { $pattern = '/ [\xC2-\xDF][\x80-\xBF] | \xE0[\xA0-\xBF][\x80-\xBF] | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | \xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2}/x'; return preg_replace_callback($pattern, function ($match) use ($options) { return sprintf($options['hex.capitalize'] ? '\u{%X}' : '\u{%x}', $this->getCodePoint($match[0])); }, $string); }
php
private function encodeUtf8($string, $options) { $pattern = '/ [\xC2-\xDF][\x80-\xBF] | \xE0[\xA0-\xBF][\x80-\xBF] | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} | \xED[\x80-\x9F][\x80-\xBF] | \xF0[\x90-\xBF][\x80-\xBF]{2} | [\xF1-\xF3][\x80-\xBF]{3} | \xF4[\x80-\x8F][\x80-\xBF]{2}/x'; return preg_replace_callback($pattern, function ($match) use ($options) { return sprintf($options['hex.capitalize'] ? '\u{%X}' : '\u{%x}', $this->getCodePoint($match[0])); }, $string); }
[ "private", "function", "encodeUtf8", "(", "$", "string", ",", "$", "options", ")", "{", "$", "pattern", "=", "'/ [\\xC2-\\xDF][\\x80-\\xBF]\n | \\xE0[\\xA0-\\xBF][\\x80-\\xBF]\n | [\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2}\n | \\xED[\\x80-\\x9F][\\x80-\\xBF]\n | \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2}\n | [\\xF1-\\xF3][\\x80-\\xBF]{3}\n | \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2}/x'", ";", "return", "preg_replace_callback", "(", "$", "pattern", ",", "function", "(", "$", "match", ")", "use", "(", "$", "options", ")", "{", "return", "sprintf", "(", "$", "options", "[", "'hex.capitalize'", "]", "?", "'\\u{%X}'", ":", "'\\u{%x}'", ",", "$", "this", "->", "getCodePoint", "(", "$", "match", "[", "0", "]", ")", ")", ";", "}", ",", "$", "string", ")", ";", "}" ]
Encodes all multibyte UTF-8 characters into PHP7 string encoding. @param string $string The string to encoder @param array $options The string encoding options @return string The string with all the multibyte characters encoded
[ "Encodes", "all", "multibyte", "UTF", "-", "8", "characters", "into", "PHP7", "string", "encoding", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L198-L212
train
Riimu/Kit-PHPEncoder
src/Encoder/StringEncoder.php
StringEncoder.getCodePoint
private function getCodePoint($bytes) { if (\strlen($bytes) === 2) { return ((\ord($bytes[0]) & 0b11111) << 6) | (\ord($bytes[1]) & 0b111111); } if (\strlen($bytes) === 3) { return ((\ord($bytes[0]) & 0b1111) << 12) | ((\ord($bytes[1]) & 0b111111) << 6) | (\ord($bytes[2]) & 0b111111); } return ((\ord($bytes[0]) & 0b111) << 18) | ((\ord($bytes[1]) & 0b111111) << 12) | ((\ord($bytes[2]) & 0b111111) << 6) | (\ord($bytes[3]) & 0b111111); }
php
private function getCodePoint($bytes) { if (\strlen($bytes) === 2) { return ((\ord($bytes[0]) & 0b11111) << 6) | (\ord($bytes[1]) & 0b111111); } if (\strlen($bytes) === 3) { return ((\ord($bytes[0]) & 0b1111) << 12) | ((\ord($bytes[1]) & 0b111111) << 6) | (\ord($bytes[2]) & 0b111111); } return ((\ord($bytes[0]) & 0b111) << 18) | ((\ord($bytes[1]) & 0b111111) << 12) | ((\ord($bytes[2]) & 0b111111) << 6) | (\ord($bytes[3]) & 0b111111); }
[ "private", "function", "getCodePoint", "(", "$", "bytes", ")", "{", "if", "(", "\\", "strlen", "(", "$", "bytes", ")", "===", "2", ")", "{", "return", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "0", "]", ")", "&", "0b11111", ")", "<<", "6", ")", "|", "(", "\\", "ord", "(", "$", "bytes", "[", "1", "]", ")", "&", "0b111111", ")", ";", "}", "if", "(", "\\", "strlen", "(", "$", "bytes", ")", "===", "3", ")", "{", "return", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "0", "]", ")", "&", "0b1111", ")", "<<", "12", ")", "|", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "1", "]", ")", "&", "0b111111", ")", "<<", "6", ")", "|", "(", "\\", "ord", "(", "$", "bytes", "[", "2", "]", ")", "&", "0b111111", ")", ";", "}", "return", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "0", "]", ")", "&", "0b111", ")", "<<", "18", ")", "|", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "1", "]", ")", "&", "0b111111", ")", "<<", "12", ")", "|", "(", "(", "\\", "ord", "(", "$", "bytes", "[", "2", "]", ")", "&", "0b111111", ")", "<<", "6", ")", "|", "(", "\\", "ord", "(", "$", "bytes", "[", "3", "]", ")", "&", "0b111111", ")", ";", "}" ]
Returns the unicode code point for the given multibyte UTF-8 character. @param string $bytes The multibyte character @return int The code point for the multibyte character
[ "Returns", "the", "unicode", "code", "point", "for", "the", "given", "multibyte", "UTF", "-", "8", "character", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/StringEncoder.php#L219-L236
train
rinvex/cortex-auth
src/Models/Manager.php
Manager.setTenantsAttribute
public function setTenantsAttribute($tenants): void { static::saved(function (self $model) use ($tenants) { $tenants = collect($tenants)->filter(); $model->tenants->pluck('id')->similar($tenants) || activity() ->performedOn($model) ->withProperties(['attributes' => ['tenants' => $tenants], 'old' => ['tenants' => $model->tenants->pluck('id')->toArray()]]) ->log('updated'); $model->syncTenants($tenants); }); }
php
public function setTenantsAttribute($tenants): void { static::saved(function (self $model) use ($tenants) { $tenants = collect($tenants)->filter(); $model->tenants->pluck('id')->similar($tenants) || activity() ->performedOn($model) ->withProperties(['attributes' => ['tenants' => $tenants], 'old' => ['tenants' => $model->tenants->pluck('id')->toArray()]]) ->log('updated'); $model->syncTenants($tenants); }); }
[ "public", "function", "setTenantsAttribute", "(", "$", "tenants", ")", ":", "void", "{", "static", "::", "saved", "(", "function", "(", "self", "$", "model", ")", "use", "(", "$", "tenants", ")", "{", "$", "tenants", "=", "collect", "(", "$", "tenants", ")", "->", "filter", "(", ")", ";", "$", "model", "->", "tenants", "->", "pluck", "(", "'id'", ")", "->", "similar", "(", "$", "tenants", ")", "||", "activity", "(", ")", "->", "performedOn", "(", "$", "model", ")", "->", "withProperties", "(", "[", "'attributes'", "=>", "[", "'tenants'", "=>", "$", "tenants", "]", ",", "'old'", "=>", "[", "'tenants'", "=>", "$", "model", "->", "tenants", "->", "pluck", "(", "'id'", ")", "->", "toArray", "(", ")", "]", "]", ")", "->", "log", "(", "'updated'", ")", ";", "$", "model", "->", "syncTenants", "(", "$", "tenants", ")", ";", "}", ")", ";", "}" ]
Attach the given tenants to the model. @param mixed $tenants @return void
[ "Attach", "the", "given", "tenants", "to", "the", "model", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/Manager.php#L102-L115
train
SimpleBus/RabbitMQBundleBridge
src/EventListener/LogErrorWhenMessageConsumptionFailed.php
LogErrorWhenMessageConsumptionFailed.messageConsumptionFailed
public function messageConsumptionFailed(MessageConsumptionFailed $event) { $this->logger->log( $this->logLevel, $this->logMessage, [ 'exception' => $event->exception(), 'message' => $event->message() ] ); }
php
public function messageConsumptionFailed(MessageConsumptionFailed $event) { $this->logger->log( $this->logLevel, $this->logMessage, [ 'exception' => $event->exception(), 'message' => $event->message() ] ); }
[ "public", "function", "messageConsumptionFailed", "(", "MessageConsumptionFailed", "$", "event", ")", "{", "$", "this", "->", "logger", "->", "log", "(", "$", "this", "->", "logLevel", ",", "$", "this", "->", "logMessage", ",", "[", "'exception'", "=>", "$", "event", "->", "exception", "(", ")", ",", "'message'", "=>", "$", "event", "->", "message", "(", ")", "]", ")", ";", "}" ]
Log the failed message and the related exception
[ "Log", "the", "failed", "message", "and", "the", "related", "exception" ]
89dfcfd355bec78bbae0d558f2796e4b0b79e170
https://github.com/SimpleBus/RabbitMQBundleBridge/blob/89dfcfd355bec78bbae0d558f2796e4b0b79e170/src/EventListener/LogErrorWhenMessageConsumptionFailed.php#L42-L52
train
rinvex/cortex-auth
src/Models/Session.php
Session.scopeGuestsBySeconds
public function scopeGuestsBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->where('last_activity', '>=', time() - $seconds)->whereNull('user_id'); }
php
public function scopeGuestsBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->where('last_activity', '>=', time() - $seconds)->whereNull('user_id'); }
[ "public", "function", "scopeGuestsBySeconds", "(", "Builder", "$", "builder", ",", "$", "seconds", "=", "60", ")", ":", "Builder", "{", "return", "$", "builder", "->", "where", "(", "'last_activity'", ",", "'>='", ",", "time", "(", ")", "-", "$", "seconds", ")", "->", "whereNull", "(", "'user_id'", ")", ";", "}" ]
Constrain the query to retrieve only sessions of guests who have been active within the specified number of seconds. @param \Illuminate\Database\Eloquent\Builder $builder @param int $seconds @return \Illuminate\Database\Eloquent\Builder
[ "Constrain", "the", "query", "to", "retrieve", "only", "sessions", "of", "guests", "who", "have", "been", "active", "within", "the", "specified", "number", "of", "seconds", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/Session.php#L125-L128
train
rinvex/cortex-auth
src/Models/Session.php
Session.scopeUsersBySeconds
public function scopeUsersBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->with(['user'])->where('last_activity', '>=', now()->subSeconds($seconds))->whereNotNull('user_id'); }
php
public function scopeUsersBySeconds(Builder $builder, $seconds = 60): Builder { return $builder->with(['user'])->where('last_activity', '>=', now()->subSeconds($seconds))->whereNotNull('user_id'); }
[ "public", "function", "scopeUsersBySeconds", "(", "Builder", "$", "builder", ",", "$", "seconds", "=", "60", ")", ":", "Builder", "{", "return", "$", "builder", "->", "with", "(", "[", "'user'", "]", ")", "->", "where", "(", "'last_activity'", ",", "'>='", ",", "now", "(", ")", "->", "subSeconds", "(", "$", "seconds", ")", ")", "->", "whereNotNull", "(", "'user_id'", ")", ";", "}" ]
Constrain the query to retrieve only sessions of users who have been active within the specified number of seconds. @param \Illuminate\Database\Eloquent\Builder $builder @param int $seconds @return \Illuminate\Database\Eloquent\Builder
[ "Constrain", "the", "query", "to", "retrieve", "only", "sessions", "of", "users", "who", "have", "been", "active", "within", "the", "specified", "number", "of", "seconds", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/Session.php#L180-L183
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AdminsMediaController.php
AdminsMediaController.destroy
public function destroy(Admin $admin, Media $media) { $admin->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.admins.edit', ['admin' => $admin]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
php
public function destroy(Admin $admin, Media $media) { $admin->media()->where($media->getKeyName(), $media->getKey())->first()->delete(); return intend([ 'url' => route('adminarea.admins.edit', ['admin' => $admin]), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/foundation::common.media'), 'identifier' => $media->getRouteKey()])], ]); }
[ "public", "function", "destroy", "(", "Admin", "$", "admin", ",", "Media", "$", "media", ")", "{", "$", "admin", "->", "media", "(", ")", "->", "where", "(", "$", "media", "->", "getKeyName", "(", ")", ",", "$", "media", "->", "getKey", "(", ")", ")", "->", "first", "(", ")", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'adminarea.admins.edit'", ",", "[", "'admin'", "=>", "$", "admin", "]", ")", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/foundation::common.media'", ")", ",", "'identifier'", "=>", "$", "media", "->", "getRouteKey", "(", ")", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given admin media. @param \Cortex\Auth\Models\Admin $admin @param \Spatie\MediaLibrary\Models\Media $media @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "admin", "media", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AdminsMediaController.php#L46-L54
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/GuardiansController.php
GuardiansController.import
public function import(Guardian $guardian, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $guardian, 'tabs' => 'adminarea.guardians.tabs', 'url' => route('adminarea.guardians.stash'), 'id' => "adminarea-attributes-{$guardian->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
php
public function import(Guardian $guardian, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $guardian, 'tabs' => 'adminarea.guardians.tabs', 'url' => route('adminarea.guardians.stash'), 'id' => "adminarea-attributes-{$guardian->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
[ "public", "function", "import", "(", "Guardian", "$", "guardian", ",", "ImportRecordsDataTable", "$", "importRecordsDataTable", ")", "{", "return", "$", "importRecordsDataTable", "->", "with", "(", "[", "'resource'", "=>", "$", "guardian", ",", "'tabs'", "=>", "'adminarea.guardians.tabs'", ",", "'url'", "=>", "route", "(", "'adminarea.guardians.stash'", ")", ",", "'id'", "=>", "\"adminarea-attributes-{$guardian->getRouteKey()}-import-table\"", ",", "]", ")", "->", "render", "(", "'cortex/foundation::adminarea.pages.datatable-dropzone'", ")", ";", "}" ]
Import guardians. @param \Cortex\Auth\Models\Guardian $guardian @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
[ "Import", "guardians", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/GuardiansController.php#L66-L74
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/GuardiansController.php
GuardiansController.destroy
public function destroy(Guardian $guardian) { $guardian->delete(); return intend([ 'url' => route('adminarea.guardians.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.guardian'), 'identifier' => $guardian->username])], ]); }
php
public function destroy(Guardian $guardian) { $guardian->delete(); return intend([ 'url' => route('adminarea.guardians.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.guardian'), 'identifier' => $guardian->username])], ]); }
[ "public", "function", "destroy", "(", "Guardian", "$", "guardian", ")", "{", "$", "guardian", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'adminarea.guardians.index'", ")", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/auth::common.guardian'", ")", ",", "'identifier'", "=>", "$", "guardian", "->", "username", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given guardian. @param \Cortex\Auth\Models\Guardian $guardian @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "guardian", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/GuardiansController.php#L211-L219
train
rinvex/cortex-auth
src/Traits/TwoFactorAuthenticatesUsers.php
TwoFactorAuthenticatesUsers.attemptTwoFactor
protected function attemptTwoFactor(AuthenticatableTwoFactorContract $user, int $token): bool { return $this->isValidTwoFactorTotp($user, $token) || $this->isValidTwoFactorBackup($user, $token) || $this->isValidTwoFactorPhone($user, $token); }
php
protected function attemptTwoFactor(AuthenticatableTwoFactorContract $user, int $token): bool { return $this->isValidTwoFactorTotp($user, $token) || $this->isValidTwoFactorBackup($user, $token) || $this->isValidTwoFactorPhone($user, $token); }
[ "protected", "function", "attemptTwoFactor", "(", "AuthenticatableTwoFactorContract", "$", "user", ",", "int", "$", "token", ")", ":", "bool", "{", "return", "$", "this", "->", "isValidTwoFactorTotp", "(", "$", "user", ",", "$", "token", ")", "||", "$", "this", "->", "isValidTwoFactorBackup", "(", "$", "user", ",", "$", "token", ")", "||", "$", "this", "->", "isValidTwoFactorPhone", "(", "$", "user", ",", "$", "token", ")", ";", "}" ]
Verify TwoFactor authentication. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
[ "Verify", "TwoFactor", "authentication", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Traits/TwoFactorAuthenticatesUsers.php#L20-L23
train
rinvex/cortex-auth
src/Traits/TwoFactorAuthenticatesUsers.php
TwoFactorAuthenticatesUsers.invalidateTwoFactorBackup
protected function invalidateTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): void { $settings = $user->getTwoFactor(); $backup = array_get($settings, 'totp.backup'); unset($backup[array_search($token, $backup)]); array_set($settings, 'totp.backup', $backup); // Update TwoFactor OTP backup codes $user->fill(['two_factor' => $settings])->forceSave(); }
php
protected function invalidateTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): void { $settings = $user->getTwoFactor(); $backup = array_get($settings, 'totp.backup'); unset($backup[array_search($token, $backup)]); array_set($settings, 'totp.backup', $backup); // Update TwoFactor OTP backup codes $user->fill(['two_factor' => $settings])->forceSave(); }
[ "protected", "function", "invalidateTwoFactorBackup", "(", "AuthenticatableTwoFactorContract", "$", "user", ",", "int", "$", "token", ")", ":", "void", "{", "$", "settings", "=", "$", "user", "->", "getTwoFactor", "(", ")", ";", "$", "backup", "=", "array_get", "(", "$", "settings", ",", "'totp.backup'", ")", ";", "unset", "(", "$", "backup", "[", "array_search", "(", "$", "token", ",", "$", "backup", ")", "]", ")", ";", "array_set", "(", "$", "settings", ",", "'totp.backup'", ",", "$", "backup", ")", ";", "// Update TwoFactor OTP backup codes", "$", "user", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "settings", "]", ")", "->", "forceSave", "(", ")", ";", "}" ]
Invalidate given backup code for the given user. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return void
[ "Invalidate", "given", "backup", "code", "for", "the", "given", "user", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Traits/TwoFactorAuthenticatesUsers.php#L33-L44
train
rinvex/cortex-auth
src/Traits/TwoFactorAuthenticatesUsers.php
TwoFactorAuthenticatesUsers.isValidTwoFactorPhone
protected function isValidTwoFactorPhone(AuthenticatableTwoFactorContract $user, int $token): bool { $settings = $user->getTwoFactor(); $authyId = array_get($settings, 'phone.authy_id'); return in_array(mb_strlen($token), [6, 7, 8]) && app('rinvex.authy.token')->verify($token, $authyId)->succeed(); }
php
protected function isValidTwoFactorPhone(AuthenticatableTwoFactorContract $user, int $token): bool { $settings = $user->getTwoFactor(); $authyId = array_get($settings, 'phone.authy_id'); return in_array(mb_strlen($token), [6, 7, 8]) && app('rinvex.authy.token')->verify($token, $authyId)->succeed(); }
[ "protected", "function", "isValidTwoFactorPhone", "(", "AuthenticatableTwoFactorContract", "$", "user", ",", "int", "$", "token", ")", ":", "bool", "{", "$", "settings", "=", "$", "user", "->", "getTwoFactor", "(", ")", ";", "$", "authyId", "=", "array_get", "(", "$", "settings", ",", "'phone.authy_id'", ")", ";", "return", "in_array", "(", "mb_strlen", "(", "$", "token", ")", ",", "[", "6", ",", "7", ",", "8", "]", ")", "&&", "app", "(", "'rinvex.authy.token'", ")", "->", "verify", "(", "$", "token", ",", "$", "authyId", ")", "->", "succeed", "(", ")", ";", "}" ]
Determine if the given token is a valid TwoFactor Phone token. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
[ "Determine", "if", "the", "given", "token", "is", "a", "valid", "TwoFactor", "Phone", "token", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Traits/TwoFactorAuthenticatesUsers.php#L54-L60
train
rinvex/cortex-auth
src/Traits/TwoFactorAuthenticatesUsers.php
TwoFactorAuthenticatesUsers.isValidTwoFactorBackup
protected function isValidTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): bool { $backup = array_get($user->getTwoFactor(), 'totp.backup', []); $result = mb_strlen($token) === 10 && in_array($token, $backup); ! $result || $this->invalidateTwoFactorBackup($user, $token); return $result; }
php
protected function isValidTwoFactorBackup(AuthenticatableTwoFactorContract $user, int $token): bool { $backup = array_get($user->getTwoFactor(), 'totp.backup', []); $result = mb_strlen($token) === 10 && in_array($token, $backup); ! $result || $this->invalidateTwoFactorBackup($user, $token); return $result; }
[ "protected", "function", "isValidTwoFactorBackup", "(", "AuthenticatableTwoFactorContract", "$", "user", ",", "int", "$", "token", ")", ":", "bool", "{", "$", "backup", "=", "array_get", "(", "$", "user", "->", "getTwoFactor", "(", ")", ",", "'totp.backup'", ",", "[", "]", ")", ";", "$", "result", "=", "mb_strlen", "(", "$", "token", ")", "===", "10", "&&", "in_array", "(", "$", "token", ",", "$", "backup", ")", ";", "!", "$", "result", "||", "$", "this", "->", "invalidateTwoFactorBackup", "(", "$", "user", ",", "$", "token", ")", ";", "return", "$", "result", ";", "}" ]
Determine if the given token is a valid TwoFactor Backup code. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
[ "Determine", "if", "the", "given", "token", "is", "a", "valid", "TwoFactor", "Backup", "code", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Traits/TwoFactorAuthenticatesUsers.php#L70-L77
train
rinvex/cortex-auth
src/Traits/TwoFactorAuthenticatesUsers.php
TwoFactorAuthenticatesUsers.isValidTwoFactorTotp
protected function isValidTwoFactorTotp(AuthenticatableTwoFactorContract $user, int $token): bool { $totpProvider = app(Google2FA::class); $secret = array_get($user->getTwoFactor(), 'totp.secret'); return mb_strlen($token) === 6 && $totpProvider->verifyKey($secret, $token); }
php
protected function isValidTwoFactorTotp(AuthenticatableTwoFactorContract $user, int $token): bool { $totpProvider = app(Google2FA::class); $secret = array_get($user->getTwoFactor(), 'totp.secret'); return mb_strlen($token) === 6 && $totpProvider->verifyKey($secret, $token); }
[ "protected", "function", "isValidTwoFactorTotp", "(", "AuthenticatableTwoFactorContract", "$", "user", ",", "int", "$", "token", ")", ":", "bool", "{", "$", "totpProvider", "=", "app", "(", "Google2FA", "::", "class", ")", ";", "$", "secret", "=", "array_get", "(", "$", "user", "->", "getTwoFactor", "(", ")", ",", "'totp.secret'", ")", ";", "return", "mb_strlen", "(", "$", "token", ")", "===", "6", "&&", "$", "totpProvider", "->", "verifyKey", "(", "$", "secret", ",", "$", "token", ")", ";", "}" ]
Determine if the given token is a valid TwoFactor TOTP token. @param \Rinvex\Auth\Contracts\AuthenticatableTwoFactorContract $user @param int $token @return bool
[ "Determine", "if", "the", "given", "token", "is", "a", "valid", "TwoFactor", "TOTP", "token", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Traits/TwoFactorAuthenticatesUsers.php#L87-L93
train
rinvex/cortex-auth
src/Console/Commands/SeedCommand.php
SeedCommand.createAdmin
protected function createAdmin(string $password): Admin { $admin = [ 'is_active' => true, 'username' => 'Admin', 'given_name' => 'Admin', 'family_name' => 'User', 'email' => '[email protected]', ]; return tap(app('cortex.auth.admin')->firstOrNew($admin)->fill([ 'remember_token' => str_random(10), 'email_verified_at' => now(), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
php
protected function createAdmin(string $password): Admin { $admin = [ 'is_active' => true, 'username' => 'Admin', 'given_name' => 'Admin', 'family_name' => 'User', 'email' => '[email protected]', ]; return tap(app('cortex.auth.admin')->firstOrNew($admin)->fill([ 'remember_token' => str_random(10), 'email_verified_at' => now(), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
[ "protected", "function", "createAdmin", "(", "string", "$", "password", ")", ":", "Admin", "{", "$", "admin", "=", "[", "'is_active'", "=>", "true", ",", "'username'", "=>", "'Admin'", ",", "'given_name'", "=>", "'Admin'", ",", "'family_name'", "=>", "'User'", ",", "'email'", "=>", "'[email protected]'", ",", "]", ";", "return", "tap", "(", "app", "(", "'cortex.auth.admin'", ")", "->", "firstOrNew", "(", "$", "admin", ")", "->", "fill", "(", "[", "'remember_token'", "=>", "str_random", "(", "10", ")", ",", "'email_verified_at'", "=>", "now", "(", ")", ",", "'password'", "=>", "$", "password", ",", "]", ")", ",", "function", "(", "$", "instance", ")", "{", "$", "instance", "->", "save", "(", ")", ";", "}", ")", ";", "}" ]
Create admin model. @param string $password @return \Cortex\Auth\Models\Admin
[ "Create", "admin", "model", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Console/Commands/SeedCommand.php#L58-L75
train
rinvex/cortex-auth
src/Console/Commands/SeedCommand.php
SeedCommand.createGuardian
protected function createGuardian(string $password): Guardian { $guardian = [ 'is_active' => true, 'username' => 'Guardian', 'email' => '[email protected]', ]; return tap(app('cortex.auth.guardian')->firstOrNew($guardian)->fill([ 'remember_token' => str_random(10), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
php
protected function createGuardian(string $password): Guardian { $guardian = [ 'is_active' => true, 'username' => 'Guardian', 'email' => '[email protected]', ]; return tap(app('cortex.auth.guardian')->firstOrNew($guardian)->fill([ 'remember_token' => str_random(10), 'password' => $password, ]), function ($instance) { $instance->save(); }); }
[ "protected", "function", "createGuardian", "(", "string", "$", "password", ")", ":", "Guardian", "{", "$", "guardian", "=", "[", "'is_active'", "=>", "true", ",", "'username'", "=>", "'Guardian'", ",", "'email'", "=>", "'[email protected]'", ",", "]", ";", "return", "tap", "(", "app", "(", "'cortex.auth.guardian'", ")", "->", "firstOrNew", "(", "$", "guardian", ")", "->", "fill", "(", "[", "'remember_token'", "=>", "str_random", "(", "10", ")", ",", "'password'", "=>", "$", "password", ",", "]", ")", ",", "function", "(", "$", "instance", ")", "{", "$", "instance", "->", "save", "(", ")", ";", "}", ")", ";", "}" ]
Create guardian model. @param string $password @return \Cortex\Auth\Models\Guardian
[ "Create", "guardian", "model", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Console/Commands/SeedCommand.php#L84-L98
train
rinvex/cortex-auth
src/Models/User.php
User.setAbilitiesAttribute
public function setAbilitiesAttribute($abilities): void { static::saved(function (self $model) use ($abilities) { $abilities = collect($abilities)->filter(); $model->abilities->pluck('id')->similar($abilities) || activity() ->performedOn($model) ->withProperties(['attributes' => ['abilities' => $abilities], 'old' => ['abilities' => $model->abilities->pluck('id')->toArray()]]) ->log('updated'); $model->abilities()->sync($abilities, true); }); }
php
public function setAbilitiesAttribute($abilities): void { static::saved(function (self $model) use ($abilities) { $abilities = collect($abilities)->filter(); $model->abilities->pluck('id')->similar($abilities) || activity() ->performedOn($model) ->withProperties(['attributes' => ['abilities' => $abilities], 'old' => ['abilities' => $model->abilities->pluck('id')->toArray()]]) ->log('updated'); $model->abilities()->sync($abilities, true); }); }
[ "public", "function", "setAbilitiesAttribute", "(", "$", "abilities", ")", ":", "void", "{", "static", "::", "saved", "(", "function", "(", "self", "$", "model", ")", "use", "(", "$", "abilities", ")", "{", "$", "abilities", "=", "collect", "(", "$", "abilities", ")", "->", "filter", "(", ")", ";", "$", "model", "->", "abilities", "->", "pluck", "(", "'id'", ")", "->", "similar", "(", "$", "abilities", ")", "||", "activity", "(", ")", "->", "performedOn", "(", "$", "model", ")", "->", "withProperties", "(", "[", "'attributes'", "=>", "[", "'abilities'", "=>", "$", "abilities", "]", ",", "'old'", "=>", "[", "'abilities'", "=>", "$", "model", "->", "abilities", "->", "pluck", "(", "'id'", ")", "->", "toArray", "(", ")", "]", "]", ")", "->", "log", "(", "'updated'", ")", ";", "$", "model", "->", "abilities", "(", ")", "->", "sync", "(", "$", "abilities", ",", "true", ")", ";", "}", ")", ";", "}" ]
Attach the given abilities to the model. @param mixed $abilities @return void
[ "Attach", "the", "given", "abilities", "to", "the", "model", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/User.php#L213-L226
train
rinvex/cortex-auth
src/Models/User.php
User.setRolesAttribute
public function setRolesAttribute($roles): void { static::saved(function (self $model) use ($roles) { $roles = collect($roles)->filter(); $model->roles->pluck('id')->similar($roles) || activity() ->performedOn($model) ->withProperties(['attributes' => ['roles' => $roles], 'old' => ['roles' => $model->roles->pluck('id')->toArray()]]) ->log('updated'); $model->roles()->sync($roles, true); }); }
php
public function setRolesAttribute($roles): void { static::saved(function (self $model) use ($roles) { $roles = collect($roles)->filter(); $model->roles->pluck('id')->similar($roles) || activity() ->performedOn($model) ->withProperties(['attributes' => ['roles' => $roles], 'old' => ['roles' => $model->roles->pluck('id')->toArray()]]) ->log('updated'); $model->roles()->sync($roles, true); }); }
[ "public", "function", "setRolesAttribute", "(", "$", "roles", ")", ":", "void", "{", "static", "::", "saved", "(", "function", "(", "self", "$", "model", ")", "use", "(", "$", "roles", ")", "{", "$", "roles", "=", "collect", "(", "$", "roles", ")", "->", "filter", "(", ")", ";", "$", "model", "->", "roles", "->", "pluck", "(", "'id'", ")", "->", "similar", "(", "$", "roles", ")", "||", "activity", "(", ")", "->", "performedOn", "(", "$", "model", ")", "->", "withProperties", "(", "[", "'attributes'", "=>", "[", "'roles'", "=>", "$", "roles", "]", ",", "'old'", "=>", "[", "'roles'", "=>", "$", "model", "->", "roles", "->", "pluck", "(", "'id'", ")", "->", "toArray", "(", ")", "]", "]", ")", "->", "log", "(", "'updated'", ")", ";", "$", "model", "->", "roles", "(", ")", "->", "sync", "(", "$", "roles", ",", "true", ")", ";", "}", ")", ";", "}" ]
Attach the given roles to the model. @param mixed $roles @return void
[ "Attach", "the", "given", "roles", "to", "the", "model", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/User.php#L235-L248
train
rinvex/cortex-auth
src/Models/User.php
User.routeNotificationForAuthy
public function routeNotificationForAuthy(): ?int { if (! ($authyId = array_get($this->getTwoFactor(), 'phone.authy_id')) && $this->getEmailForVerification() && $this->getPhoneForVerification() && $this->getCountryForVerification()) { $result = app('rinvex.authy.user')->register($this->getEmailForVerification(), preg_replace('/[^0-9]/', '', $this->getPhoneForVerification()), $this->getCountryForVerification()); $authyId = $result->get('user')['id']; // Prepare required variables $twoFactor = $this->getTwoFactor(); // Update user account array_set($twoFactor, 'phone.authy_id', $authyId); $this->fill(['two_factor' => $twoFactor])->forceSave(); } return $authyId; }
php
public function routeNotificationForAuthy(): ?int { if (! ($authyId = array_get($this->getTwoFactor(), 'phone.authy_id')) && $this->getEmailForVerification() && $this->getPhoneForVerification() && $this->getCountryForVerification()) { $result = app('rinvex.authy.user')->register($this->getEmailForVerification(), preg_replace('/[^0-9]/', '', $this->getPhoneForVerification()), $this->getCountryForVerification()); $authyId = $result->get('user')['id']; // Prepare required variables $twoFactor = $this->getTwoFactor(); // Update user account array_set($twoFactor, 'phone.authy_id', $authyId); $this->fill(['two_factor' => $twoFactor])->forceSave(); } return $authyId; }
[ "public", "function", "routeNotificationForAuthy", "(", ")", ":", "?", "int", "{", "if", "(", "!", "(", "$", "authyId", "=", "array_get", "(", "$", "this", "->", "getTwoFactor", "(", ")", ",", "'phone.authy_id'", ")", ")", "&&", "$", "this", "->", "getEmailForVerification", "(", ")", "&&", "$", "this", "->", "getPhoneForVerification", "(", ")", "&&", "$", "this", "->", "getCountryForVerification", "(", ")", ")", "{", "$", "result", "=", "app", "(", "'rinvex.authy.user'", ")", "->", "register", "(", "$", "this", "->", "getEmailForVerification", "(", ")", ",", "preg_replace", "(", "'/[^0-9]/'", ",", "''", ",", "$", "this", "->", "getPhoneForVerification", "(", ")", ")", ",", "$", "this", "->", "getCountryForVerification", "(", ")", ")", ";", "$", "authyId", "=", "$", "result", "->", "get", "(", "'user'", ")", "[", "'id'", "]", ";", "// Prepare required variables", "$", "twoFactor", "=", "$", "this", "->", "getTwoFactor", "(", ")", ";", "// Update user account", "array_set", "(", "$", "twoFactor", ",", "'phone.authy_id'", ",", "$", "authyId", ")", ";", "$", "this", "->", "fill", "(", "[", "'two_factor'", "=>", "$", "twoFactor", "]", ")", "->", "forceSave", "(", ")", ";", "}", "return", "$", "authyId", ";", "}" ]
Route notifications for the authy channel. @return int|null
[ "Route", "notifications", "for", "the", "authy", "channel", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/User.php#L291-L307
train
rinvex/cortex-auth
src/Models/User.php
User.getManagedRoles
public function getManagedRoles(): Collection { if ($this->isA('superadmin')) { $roles = app('cortex.auth.role')->all(); } elseif ($this->isA('supermanager')) { $roles = $this->roles->merge(config('rinvex.tenants.active') ? app('cortex.auth.role')->where('scope', config('rinvex.tenants.active')->getKey())->get() : collect()); } else { $roles = $this->roles; } return $roles->pluck('title', 'id')->sort(); }
php
public function getManagedRoles(): Collection { if ($this->isA('superadmin')) { $roles = app('cortex.auth.role')->all(); } elseif ($this->isA('supermanager')) { $roles = $this->roles->merge(config('rinvex.tenants.active') ? app('cortex.auth.role')->where('scope', config('rinvex.tenants.active')->getKey())->get() : collect()); } else { $roles = $this->roles; } return $roles->pluck('title', 'id')->sort(); }
[ "public", "function", "getManagedRoles", "(", ")", ":", "Collection", "{", "if", "(", "$", "this", "->", "isA", "(", "'superadmin'", ")", ")", "{", "$", "roles", "=", "app", "(", "'cortex.auth.role'", ")", "->", "all", "(", ")", ";", "}", "elseif", "(", "$", "this", "->", "isA", "(", "'supermanager'", ")", ")", "{", "$", "roles", "=", "$", "this", "->", "roles", "->", "merge", "(", "config", "(", "'rinvex.tenants.active'", ")", "?", "app", "(", "'cortex.auth.role'", ")", "->", "where", "(", "'scope'", ",", "config", "(", "'rinvex.tenants.active'", ")", "->", "getKey", "(", ")", ")", "->", "get", "(", ")", ":", "collect", "(", ")", ")", ";", "}", "else", "{", "$", "roles", "=", "$", "this", "->", "roles", ";", "}", "return", "$", "roles", "->", "pluck", "(", "'title'", ",", "'id'", ")", "->", "sort", "(", ")", ";", "}" ]
Get managed roles. @return \Illuminate\Support\Collection
[ "Get", "managed", "roles", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/User.php#L368-L379
train
rinvex/cortex-auth
src/Models/User.php
User.getManagedAbilities
public function getManagedAbilities(): Collection { $abilities = $this->isA('superadmin') ? app('cortex.auth.ability')->all() : $this->getAbilities(); return $abilities->groupBy('entity_type')->map->pluck('title', 'id')->sortKeys(); }
php
public function getManagedAbilities(): Collection { $abilities = $this->isA('superadmin') ? app('cortex.auth.ability')->all() : $this->getAbilities(); return $abilities->groupBy('entity_type')->map->pluck('title', 'id')->sortKeys(); }
[ "public", "function", "getManagedAbilities", "(", ")", ":", "Collection", "{", "$", "abilities", "=", "$", "this", "->", "isA", "(", "'superadmin'", ")", "?", "app", "(", "'cortex.auth.ability'", ")", "->", "all", "(", ")", ":", "$", "this", "->", "getAbilities", "(", ")", ";", "return", "$", "abilities", "->", "groupBy", "(", "'entity_type'", ")", "->", "map", "->", "pluck", "(", "'title'", ",", "'id'", ")", "->", "sortKeys", "(", ")", ";", "}" ]
Get managed abilites. @return \Illuminate\Support\Collection
[ "Get", "managed", "abilites", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Models/User.php#L386-L391
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AdminsController.php
AdminsController.import
public function import(Admin $admin, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $admin, 'tabs' => 'adminarea.admins.tabs', 'url' => route('adminarea.admins.stash'), 'id' => "adminarea-attributes-{$admin->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
php
public function import(Admin $admin, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $admin, 'tabs' => 'adminarea.admins.tabs', 'url' => route('adminarea.admins.stash'), 'id' => "adminarea-attributes-{$admin->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
[ "public", "function", "import", "(", "Admin", "$", "admin", ",", "ImportRecordsDataTable", "$", "importRecordsDataTable", ")", "{", "return", "$", "importRecordsDataTable", "->", "with", "(", "[", "'resource'", "=>", "$", "admin", ",", "'tabs'", "=>", "'adminarea.admins.tabs'", ",", "'url'", "=>", "route", "(", "'adminarea.admins.stash'", ")", ",", "'id'", "=>", "\"adminarea-attributes-{$admin->getRouteKey()}-import-table\"", ",", "]", ")", "->", "render", "(", "'cortex/foundation::adminarea.pages.datatable-dropzone'", ")", ";", "}" ]
Import admins. @param \Cortex\Auth\Models\Admin $admin @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
[ "Import", "admins", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AdminsController.php#L119-L127
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AdminsController.php
AdminsController.destroy
public function destroy(Admin $admin) { $admin->delete(); return intend([ 'url' => route('adminarea.admins.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.admin'), 'identifier' => $admin->username])], ]); }
php
public function destroy(Admin $admin) { $admin->delete(); return intend([ 'url' => route('adminarea.admins.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.admin'), 'identifier' => $admin->username])], ]); }
[ "public", "function", "destroy", "(", "Admin", "$", "admin", ")", "{", "$", "admin", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'adminarea.admins.index'", ")", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/auth::common.admin'", ")", ",", "'identifier'", "=>", "$", "admin", "->", "username", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given admin. @param \Cortex\Auth\Models\Admin $admin @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "admin", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AdminsController.php#L316-L324
train
rinvex/languages
src/LanguageLoader.php
LanguageLoader.language
public static function language($code, $hydrate = true) { $code = mb_strtolower($code); if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } if (! isset(static::$languages[$code])) { throw LanguageLoaderException::invalidLanguage(); } return $hydrate ? new Language(static::$languages[$code]) : static::$languages[$code]; }
php
public static function language($code, $hydrate = true) { $code = mb_strtolower($code); if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } if (! isset(static::$languages[$code])) { throw LanguageLoaderException::invalidLanguage(); } return $hydrate ? new Language(static::$languages[$code]) : static::$languages[$code]; }
[ "public", "static", "function", "language", "(", "$", "code", ",", "$", "hydrate", "=", "true", ")", "{", "$", "code", "=", "mb_strtolower", "(", "$", "code", ")", ";", "if", "(", "!", "isset", "(", "static", "::", "$", "languages", ")", ")", "{", "static", "::", "$", "languages", "=", "json_decode", "(", "static", "::", "getFile", "(", "__DIR__", ".", "'/../resources/languages.json'", ")", ",", "true", ")", ";", "}", "if", "(", "!", "isset", "(", "static", "::", "$", "languages", "[", "$", "code", "]", ")", ")", "{", "throw", "LanguageLoaderException", "::", "invalidLanguage", "(", ")", ";", "}", "return", "$", "hydrate", "?", "new", "Language", "(", "static", "::", "$", "languages", "[", "$", "code", "]", ")", ":", "static", "::", "$", "languages", "[", "$", "code", "]", ";", "}" ]
Get the language by it's ISO ISO 639-1 code. @param string $code @param bool $hydrate @throws \Rinvex\Language\LanguageLoaderException @return \Rinvex\Language\Language|array
[ "Get", "the", "language", "by", "it", "s", "ISO", "ISO", "639", "-", "1", "code", "." ]
b4026ed41cb1950132c8061e80e549c2d3aa763f
https://github.com/rinvex/languages/blob/b4026ed41cb1950132c8061e80e549c2d3aa763f/src/LanguageLoader.php#L28-L41
train
rinvex/languages
src/LanguageLoader.php
LanguageLoader.scripts
public static function scripts() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'script.name', 'script.iso_15924'); }
php
public static function scripts() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'script.name', 'script.iso_15924'); }
[ "public", "static", "function", "scripts", "(", ")", "{", "if", "(", "!", "isset", "(", "static", "::", "$", "languages", ")", ")", "{", "static", "::", "$", "languages", "=", "json_decode", "(", "static", "::", "getFile", "(", "__DIR__", ".", "'/../resources/languages.json'", ")", ",", "true", ")", ";", "}", "return", "static", "::", "pluck", "(", "static", "::", "$", "languages", ",", "'script.name'", ",", "'script.iso_15924'", ")", ";", "}" ]
Get all language scripts. @return array
[ "Get", "all", "language", "scripts", "." ]
b4026ed41cb1950132c8061e80e549c2d3aa763f
https://github.com/rinvex/languages/blob/b4026ed41cb1950132c8061e80e549c2d3aa763f/src/LanguageLoader.php#L66-L73
train
rinvex/languages
src/LanguageLoader.php
LanguageLoader.families
public static function families() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'family.name', 'family.iso_639_5'); }
php
public static function families() { if (! isset(static::$languages)) { static::$languages = json_decode(static::getFile(__DIR__.'/../resources/languages.json'), true); } return static::pluck(static::$languages, 'family.name', 'family.iso_639_5'); }
[ "public", "static", "function", "families", "(", ")", "{", "if", "(", "!", "isset", "(", "static", "::", "$", "languages", ")", ")", "{", "static", "::", "$", "languages", "=", "json_decode", "(", "static", "::", "getFile", "(", "__DIR__", ".", "'/../resources/languages.json'", ")", ",", "true", ")", ";", "}", "return", "static", "::", "pluck", "(", "static", "::", "$", "languages", ",", "'family.name'", ",", "'family.iso_639_5'", ")", ";", "}" ]
Get all language families. @return array
[ "Get", "all", "language", "families", "." ]
b4026ed41cb1950132c8061e80e549c2d3aa763f
https://github.com/rinvex/languages/blob/b4026ed41cb1950132c8061e80e549c2d3aa763f/src/LanguageLoader.php#L80-L87
train
rinvex/cortex-auth
src/Handlers/GenericHandler.php
GenericHandler.lockout
public function lockout(Lockout $event): void { if (config('cortex.auth.emails.throttle_lockout')) { switch ($event->request->route('accessarea')) { case 'managerarea': $model = app('cortex.auth.manager'); break; case 'adminarea': $model = app('cortex.auth.admin'); break; case 'frontarea': case 'tenantarea': default: $model = app('cortex.auth.member'); break; } $user = get_login_field($loginfield = $event->request->get('loginfield')) === 'email' ? $model::where('email', $loginfield)->first() : $model::where('username', $loginfield)->first(); ! $user || $user->notify(new AuthenticationLockoutNotification($event->request->ip(), $event->request->server('HTTP_USER_AGENT'))); } }
php
public function lockout(Lockout $event): void { if (config('cortex.auth.emails.throttle_lockout')) { switch ($event->request->route('accessarea')) { case 'managerarea': $model = app('cortex.auth.manager'); break; case 'adminarea': $model = app('cortex.auth.admin'); break; case 'frontarea': case 'tenantarea': default: $model = app('cortex.auth.member'); break; } $user = get_login_field($loginfield = $event->request->get('loginfield')) === 'email' ? $model::where('email', $loginfield)->first() : $model::where('username', $loginfield)->first(); ! $user || $user->notify(new AuthenticationLockoutNotification($event->request->ip(), $event->request->server('HTTP_USER_AGENT'))); } }
[ "public", "function", "lockout", "(", "Lockout", "$", "event", ")", ":", "void", "{", "if", "(", "config", "(", "'cortex.auth.emails.throttle_lockout'", ")", ")", "{", "switch", "(", "$", "event", "->", "request", "->", "route", "(", "'accessarea'", ")", ")", "{", "case", "'managerarea'", ":", "$", "model", "=", "app", "(", "'cortex.auth.manager'", ")", ";", "break", ";", "case", "'adminarea'", ":", "$", "model", "=", "app", "(", "'cortex.auth.admin'", ")", ";", "break", ";", "case", "'frontarea'", ":", "case", "'tenantarea'", ":", "default", ":", "$", "model", "=", "app", "(", "'cortex.auth.member'", ")", ";", "break", ";", "}", "$", "user", "=", "get_login_field", "(", "$", "loginfield", "=", "$", "event", "->", "request", "->", "get", "(", "'loginfield'", ")", ")", "===", "'email'", "?", "$", "model", "::", "where", "(", "'email'", ",", "$", "loginfield", ")", "->", "first", "(", ")", ":", "$", "model", "::", "where", "(", "'username'", ",", "$", "loginfield", ")", "->", "first", "(", ")", ";", "!", "$", "user", "||", "$", "user", "->", "notify", "(", "new", "AuthenticationLockoutNotification", "(", "$", "event", "->", "request", "->", "ip", "(", ")", ",", "$", "event", "->", "request", "->", "server", "(", "'HTTP_USER_AGENT'", ")", ")", ")", ";", "}", "}" ]
Listen to the authentication lockout event. @param \Illuminate\Auth\Events\Lockout $event @return void
[ "Listen", "to", "the", "authentication", "lockout", "event", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Handlers/GenericHandler.php#L53-L76
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountSessionsController.php
AccountSessionsController.destroy
public function destroy(Session $session) { $session->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.session'), 'identifier' => $session->getKey()])], ]); }
php
public function destroy(Session $session) { $session->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.session'), 'identifier' => $session->getKey()])], ]); }
[ "public", "function", "destroy", "(", "Session", "$", "session", ")", "{", "$", "session", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/auth::common.session'", ")", ",", "'identifier'", "=>", "$", "session", "->", "getKey", "(", ")", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given session. @param \Cortex\Auth\Models\Session $session @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "session", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountSessionsController.php#L32-L40
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountSessionsController.php
AccountSessionsController.flush
public function flush(Request $request) { $request->user($this->getGuard())->sessions()->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/auth::messages.auth.session.flushed')], ]); }
php
public function flush(Request $request) { $request->user($this->getGuard())->sessions()->delete(); return intend([ 'back' => true, 'with' => ['warning' => trans('cortex/auth::messages.auth.session.flushed')], ]); }
[ "public", "function", "flush", "(", "Request", "$", "request", ")", "{", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", "->", "sessions", "(", ")", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/auth::messages.auth.session.flushed'", ")", "]", ",", "]", ")", ";", "}" ]
Flush all sessions. @param \Illuminate\Http\Request $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Flush", "all", "sessions", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountSessionsController.php#L49-L57
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountSettingsController.php
AccountSettingsController.edit
public function edit(Request $request) { $countries = collect(countries())->map(function ($country, $code) { return [ 'id' => $code, 'text' => $country['name'], 'emoji' => $country['emoji'], ]; })->values(); $languages = collect(languages())->pluck('name', 'iso_639_1'); $genders = ['male' => trans('cortex/auth::common.male'), 'female' => trans('cortex/auth::common.female')]; return view('cortex/auth::adminarea.pages.account-settings', compact('countries', 'languages', 'genders')); }
php
public function edit(Request $request) { $countries = collect(countries())->map(function ($country, $code) { return [ 'id' => $code, 'text' => $country['name'], 'emoji' => $country['emoji'], ]; })->values(); $languages = collect(languages())->pluck('name', 'iso_639_1'); $genders = ['male' => trans('cortex/auth::common.male'), 'female' => trans('cortex/auth::common.female')]; return view('cortex/auth::adminarea.pages.account-settings', compact('countries', 'languages', 'genders')); }
[ "public", "function", "edit", "(", "Request", "$", "request", ")", "{", "$", "countries", "=", "collect", "(", "countries", "(", ")", ")", "->", "map", "(", "function", "(", "$", "country", ",", "$", "code", ")", "{", "return", "[", "'id'", "=>", "$", "code", ",", "'text'", "=>", "$", "country", "[", "'name'", "]", ",", "'emoji'", "=>", "$", "country", "[", "'emoji'", "]", ",", "]", ";", "}", ")", "->", "values", "(", ")", ";", "$", "languages", "=", "collect", "(", "languages", "(", ")", ")", "->", "pluck", "(", "'name'", ",", "'iso_639_1'", ")", ";", "$", "genders", "=", "[", "'male'", "=>", "trans", "(", "'cortex/auth::common.male'", ")", ",", "'female'", "=>", "trans", "(", "'cortex/auth::common.female'", ")", "]", ";", "return", "view", "(", "'cortex/auth::adminarea.pages.account-settings'", ",", "compact", "(", "'countries'", ",", "'languages'", ",", "'genders'", ")", ")", ";", "}" ]
Edit account settings. @param \Illuminate\Http\Request $request @return \Illuminate\View\View
[ "Edit", "account", "settings", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountSettingsController.php#L30-L43
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountSettingsController.php
AccountSettingsController.update
public function update(AccountSettingsRequest $request) { $data = $request->validated(); $currentUser = $request->user($this->getGuard()); ! $request->hasFile('profile_picture') || $currentUser->addMediaFromRequest('profile_picture') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('profile_picture', config('cortex.auth.media.disk')); ! $request->hasFile('cover_photo') || $currentUser->addMediaFromRequest('cover_photo') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('cover_photo', config('cortex.auth.media.disk')); // Update profile $currentUser->fill($data)->save(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.account.updated_account')] + (isset($data['two_factor']) ? ['warning' => trans('cortex/auth::messages.verification.twofactor.phone.auto_disabled')] : []), ]); }
php
public function update(AccountSettingsRequest $request) { $data = $request->validated(); $currentUser = $request->user($this->getGuard()); ! $request->hasFile('profile_picture') || $currentUser->addMediaFromRequest('profile_picture') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('profile_picture', config('cortex.auth.media.disk')); ! $request->hasFile('cover_photo') || $currentUser->addMediaFromRequest('cover_photo') ->sanitizingFileName(function ($fileName) { return md5($fileName).'.'.pathinfo($fileName, PATHINFO_EXTENSION); }) ->toMediaCollection('cover_photo', config('cortex.auth.media.disk')); // Update profile $currentUser->fill($data)->save(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.account.updated_account')] + (isset($data['two_factor']) ? ['warning' => trans('cortex/auth::messages.verification.twofactor.phone.auto_disabled')] : []), ]); }
[ "public", "function", "update", "(", "AccountSettingsRequest", "$", "request", ")", "{", "$", "data", "=", "$", "request", "->", "validated", "(", ")", ";", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "!", "$", "request", "->", "hasFile", "(", "'profile_picture'", ")", "||", "$", "currentUser", "->", "addMediaFromRequest", "(", "'profile_picture'", ")", "->", "sanitizingFileName", "(", "function", "(", "$", "fileName", ")", "{", "return", "md5", "(", "$", "fileName", ")", ".", "'.'", ".", "pathinfo", "(", "$", "fileName", ",", "PATHINFO_EXTENSION", ")", ";", "}", ")", "->", "toMediaCollection", "(", "'profile_picture'", ",", "config", "(", "'cortex.auth.media.disk'", ")", ")", ";", "!", "$", "request", "->", "hasFile", "(", "'cover_photo'", ")", "||", "$", "currentUser", "->", "addMediaFromRequest", "(", "'cover_photo'", ")", "->", "sanitizingFileName", "(", "function", "(", "$", "fileName", ")", "{", "return", "md5", "(", "$", "fileName", ")", ".", "'.'", ".", "pathinfo", "(", "$", "fileName", ",", "PATHINFO_EXTENSION", ")", ";", "}", ")", "->", "toMediaCollection", "(", "'cover_photo'", ",", "config", "(", "'cortex.auth.media.disk'", ")", ")", ";", "// Update profile", "$", "currentUser", "->", "fill", "(", "$", "data", ")", "->", "save", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.account.updated_account'", ")", "]", "+", "(", "isset", "(", "$", "data", "[", "'two_factor'", "]", ")", "?", "[", "'warning'", "=>", "trans", "(", "'cortex/auth::messages.verification.twofactor.phone.auto_disabled'", ")", "]", ":", "[", "]", ")", ",", "]", ")", ";", "}" ]
Update account settings. @param \Cortex\Auth\Http\Requests\Adminarea\AccountSettingsRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Update", "account", "settings", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountSettingsController.php#L52-L79
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AccountAttributesController.php
AccountAttributesController.update
public function update(AccountAttributesRequest $request) { $data = $request->validated(); $currentUser = $request->user($this->getGuard()); // Update profile $currentUser->fill($data)->save(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.account.updated_attributes')], ]); }
php
public function update(AccountAttributesRequest $request) { $data = $request->validated(); $currentUser = $request->user($this->getGuard()); // Update profile $currentUser->fill($data)->save(); return intend([ 'back' => true, 'with' => ['success' => trans('cortex/auth::messages.account.updated_attributes')], ]); }
[ "public", "function", "update", "(", "AccountAttributesRequest", "$", "request", ")", "{", "$", "data", "=", "$", "request", "->", "validated", "(", ")", ";", "$", "currentUser", "=", "$", "request", "->", "user", "(", "$", "this", "->", "getGuard", "(", ")", ")", ";", "// Update profile", "$", "currentUser", "->", "fill", "(", "$", "data", ")", "->", "save", "(", ")", ";", "return", "intend", "(", "[", "'back'", "=>", "true", ",", "'with'", "=>", "[", "'success'", "=>", "trans", "(", "'cortex/auth::messages.account.updated_attributes'", ")", "]", ",", "]", ")", ";", "}" ]
Update account attributes. @param \Cortex\Auth\Http\Requests\Adminarea\AccountAttributesRequest $request @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Update", "account", "attributes", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AccountAttributesController.php#L32-L44
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.getAlignedArray
private function getAlignedArray(array $array, $depth, array $options, callable $encode) { $next = 0; $omit = $options['array.omit']; foreach (array_keys($array) as $key) { if ($key !== $next++) { $omit = false; break; } } return $omit ? $this->getFormattedArray($array, $depth, $options, $encode) : $this->buildArray($this->getAlignedPairs($array, $encode), $depth, $options); }
php
private function getAlignedArray(array $array, $depth, array $options, callable $encode) { $next = 0; $omit = $options['array.omit']; foreach (array_keys($array) as $key) { if ($key !== $next++) { $omit = false; break; } } return $omit ? $this->getFormattedArray($array, $depth, $options, $encode) : $this->buildArray($this->getAlignedPairs($array, $encode), $depth, $options); }
[ "private", "function", "getAlignedArray", "(", "array", "$", "array", ",", "$", "depth", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "$", "next", "=", "0", ";", "$", "omit", "=", "$", "options", "[", "'array.omit'", "]", ";", "foreach", "(", "array_keys", "(", "$", "array", ")", "as", "$", "key", ")", "{", "if", "(", "$", "key", "!==", "$", "next", "++", ")", "{", "$", "omit", "=", "false", ";", "break", ";", "}", "}", "return", "$", "omit", "?", "$", "this", "->", "getFormattedArray", "(", "$", "array", ",", "$", "depth", ",", "$", "options", ",", "$", "encode", ")", ":", "$", "this", "->", "buildArray", "(", "$", "this", "->", "getAlignedPairs", "(", "$", "array", ",", "$", "encode", ")", ",", "$", "depth", ",", "$", "options", ")", ";", "}" ]
Returns the PHP code for aligned array accounting for omitted keys and inline arrays. @param array $array Array to encode @param int $depth Current indentation depth of the output @param array $options List of encoder options @param callable $encode Callback used to encode values @return string The PHP code representation for the array
[ "Returns", "the", "PHP", "code", "for", "aligned", "array", "accounting", "for", "omitted", "keys", "and", "inline", "arrays", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L58-L73
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.getFormattedArray
private function getFormattedArray(array $array, $depth, array $options, callable $encode) { $lines = $this->getPairs($array, ' ', $options['array.omit'], $encode, $omitted); if ($omitted && $options['array.inline'] !== false) { $output = $this->getInlineArray($lines, $options); if ($output !== false) { return $output; } } return $this->buildArray($lines, $depth, $options); }
php
private function getFormattedArray(array $array, $depth, array $options, callable $encode) { $lines = $this->getPairs($array, ' ', $options['array.omit'], $encode, $omitted); if ($omitted && $options['array.inline'] !== false) { $output = $this->getInlineArray($lines, $options); if ($output !== false) { return $output; } } return $this->buildArray($lines, $depth, $options); }
[ "private", "function", "getFormattedArray", "(", "array", "$", "array", ",", "$", "depth", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "$", "lines", "=", "$", "this", "->", "getPairs", "(", "$", "array", ",", "' '", ",", "$", "options", "[", "'array.omit'", "]", ",", "$", "encode", ",", "$", "omitted", ")", ";", "if", "(", "$", "omitted", "&&", "$", "options", "[", "'array.inline'", "]", "!==", "false", ")", "{", "$", "output", "=", "$", "this", "->", "getInlineArray", "(", "$", "lines", ",", "$", "options", ")", ";", "if", "(", "$", "output", "!==", "false", ")", "{", "return", "$", "output", ";", "}", "}", "return", "$", "this", "->", "buildArray", "(", "$", "lines", ",", "$", "depth", ",", "$", "options", ")", ";", "}" ]
Returns the PHP code for the array as inline or multi line array. @param array $array Array to encode @param int $depth Current indentation depth of the output @param array $options List of encoder options @param callable $encode Callback used to encode values @return string The PHP code representation for the array
[ "Returns", "the", "PHP", "code", "for", "the", "array", "as", "inline", "or", "multi", "line", "array", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L83-L96
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.getInlineArray
private function getInlineArray(array $lines, array $options) { $output = $this->wrap(implode(', ', $lines), $options['array.short']); if (preg_match('/[\r\n\t]/', $output)) { return false; } elseif ($options['array.inline'] === true || \strlen($output) <= (int) $options['array.inline']) { return $output; } return false; }
php
private function getInlineArray(array $lines, array $options) { $output = $this->wrap(implode(', ', $lines), $options['array.short']); if (preg_match('/[\r\n\t]/', $output)) { return false; } elseif ($options['array.inline'] === true || \strlen($output) <= (int) $options['array.inline']) { return $output; } return false; }
[ "private", "function", "getInlineArray", "(", "array", "$", "lines", ",", "array", "$", "options", ")", "{", "$", "output", "=", "$", "this", "->", "wrap", "(", "implode", "(", "', '", ",", "$", "lines", ")", ",", "$", "options", "[", "'array.short'", "]", ")", ";", "if", "(", "preg_match", "(", "'/[\\r\\n\\t]/'", ",", "$", "output", ")", ")", "{", "return", "false", ";", "}", "elseif", "(", "$", "options", "[", "'array.inline'", "]", "===", "true", "||", "\\", "strlen", "(", "$", "output", ")", "<=", "(", "int", ")", "$", "options", "[", "'array.inline'", "]", ")", "{", "return", "$", "output", ";", "}", "return", "false", ";", "}" ]
Returns the code for the inline array, if possible. @param string[] $lines Encoded key and value pairs @param array $options List of encoder options @return string|false Array encoded as single line of PHP code or false if not possible
[ "Returns", "the", "code", "for", "the", "inline", "array", "if", "possible", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L104-L115
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.buildArray
private function buildArray(array $lines, $depth, array $options) { $indent = $this->buildIndent($options['array.base'], $options['array.indent'], $depth + 1); $last = $this->buildIndent($options['array.base'], $options['array.indent'], $depth); $eol = $options['array.eol'] === false ? \PHP_EOL : (string) $options['array.eol']; return $this->wrap( sprintf('%s%s%s,%1$s%s', $eol, $indent, implode(',' . $eol . $indent, $lines), $last), $options['array.short'] ); }
php
private function buildArray(array $lines, $depth, array $options) { $indent = $this->buildIndent($options['array.base'], $options['array.indent'], $depth + 1); $last = $this->buildIndent($options['array.base'], $options['array.indent'], $depth); $eol = $options['array.eol'] === false ? \PHP_EOL : (string) $options['array.eol']; return $this->wrap( sprintf('%s%s%s,%1$s%s', $eol, $indent, implode(',' . $eol . $indent, $lines), $last), $options['array.short'] ); }
[ "private", "function", "buildArray", "(", "array", "$", "lines", ",", "$", "depth", ",", "array", "$", "options", ")", "{", "$", "indent", "=", "$", "this", "->", "buildIndent", "(", "$", "options", "[", "'array.base'", "]", ",", "$", "options", "[", "'array.indent'", "]", ",", "$", "depth", "+", "1", ")", ";", "$", "last", "=", "$", "this", "->", "buildIndent", "(", "$", "options", "[", "'array.base'", "]", ",", "$", "options", "[", "'array.indent'", "]", ",", "$", "depth", ")", ";", "$", "eol", "=", "$", "options", "[", "'array.eol'", "]", "===", "false", "?", "\\", "PHP_EOL", ":", "(", "string", ")", "$", "options", "[", "'array.eol'", "]", ";", "return", "$", "this", "->", "wrap", "(", "sprintf", "(", "'%s%s%s,%1$s%s'", ",", "$", "eol", ",", "$", "indent", ",", "implode", "(", "','", ".", "$", "eol", ".", "$", "indent", ",", "$", "lines", ")", ",", "$", "last", ")", ",", "$", "options", "[", "'array.short'", "]", ")", ";", "}" ]
Builds the complete array from the encoded key and value pairs. @param string[] $lines Encoded key and value pairs @param int $depth Current indentation depth of the output @param array $options List of encoder options @return string Array encoded as PHP code
[ "Builds", "the", "complete", "array", "from", "the", "encoded", "key", "and", "value", "pairs", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L124-L134
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.buildIndent
private function buildIndent($base, $indent, $depth) { $base = \is_int($base) ? str_repeat(' ', $base) : (string) $base; return $depth === 0 ? $base : $base . str_repeat( \is_int($indent) ? str_repeat(' ', $indent) : (string) $indent, $depth ); }
php
private function buildIndent($base, $indent, $depth) { $base = \is_int($base) ? str_repeat(' ', $base) : (string) $base; return $depth === 0 ? $base : $base . str_repeat( \is_int($indent) ? str_repeat(' ', $indent) : (string) $indent, $depth ); }
[ "private", "function", "buildIndent", "(", "$", "base", ",", "$", "indent", ",", "$", "depth", ")", "{", "$", "base", "=", "\\", "is_int", "(", "$", "base", ")", "?", "str_repeat", "(", "' '", ",", "$", "base", ")", ":", "(", "string", ")", "$", "base", ";", "return", "$", "depth", "===", "0", "?", "$", "base", ":", "$", "base", ".", "str_repeat", "(", "\\", "is_int", "(", "$", "indent", ")", "?", "str_repeat", "(", "' '", ",", "$", "indent", ")", ":", "(", "string", ")", "$", "indent", ",", "$", "depth", ")", ";", "}" ]
Builds the indentation based on the options. @param string|int $base The base indentation @param string|int $indent A single indentation level @param int $depth The level of indentation @return string The indentation for the current depth
[ "Builds", "the", "indentation", "based", "on", "the", "options", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L154-L162
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.getAlignedPairs
private function getAlignedPairs(array $array, callable $encode) { $keys = []; $values = []; foreach ($array as $key => $value) { $keys[] = $encode($key, 1); $values[] = $encode($value, 1); } $format = sprintf('%%-%ds => %%s', max(array_map('strlen', $keys))); $pairs = []; for ($i = 0, $count = \count($keys); $i < $count; $i++) { $pairs[] = sprintf($format, $keys[$i], $values[$i]); } return $pairs; }
php
private function getAlignedPairs(array $array, callable $encode) { $keys = []; $values = []; foreach ($array as $key => $value) { $keys[] = $encode($key, 1); $values[] = $encode($value, 1); } $format = sprintf('%%-%ds => %%s', max(array_map('strlen', $keys))); $pairs = []; for ($i = 0, $count = \count($keys); $i < $count; $i++) { $pairs[] = sprintf($format, $keys[$i], $values[$i]); } return $pairs; }
[ "private", "function", "getAlignedPairs", "(", "array", "$", "array", ",", "callable", "$", "encode", ")", "{", "$", "keys", "=", "[", "]", ";", "$", "values", "=", "[", "]", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "keys", "[", "]", "=", "$", "encode", "(", "$", "key", ",", "1", ")", ";", "$", "values", "[", "]", "=", "$", "encode", "(", "$", "value", ",", "1", ")", ";", "}", "$", "format", "=", "sprintf", "(", "'%%-%ds => %%s'", ",", "max", "(", "array_map", "(", "'strlen'", ",", "$", "keys", ")", ")", ")", ";", "$", "pairs", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ",", "$", "count", "=", "\\", "count", "(", "$", "keys", ")", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "pairs", "[", "]", "=", "sprintf", "(", "$", "format", ",", "$", "keys", "[", "$", "i", "]", ",", "$", "values", "[", "$", "i", "]", ")", ";", "}", "return", "$", "pairs", ";", "}" ]
Returns each encoded key and value pair with aligned assignment operators. @param array $array Array to convert into code @param callable $encode Callback used to encode values @return string[] Each of key and value pair encoded as php
[ "Returns", "each", "encoded", "key", "and", "value", "pair", "with", "aligned", "assignment", "operators", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L170-L188
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.getPairs
private function getPairs(array $array, $space, $omit, callable $encode, & $omitted = true) { $pairs = []; $nextIndex = 0; $omitted = true; $format = '%s' . $space . '=>' . $space . '%s'; foreach ($array as $key => $value) { if ($omit && $this->canOmitKey($key, $nextIndex)) { $pairs[] = $encode($value, 1); } else { $pairs[] = sprintf($format, $encode($key, 1), $encode($value, 1)); $omitted = false; } } return $pairs; }
php
private function getPairs(array $array, $space, $omit, callable $encode, & $omitted = true) { $pairs = []; $nextIndex = 0; $omitted = true; $format = '%s' . $space . '=>' . $space . '%s'; foreach ($array as $key => $value) { if ($omit && $this->canOmitKey($key, $nextIndex)) { $pairs[] = $encode($value, 1); } else { $pairs[] = sprintf($format, $encode($key, 1), $encode($value, 1)); $omitted = false; } } return $pairs; }
[ "private", "function", "getPairs", "(", "array", "$", "array", ",", "$", "space", ",", "$", "omit", ",", "callable", "$", "encode", ",", "&", "$", "omitted", "=", "true", ")", "{", "$", "pairs", "=", "[", "]", ";", "$", "nextIndex", "=", "0", ";", "$", "omitted", "=", "true", ";", "$", "format", "=", "'%s'", ".", "$", "space", ".", "'=>'", ".", "$", "space", ".", "'%s'", ";", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "omit", "&&", "$", "this", "->", "canOmitKey", "(", "$", "key", ",", "$", "nextIndex", ")", ")", "{", "$", "pairs", "[", "]", "=", "$", "encode", "(", "$", "value", ",", "1", ")", ";", "}", "else", "{", "$", "pairs", "[", "]", "=", "sprintf", "(", "$", "format", ",", "$", "encode", "(", "$", "key", ",", "1", ")", ",", "$", "encode", "(", "$", "value", ",", "1", ")", ")", ";", "$", "omitted", "=", "false", ";", "}", "}", "return", "$", "pairs", ";", "}" ]
Returns each key and value pair encoded as array assignment. @param array $array Array to convert into code @param string $space Whitespace between array assignment operator @param bool $omit True to omit unnecessary keys, false to not @param callable $encode Callback used to encode values @param bool $omitted Set to true, if all the keys were omitted, false otherwise @return string[] Each of key and value pair encoded as php
[ "Returns", "each", "key", "and", "value", "pair", "encoded", "as", "array", "assignment", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L199-L216
train
Riimu/Kit-PHPEncoder
src/Encoder/ArrayEncoder.php
ArrayEncoder.canOmitKey
private function canOmitKey($key, & $nextIndex) { $result = $key === $nextIndex; if (\is_int($key)) { $nextIndex = max($key + 1, $nextIndex); } return $result; }
php
private function canOmitKey($key, & $nextIndex) { $result = $key === $nextIndex; if (\is_int($key)) { $nextIndex = max($key + 1, $nextIndex); } return $result; }
[ "private", "function", "canOmitKey", "(", "$", "key", ",", "&", "$", "nextIndex", ")", "{", "$", "result", "=", "$", "key", "===", "$", "nextIndex", ";", "if", "(", "\\", "is_int", "(", "$", "key", ")", ")", "{", "$", "nextIndex", "=", "max", "(", "$", "key", "+", "1", ",", "$", "nextIndex", ")", ";", "}", "return", "$", "result", ";", "}" ]
Tells if the key can be omitted from array output based on expected index. @param int|string $key Current array key @param int $nextIndex Next expected key that can be omitted @return bool True if the key can be omitted, false if not
[ "Tells", "if", "the", "key", "can", "be", "omitted", "from", "array", "output", "based", "on", "expected", "index", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ArrayEncoder.php#L224-L233
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AbilitiesController.php
AbilitiesController.import
public function import(Ability $ability, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $ability, 'tabs' => 'adminarea.abilities.tabs', 'url' => route('adminarea.abilities.stash'), 'id' => "adminarea-abilities-{$ability->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
php
public function import(Ability $ability, ImportRecordsDataTable $importRecordsDataTable) { return $importRecordsDataTable->with([ 'resource' => $ability, 'tabs' => 'adminarea.abilities.tabs', 'url' => route('adminarea.abilities.stash'), 'id' => "adminarea-abilities-{$ability->getRouteKey()}-import-table", ])->render('cortex/foundation::adminarea.pages.datatable-dropzone'); }
[ "public", "function", "import", "(", "Ability", "$", "ability", ",", "ImportRecordsDataTable", "$", "importRecordsDataTable", ")", "{", "return", "$", "importRecordsDataTable", "->", "with", "(", "[", "'resource'", "=>", "$", "ability", ",", "'tabs'", "=>", "'adminarea.abilities.tabs'", ",", "'url'", "=>", "route", "(", "'adminarea.abilities.stash'", ")", ",", "'id'", "=>", "\"adminarea-abilities-{$ability->getRouteKey()}-import-table\"", ",", "]", ")", "->", "render", "(", "'cortex/foundation::adminarea.pages.datatable-dropzone'", ")", ";", "}" ]
Import abilities. @param \Cortex\Auth\Models\Ability $ability @param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable @return \Illuminate\View\View
[ "Import", "abilities", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AbilitiesController.php#L67-L75
train
rinvex/cortex-auth
src/Http/Controllers/Adminarea/AbilitiesController.php
AbilitiesController.destroy
public function destroy(Ability $ability) { $ability->delete(); return intend([ 'url' => route('adminarea.abilities.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.ability'), 'identifier' => $ability->title])], ]); }
php
public function destroy(Ability $ability) { $ability->delete(); return intend([ 'url' => route('adminarea.abilities.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/auth::common.ability'), 'identifier' => $ability->title])], ]); }
[ "public", "function", "destroy", "(", "Ability", "$", "ability", ")", "{", "$", "ability", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'adminarea.abilities.index'", ")", ",", "'with'", "=>", "[", "'warning'", "=>", "trans", "(", "'cortex/foundation::messages.resource_deleted'", ",", "[", "'resource'", "=>", "trans", "(", "'cortex/auth::common.ability'", ")", ",", "'identifier'", "=>", "$", "ability", "->", "title", "]", ")", "]", ",", "]", ")", ";", "}" ]
Destroy given ability. @param \Cortex\Auth\Models\Ability $ability @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "ability", "." ]
44a380a415bb1a1c3d48718abc5298b9e82888fb
https://github.com/rinvex/cortex-auth/blob/44a380a415bb1a1c3d48718abc5298b9e82888fb/src/Http/Controllers/Adminarea/AbilitiesController.php#L238-L246
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.addEncoder
public function addEncoder(Encoder\Encoder $encoder, $prepend = false) { $prepend ? array_unshift($this->encoders, $encoder) : array_push($this->encoders, $encoder); }
php
public function addEncoder(Encoder\Encoder $encoder, $prepend = false) { $prepend ? array_unshift($this->encoders, $encoder) : array_push($this->encoders, $encoder); }
[ "public", "function", "addEncoder", "(", "Encoder", "\\", "Encoder", "$", "encoder", ",", "$", "prepend", "=", "false", ")", "{", "$", "prepend", "?", "array_unshift", "(", "$", "this", "->", "encoders", ",", "$", "encoder", ")", ":", "array_push", "(", "$", "this", "->", "encoders", ",", "$", "encoder", ")", ";", "}" ]
Adds a new encoder. Values are always encoded by the first encoder that supports encoding that type of value. By setting the second optional parameter to true, you can prepend the encoder to the list to ensure that it will be tested first. @param Encoder\Encoder $encoder Encoder for encoding values @param bool $prepend True to prepend the encoder to the list, false to add it as last
[ "Adds", "a", "new", "encoder", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L84-L87
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.setOption
public function setOption($option, $value) { if (!$this->isValidOption($option)) { throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $option)); } $this->options[$option] = $value; }
php
public function setOption($option, $value) { if (!$this->isValidOption($option)) { throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $option)); } $this->options[$option] = $value; }
[ "public", "function", "setOption", "(", "$", "option", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "isValidOption", "(", "$", "option", ")", ")", "{", "throw", "new", "InvalidOptionException", "(", "sprintf", "(", "\"Invalid encoder option '%s'\"", ",", "$", "option", ")", ")", ";", "}", "$", "this", "->", "options", "[", "$", "option", "]", "=", "$", "value", ";", "}" ]
Sets the value for an encoder option. @param string $option Name of the option @param mixed $value Value for the option @throws InvalidOptionException If the provided encoder option is invalid
[ "Sets", "the", "value", "for", "an", "encoder", "option", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L95-L102
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.isValidOption
private function isValidOption($option) { if (array_key_exists($option, $this->options)) { return true; } foreach ($this->encoders as $encoder) { if (array_key_exists($option, $encoder->getDefaultOptions())) { return true; } } return false; }
php
private function isValidOption($option) { if (array_key_exists($option, $this->options)) { return true; } foreach ($this->encoders as $encoder) { if (array_key_exists($option, $encoder->getDefaultOptions())) { return true; } } return false; }
[ "private", "function", "isValidOption", "(", "$", "option", ")", "{", "if", "(", "array_key_exists", "(", "$", "option", ",", "$", "this", "->", "options", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "$", "this", "->", "encoders", "as", "$", "encoder", ")", "{", "if", "(", "array_key_exists", "(", "$", "option", ",", "$", "encoder", "->", "getDefaultOptions", "(", ")", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Tells if the given string is a valid option name. @param string $option Option name to validate @return bool True if the name is a valid option name, false if not
[ "Tells", "if", "the", "given", "string", "is", "a", "valid", "option", "name", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L109-L122
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.getAllOptions
public function getAllOptions(array $overrides = []) { $options = $this->options; foreach ($this->encoders as $encoder) { $options += $encoder->getDefaultOptions(); } foreach ($overrides as $name => $value) { if (!array_key_exists($name, $options)) { throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $name)); } $options[$name] = $value; } ksort($options); return $options; }
php
public function getAllOptions(array $overrides = []) { $options = $this->options; foreach ($this->encoders as $encoder) { $options += $encoder->getDefaultOptions(); } foreach ($overrides as $name => $value) { if (!array_key_exists($name, $options)) { throw new InvalidOptionException(sprintf("Invalid encoder option '%s'", $name)); } $options[$name] = $value; } ksort($options); return $options; }
[ "public", "function", "getAllOptions", "(", "array", "$", "overrides", "=", "[", "]", ")", "{", "$", "options", "=", "$", "this", "->", "options", ";", "foreach", "(", "$", "this", "->", "encoders", "as", "$", "encoder", ")", "{", "$", "options", "+=", "$", "encoder", "->", "getDefaultOptions", "(", ")", ";", "}", "foreach", "(", "$", "overrides", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "name", ",", "$", "options", ")", ")", "{", "throw", "new", "InvalidOptionException", "(", "sprintf", "(", "\"Invalid encoder option '%s'\"", ",", "$", "name", ")", ")", ";", "}", "$", "options", "[", "$", "name", "]", "=", "$", "value", ";", "}", "ksort", "(", "$", "options", ")", ";", "return", "$", "options", ";", "}" ]
Returns a list of all encoder options. @param array $overrides Options to override in the returned array @return array List of encoder options @throws InvalidOptionException If any of the encoder option overrides are invalid
[ "Returns", "a", "list", "of", "all", "encoder", "options", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L144-L163
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.generate
private function generate($value, $depth, array $options, array $recursion = []) { if ($this->detectRecursion($value, $options, $recursion)) { $recursion[] = $value; } if ($options['recursion.max'] !== false && $depth > (int) $options['recursion.max']) { throw new \RuntimeException('Maximum encoding depth reached'); } $callback = function ($value, $level = 0, array $overrides = []) use ($depth, $options, $recursion) { return $this->generate($value, $depth + (int) $level, $overrides + $options, $recursion); }; return $this->encodeValue($value, $depth, $options, $callback); }
php
private function generate($value, $depth, array $options, array $recursion = []) { if ($this->detectRecursion($value, $options, $recursion)) { $recursion[] = $value; } if ($options['recursion.max'] !== false && $depth > (int) $options['recursion.max']) { throw new \RuntimeException('Maximum encoding depth reached'); } $callback = function ($value, $level = 0, array $overrides = []) use ($depth, $options, $recursion) { return $this->generate($value, $depth + (int) $level, $overrides + $options, $recursion); }; return $this->encodeValue($value, $depth, $options, $callback); }
[ "private", "function", "generate", "(", "$", "value", ",", "$", "depth", ",", "array", "$", "options", ",", "array", "$", "recursion", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "detectRecursion", "(", "$", "value", ",", "$", "options", ",", "$", "recursion", ")", ")", "{", "$", "recursion", "[", "]", "=", "$", "value", ";", "}", "if", "(", "$", "options", "[", "'recursion.max'", "]", "!==", "false", "&&", "$", "depth", ">", "(", "int", ")", "$", "options", "[", "'recursion.max'", "]", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Maximum encoding depth reached'", ")", ";", "}", "$", "callback", "=", "function", "(", "$", "value", ",", "$", "level", "=", "0", ",", "array", "$", "overrides", "=", "[", "]", ")", "use", "(", "$", "depth", ",", "$", "options", ",", "$", "recursion", ")", "{", "return", "$", "this", "->", "generate", "(", "$", "value", ",", "$", "depth", "+", "(", "int", ")", "$", "level", ",", "$", "overrides", "+", "$", "options", ",", "$", "recursion", ")", ";", "}", ";", "return", "$", "this", "->", "encodeValue", "(", "$", "value", ",", "$", "depth", ",", "$", "options", ",", "$", "callback", ")", ";", "}" ]
Generates the code for the given value recursively. @param mixed $value Value to encode @param int $depth Current indentation depth of the output @param array $options List of encoder options @param array $recursion Previously encoded values for recursion detection @return string The PHP code that represents the given value @throws \RuntimeException If max depth is reached or a recursive value is detected
[ "Generates", "the", "code", "for", "the", "given", "value", "recursively", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L174-L189
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.detectRecursion
private function detectRecursion(& $value, array $options, array $recursion) { if ($options['recursion.detect']) { if (array_search($value, $recursion, true) !== false) { if ($options['recursion.ignore']) { $value = null; } else { throw new \RuntimeException('A recursive value was detected'); } } return true; } return false; }
php
private function detectRecursion(& $value, array $options, array $recursion) { if ($options['recursion.detect']) { if (array_search($value, $recursion, true) !== false) { if ($options['recursion.ignore']) { $value = null; } else { throw new \RuntimeException('A recursive value was detected'); } } return true; } return false; }
[ "private", "function", "detectRecursion", "(", "&", "$", "value", ",", "array", "$", "options", ",", "array", "$", "recursion", ")", "{", "if", "(", "$", "options", "[", "'recursion.detect'", "]", ")", "{", "if", "(", "array_search", "(", "$", "value", ",", "$", "recursion", ",", "true", ")", "!==", "false", ")", "{", "if", "(", "$", "options", "[", "'recursion.ignore'", "]", ")", "{", "$", "value", "=", "null", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "'A recursive value was detected'", ")", ";", "}", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Attempts to detect circular references in values. @param mixed $value Value to try for circular reference @param array $options List of encoder options @param array $recursion Upper values in the encoding tree @return bool True if values should be recorded, false if not @throws \RuntimeException If a recursive value is detected
[ "Attempts", "to", "detect", "circular", "references", "in", "values", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L199-L214
train
Riimu/Kit-PHPEncoder
src/PHPEncoder.php
PHPEncoder.encodeValue
private function encodeValue($value, $depth, array $options, callable $encode) { foreach ($this->encoders as $encoder) { if ($encoder->supports($value)) { return $encoder->encode($value, $depth, $options, $encode); } } throw new \InvalidArgumentException(sprintf("Unsupported value type '%s'", \gettype($value))); }
php
private function encodeValue($value, $depth, array $options, callable $encode) { foreach ($this->encoders as $encoder) { if ($encoder->supports($value)) { return $encoder->encode($value, $depth, $options, $encode); } } throw new \InvalidArgumentException(sprintf("Unsupported value type '%s'", \gettype($value))); }
[ "private", "function", "encodeValue", "(", "$", "value", ",", "$", "depth", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "foreach", "(", "$", "this", "->", "encoders", "as", "$", "encoder", ")", "{", "if", "(", "$", "encoder", "->", "supports", "(", "$", "value", ")", ")", "{", "return", "$", "encoder", "->", "encode", "(", "$", "value", ",", "$", "depth", ",", "$", "options", ",", "$", "encode", ")", ";", "}", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "\"Unsupported value type '%s'\"", ",", "\\", "gettype", "(", "$", "value", ")", ")", ")", ";", "}" ]
Encodes the value using one of the encoders that supports the value type. @param mixed $value Value to encode @param int $depth Current indentation depth of the output @param array $options List of encoder options @param callable $encode Callback used to encode values @return string The PHP code that represents the given value @throws \InvalidArgumentException If the provided value contains an unsupported value type
[ "Encodes", "the", "value", "using", "one", "of", "the", "encoders", "that", "supports", "the", "value", "type", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/PHPEncoder.php#L225-L234
train
Riimu/Kit-PHPEncoder
src/Encoder/ObjectEncoder.php
ObjectEncoder.encodeObject
private function encodeObject($object, array $options, callable $encode) { if ($options['object.format'] === 'string') { return $encode((string) $object); } elseif ($options['object.format'] === 'serialize') { return sprintf('unserialize(%s)', $encode(serialize($object))); } elseif ($options['object.format'] === 'export') { return sprintf('\\%s::__set_state(%s)', \get_class($object), $encode($this->getObjectState($object))); } return $this->encodeObjectArray($object, $options, $encode); }
php
private function encodeObject($object, array $options, callable $encode) { if ($options['object.format'] === 'string') { return $encode((string) $object); } elseif ($options['object.format'] === 'serialize') { return sprintf('unserialize(%s)', $encode(serialize($object))); } elseif ($options['object.format'] === 'export') { return sprintf('\\%s::__set_state(%s)', \get_class($object), $encode($this->getObjectState($object))); } return $this->encodeObjectArray($object, $options, $encode); }
[ "private", "function", "encodeObject", "(", "$", "object", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "if", "(", "$", "options", "[", "'object.format'", "]", "===", "'string'", ")", "{", "return", "$", "encode", "(", "(", "string", ")", "$", "object", ")", ";", "}", "elseif", "(", "$", "options", "[", "'object.format'", "]", "===", "'serialize'", ")", "{", "return", "sprintf", "(", "'unserialize(%s)'", ",", "$", "encode", "(", "serialize", "(", "$", "object", ")", ")", ")", ";", "}", "elseif", "(", "$", "options", "[", "'object.format'", "]", "===", "'export'", ")", "{", "return", "sprintf", "(", "'\\\\%s::__set_state(%s)'", ",", "\\", "get_class", "(", "$", "object", ")", ",", "$", "encode", "(", "$", "this", "->", "getObjectState", "(", "$", "object", ")", ")", ")", ";", "}", "return", "$", "this", "->", "encodeObjectArray", "(", "$", "object", ",", "$", "options", ",", "$", "encode", ")", ";", "}" ]
Encodes the object as string according to encoding options. @param object $object Object to encode as PHP @param array $options List of encoder options @param callable $encode Callback used to encode values @return string The object encoded as string
[ "Encodes", "the", "object", "as", "string", "according", "to", "encoding", "options", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ObjectEncoder.php#L50-L61
train
Riimu/Kit-PHPEncoder
src/Encoder/ObjectEncoder.php
ObjectEncoder.encodeObjectArray
private function encodeObjectArray($object, array $options, callable $encode) { if (!\in_array((string) $options['object.format'], ['array', 'vars', 'iterate'], true)) { throw new \RuntimeException('Invalid object encoding format: ' . $options['object.format']); } $output = $encode($this->getObjectArray($object, $options['object.format'])); if ($options['object.cast']) { $output = '(object)' . ($options['whitespace'] ? ' ' : '') . $output; } return $output; }
php
private function encodeObjectArray($object, array $options, callable $encode) { if (!\in_array((string) $options['object.format'], ['array', 'vars', 'iterate'], true)) { throw new \RuntimeException('Invalid object encoding format: ' . $options['object.format']); } $output = $encode($this->getObjectArray($object, $options['object.format'])); if ($options['object.cast']) { $output = '(object)' . ($options['whitespace'] ? ' ' : '') . $output; } return $output; }
[ "private", "function", "encodeObjectArray", "(", "$", "object", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "if", "(", "!", "\\", "in_array", "(", "(", "string", ")", "$", "options", "[", "'object.format'", "]", ",", "[", "'array'", ",", "'vars'", ",", "'iterate'", "]", ",", "true", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Invalid object encoding format: '", ".", "$", "options", "[", "'object.format'", "]", ")", ";", "}", "$", "output", "=", "$", "encode", "(", "$", "this", "->", "getObjectArray", "(", "$", "object", ",", "$", "options", "[", "'object.format'", "]", ")", ")", ";", "if", "(", "$", "options", "[", "'object.cast'", "]", ")", "{", "$", "output", "=", "'(object)'", ".", "(", "$", "options", "[", "'whitespace'", "]", "?", "' '", ":", "''", ")", ".", "$", "output", ";", "}", "return", "$", "output", ";", "}" ]
Encodes the object into one of the array formats. @param object $object Object to encode as PHP @param array $options List of encoder options @param callable $encode Callback used to encode values @return string The object encoded as string @throws \RuntimeException If the object format is invalid
[ "Encodes", "the", "object", "into", "one", "of", "the", "array", "formats", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ObjectEncoder.php#L71-L84
train
Riimu/Kit-PHPEncoder
src/Encoder/ObjectEncoder.php
ObjectEncoder.getObjectArray
private function getObjectArray($object, $format) { if ($format === 'array') { return (array) $object; } elseif ($format === 'vars') { return get_object_vars($object); } $array = []; foreach ($object as $key => $value) { $array[$key] = $value; } return $array; }
php
private function getObjectArray($object, $format) { if ($format === 'array') { return (array) $object; } elseif ($format === 'vars') { return get_object_vars($object); } $array = []; foreach ($object as $key => $value) { $array[$key] = $value; } return $array; }
[ "private", "function", "getObjectArray", "(", "$", "object", ",", "$", "format", ")", "{", "if", "(", "$", "format", "===", "'array'", ")", "{", "return", "(", "array", ")", "$", "object", ";", "}", "elseif", "(", "$", "format", "===", "'vars'", ")", "{", "return", "get_object_vars", "(", "$", "object", ")", ";", "}", "$", "array", "=", "[", "]", ";", "foreach", "(", "$", "object", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "array", "[", "$", "key", "]", "=", "$", "value", ";", "}", "return", "$", "array", ";", "}" ]
Converts the object into array that can be encoded. @param object $object Object to convert to an array @param string $format Object conversion format @return array The object converted into an array @throws \RuntimeException If object conversion format is invalid
[ "Converts", "the", "object", "into", "array", "that", "can", "be", "encoded", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ObjectEncoder.php#L93-L108
train
Riimu/Kit-PHPEncoder
src/Encoder/ObjectEncoder.php
ObjectEncoder.getObjectState
private function getObjectState($object) { $class = new \ReflectionClass($object); $visibility = \ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED; $values = []; do { foreach ($class->getProperties($visibility) as $property) { $property->setAccessible(true); $values[$property->getName()] = $property->getValue($object); } $class = $class->getParentClass(); $visibility = \ReflectionProperty::IS_PRIVATE; } while ($class); return get_object_vars($object) + $values; }
php
private function getObjectState($object) { $class = new \ReflectionClass($object); $visibility = \ReflectionProperty::IS_PRIVATE | \ReflectionProperty::IS_PROTECTED; $values = []; do { foreach ($class->getProperties($visibility) as $property) { $property->setAccessible(true); $values[$property->getName()] = $property->getValue($object); } $class = $class->getParentClass(); $visibility = \ReflectionProperty::IS_PRIVATE; } while ($class); return get_object_vars($object) + $values; }
[ "private", "function", "getObjectState", "(", "$", "object", ")", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "object", ")", ";", "$", "visibility", "=", "\\", "ReflectionProperty", "::", "IS_PRIVATE", "|", "\\", "ReflectionProperty", "::", "IS_PROTECTED", ";", "$", "values", "=", "[", "]", ";", "do", "{", "foreach", "(", "$", "class", "->", "getProperties", "(", "$", "visibility", ")", "as", "$", "property", ")", "{", "$", "property", "->", "setAccessible", "(", "true", ")", ";", "$", "values", "[", "$", "property", "->", "getName", "(", ")", "]", "=", "$", "property", "->", "getValue", "(", "$", "object", ")", ";", "}", "$", "class", "=", "$", "class", "->", "getParentClass", "(", ")", ";", "$", "visibility", "=", "\\", "ReflectionProperty", "::", "IS_PRIVATE", ";", "}", "while", "(", "$", "class", ")", ";", "return", "get_object_vars", "(", "$", "object", ")", "+", "$", "values", ";", "}" ]
Returns an array of object properties as would be generated by var_export. @param object $object Object to turn into array @return array Properties of the object as passed to var_export
[ "Returns", "an", "array", "of", "object", "properties", "as", "would", "be", "generated", "by", "var_export", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/ObjectEncoder.php#L115-L132
train
Riimu/Kit-PHPEncoder
src/Encoder/FloatEncoder.php
FloatEncoder.encodeNumber
private function encodeNumber($float, array $options, callable $encode) { if ($this->isInteger($float, $options['float.integers'])) { return $this->encodeInteger($float, $encode); } elseif ($float === 0.0) { return '0.0'; } elseif ($options['float.export']) { return var_export((float) $float, true); } return $this->encodeFloat($float, $this->determinePrecision($options)); }
php
private function encodeNumber($float, array $options, callable $encode) { if ($this->isInteger($float, $options['float.integers'])) { return $this->encodeInteger($float, $encode); } elseif ($float === 0.0) { return '0.0'; } elseif ($options['float.export']) { return var_export((float) $float, true); } return $this->encodeFloat($float, $this->determinePrecision($options)); }
[ "private", "function", "encodeNumber", "(", "$", "float", ",", "array", "$", "options", ",", "callable", "$", "encode", ")", "{", "if", "(", "$", "this", "->", "isInteger", "(", "$", "float", ",", "$", "options", "[", "'float.integers'", "]", ")", ")", "{", "return", "$", "this", "->", "encodeInteger", "(", "$", "float", ",", "$", "encode", ")", ";", "}", "elseif", "(", "$", "float", "===", "0.0", ")", "{", "return", "'0.0'", ";", "}", "elseif", "(", "$", "options", "[", "'float.export'", "]", ")", "{", "return", "var_export", "(", "(", "float", ")", "$", "float", ",", "true", ")", ";", "}", "return", "$", "this", "->", "encodeFloat", "(", "$", "float", ",", "$", "this", "->", "determinePrecision", "(", "$", "options", ")", ")", ";", "}" ]
Encodes the number as a PHP number representation. @param float $float The number to encode @param array $options The float encoding options @param callable $encode Callback used to encode values @return string The PHP code representation for the number
[ "Encodes", "the", "number", "as", "a", "PHP", "number", "representation", "." ]
ae9510fc135764d321b878fb7a952b410da63bda
https://github.com/Riimu/Kit-PHPEncoder/blob/ae9510fc135764d321b878fb7a952b410da63bda/src/Encoder/FloatEncoder.php#L51-L62
train