id
int32
0
241k
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
13,300
vi-kon/laravel-parser
src/ViKon/Parser/lexer/LexerPattern.php
LexerPattern.addPattern
public function addPattern($pattern, $childRuleName = null) { preg_match_all( '/\\\\.|' . // match \. '\(\?|[()]|' . // match "(" or ")" '\[\^?\]?(?:\\\\.|\[:[^]]*:\]|[^]\\\\])*\]|' . // match combination of "[]" '[^[()\\\\]+/', // match not in list "()\" $pattern, $matches); $groupDeep = 0; $pattern = '('; foreach ($matches[0] as $match) { switch ($match) { case '(': $pattern .= '\\('; break; case ')': if ($groupDeep > 0) { $groupDeep--; } else { $pattern .= '\\'; } $pattern .= ')'; break; case '(?': $groupDeep++; $pattern .= '(?'; break; default: $pattern .= substr($match, 0, 1) == '\\' ? $match : str_replace('/', '\\/', $match); break; } } $pattern .= ')'; $this->patterns[] = [ 'pattern' => $pattern, 'childRuleName' => $childRuleName, ]; }
php
public function addPattern($pattern, $childRuleName = null) { preg_match_all( '/\\\\.|' . // match \. '\(\?|[()]|' . // match "(" or ")" '\[\^?\]?(?:\\\\.|\[:[^]]*:\]|[^]\\\\])*\]|' . // match combination of "[]" '[^[()\\\\]+/', // match not in list "()\" $pattern, $matches); $groupDeep = 0; $pattern = '('; foreach ($matches[0] as $match) { switch ($match) { case '(': $pattern .= '\\('; break; case ')': if ($groupDeep > 0) { $groupDeep--; } else { $pattern .= '\\'; } $pattern .= ')'; break; case '(?': $groupDeep++; $pattern .= '(?'; break; default: $pattern .= substr($match, 0, 1) == '\\' ? $match : str_replace('/', '\\/', $match); break; } } $pattern .= ')'; $this->patterns[] = [ 'pattern' => $pattern, 'childRuleName' => $childRuleName, ]; }
[ "public", "function", "addPattern", "(", "$", "pattern", ",", "$", "childRuleName", "=", "null", ")", "{", "preg_match_all", "(", "'/\\\\\\\\.|'", ".", "// match \\.", "'\\(\\?|[()]|'", ".", "// match \"(\" or \")\"", "'\\[\\^?\\]?(?:\\\\\\\\.|\\[:[^]]*:\\]|[^]\\\\\\\\])*\\]|'", ".", "// match combination of \"[]\"", "'[^[()\\\\\\\\]+/'", ",", "// match not in list \"()\\\"", "$", "pattern", ",", "$", "matches", ")", ";", "$", "groupDeep", "=", "0", ";", "$", "pattern", "=", "'('", ";", "foreach", "(", "$", "matches", "[", "0", "]", "as", "$", "match", ")", "{", "switch", "(", "$", "match", ")", "{", "case", "'('", ":", "$", "pattern", ".=", "'\\\\('", ";", "break", ";", "case", "')'", ":", "if", "(", "$", "groupDeep", ">", "0", ")", "{", "$", "groupDeep", "--", ";", "}", "else", "{", "$", "pattern", ".=", "'\\\\'", ";", "}", "$", "pattern", ".=", "')'", ";", "break", ";", "case", "'(?'", ":", "$", "groupDeep", "++", ";", "$", "pattern", ".=", "'(?'", ";", "break", ";", "default", ":", "$", "pattern", ".=", "substr", "(", "$", "match", ",", "0", ",", "1", ")", "==", "'\\\\'", "?", "$", "match", ":", "str_replace", "(", "'/'", ",", "'\\\\/'", ",", "$", "match", ")", ";", "break", ";", "}", "}", "$", "pattern", ".=", "')'", ";", "$", "this", "->", "patterns", "[", "]", "=", "[", "'pattern'", "=>", "$", "pattern", ",", "'childRuleName'", "=>", "$", "childRuleName", ",", "]", ";", "}" ]
Add pattern to rule pattern @param string $pattern regex pattern @param string|null $childRuleName regex pattern owner rule name
[ "Add", "pattern", "to", "rule", "pattern" ]
070f0bb9120cb9ca6ff836d4f418e78ee33ee182
https://github.com/vi-kon/laravel-parser/blob/070f0bb9120cb9ca6ff836d4f418e78ee33ee182/src/ViKon/Parser/lexer/LexerPattern.php#L45-L90
13,301
vi-kon/laravel-parser
src/ViKon/Parser/lexer/LexerPattern.php
LexerPattern.split
public function split($text) { if (count($this->patterns) === 0) { return false; } if ($this->concatenatedPatterns === null) { $this->concatenatedPatterns = '/' . implode('|', array_map(function ($pattern) { return $pattern['pattern']; }, $this->patterns)) . '/msSi'; } if (!preg_match($this->concatenatedPatterns, $text, $matches)) { return false; } $match = array_shift($matches); $patternNo = count($matches) - 1; $childRuleName = $this->patterns[$patternNo]['childRuleName']; list($first, $end) = preg_split($this->patterns[$patternNo]['pattern'] . 'msSi', $text, 2); return [$first, $match, $end, $childRuleName]; }
php
public function split($text) { if (count($this->patterns) === 0) { return false; } if ($this->concatenatedPatterns === null) { $this->concatenatedPatterns = '/' . implode('|', array_map(function ($pattern) { return $pattern['pattern']; }, $this->patterns)) . '/msSi'; } if (!preg_match($this->concatenatedPatterns, $text, $matches)) { return false; } $match = array_shift($matches); $patternNo = count($matches) - 1; $childRuleName = $this->patterns[$patternNo]['childRuleName']; list($first, $end) = preg_split($this->patterns[$patternNo]['pattern'] . 'msSi', $text, 2); return [$first, $match, $end, $childRuleName]; }
[ "public", "function", "split", "(", "$", "text", ")", "{", "if", "(", "count", "(", "$", "this", "->", "patterns", ")", "===", "0", ")", "{", "return", "false", ";", "}", "if", "(", "$", "this", "->", "concatenatedPatterns", "===", "null", ")", "{", "$", "this", "->", "concatenatedPatterns", "=", "'/'", ".", "implode", "(", "'|'", ",", "array_map", "(", "function", "(", "$", "pattern", ")", "{", "return", "$", "pattern", "[", "'pattern'", "]", ";", "}", ",", "$", "this", "->", "patterns", ")", ")", ".", "'/msSi'", ";", "}", "if", "(", "!", "preg_match", "(", "$", "this", "->", "concatenatedPatterns", ",", "$", "text", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "$", "match", "=", "array_shift", "(", "$", "matches", ")", ";", "$", "patternNo", "=", "count", "(", "$", "matches", ")", "-", "1", ";", "$", "childRuleName", "=", "$", "this", "->", "patterns", "[", "$", "patternNo", "]", "[", "'childRuleName'", "]", ";", "list", "(", "$", "first", ",", "$", "end", ")", "=", "preg_split", "(", "$", "this", "->", "patterns", "[", "$", "patternNo", "]", "[", "'pattern'", "]", ".", "'msSi'", ",", "$", "text", ",", "2", ")", ";", "return", "[", "$", "first", ",", "$", "match", ",", "$", "end", ",", "$", "childRuleName", "]", ";", "}" ]
Split subject into pieces @param string $text raw text to split @return array|bool return array with exploded string chunks
[ "Split", "subject", "into", "pieces" ]
070f0bb9120cb9ca6ff836d4f418e78ee33ee182
https://github.com/vi-kon/laravel-parser/blob/070f0bb9120cb9ca6ff836d4f418e78ee33ee182/src/ViKon/Parser/lexer/LexerPattern.php#L99-L119
13,302
unimapper/unimapper
src/Validator.php
Validator.addCondition
public function addCondition($validation) { if (!$this->property) { throw new Exception\InvalidArgumentException( "Condition can be called only on properties!" ); } $condition = new Validator\Condition( $this->_getValidation($validation), $this ); $this->rules[] = $condition; return $condition->getValidator(); }
php
public function addCondition($validation) { if (!$this->property) { throw new Exception\InvalidArgumentException( "Condition can be called only on properties!" ); } $condition = new Validator\Condition( $this->_getValidation($validation), $this ); $this->rules[] = $condition; return $condition->getValidator(); }
[ "public", "function", "addCondition", "(", "$", "validation", ")", "{", "if", "(", "!", "$", "this", "->", "property", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "\"Condition can be called only on properties!\"", ")", ";", "}", "$", "condition", "=", "new", "Validator", "\\", "Condition", "(", "$", "this", "->", "_getValidation", "(", "$", "validation", ")", ",", "$", "this", ")", ";", "$", "this", "->", "rules", "[", "]", "=", "$", "condition", ";", "return", "$", "condition", "->", "getValidator", "(", ")", ";", "}" ]
Add validation condition @param mixed $validation Callable or some default validation method name @return \UniMapper\Validator
[ "Add", "validation", "condition" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Validator.php#L66-L79
13,303
unimapper/unimapper
src/Validator.php
Validator.addError
public function addError($message, $severity = Validator\Rule::ERROR, array $indexes = [] ) { $rule = new Validator\Rule( $this->entity, function () { return false; }, $message, $this->property, $severity, $this->child ); $rule->setChildFailed($indexes); $this->rules[] = $rule; return $this; }
php
public function addError($message, $severity = Validator\Rule::ERROR, array $indexes = [] ) { $rule = new Validator\Rule( $this->entity, function () { return false; }, $message, $this->property, $severity, $this->child ); $rule->setChildFailed($indexes); $this->rules[] = $rule; return $this; }
[ "public", "function", "addError", "(", "$", "message", ",", "$", "severity", "=", "Validator", "\\", "Rule", "::", "ERROR", ",", "array", "$", "indexes", "=", "[", "]", ")", "{", "$", "rule", "=", "new", "Validator", "\\", "Rule", "(", "$", "this", "->", "entity", ",", "function", "(", ")", "{", "return", "false", ";", "}", ",", "$", "message", ",", "$", "this", "->", "property", ",", "$", "severity", ",", "$", "this", "->", "child", ")", ";", "$", "rule", "->", "setChildFailed", "(", "$", "indexes", ")", ";", "$", "this", "->", "rules", "[", "]", "=", "$", "rule", ";", "return", "$", "this", ";", "}" ]
Add permanent error manually @param string $message @param integer $severity @param array $indexes Failed indexes, has effect on collections only @return \UniMapper\Validator
[ "Add", "permanent", "error", "manually" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Validator.php#L98-L114
13,304
unimapper/unimapper
src/Validator.php
Validator.on
public function on($name, $child = null) { $reflection = $this->entity->getReflection(); if (!$reflection->hasProperty($name)) { throw new Exception\InvalidArgumentException( "Unknown property '" . $name . "'!" ); } $this->property = $reflection->getProperty($name); if ($this->property->hasOption(Computed::KEY)) { throw new Exception\InvalidArgumentException( "Validation can not be used on computed property!" ); } if ($child && (!$this->property->getType() === Entity\Reflection\Property::TYPE_ENTITY && !$this->property->getType() === Entity\Reflection\Property::TYPE_COLLECTION) ) { throw new Exception\InvalidArgumentException( "Child validation can be used only on entities and collections!" ); } $this->child = $child; return $this->endCondition(); }
php
public function on($name, $child = null) { $reflection = $this->entity->getReflection(); if (!$reflection->hasProperty($name)) { throw new Exception\InvalidArgumentException( "Unknown property '" . $name . "'!" ); } $this->property = $reflection->getProperty($name); if ($this->property->hasOption(Computed::KEY)) { throw new Exception\InvalidArgumentException( "Validation can not be used on computed property!" ); } if ($child && (!$this->property->getType() === Entity\Reflection\Property::TYPE_ENTITY && !$this->property->getType() === Entity\Reflection\Property::TYPE_COLLECTION) ) { throw new Exception\InvalidArgumentException( "Child validation can be used only on entities and collections!" ); } $this->child = $child; return $this->endCondition(); }
[ "public", "function", "on", "(", "$", "name", ",", "$", "child", "=", "null", ")", "{", "$", "reflection", "=", "$", "this", "->", "entity", "->", "getReflection", "(", ")", ";", "if", "(", "!", "$", "reflection", "->", "hasProperty", "(", "$", "name", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "\"Unknown property '\"", ".", "$", "name", ".", "\"'!\"", ")", ";", "}", "$", "this", "->", "property", "=", "$", "reflection", "->", "getProperty", "(", "$", "name", ")", ";", "if", "(", "$", "this", "->", "property", "->", "hasOption", "(", "Computed", "::", "KEY", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "\"Validation can not be used on computed property!\"", ")", ";", "}", "if", "(", "$", "child", "&&", "(", "!", "$", "this", "->", "property", "->", "getType", "(", ")", "===", "Entity", "\\", "Reflection", "\\", "Property", "::", "TYPE_ENTITY", "&&", "!", "$", "this", "->", "property", "->", "getType", "(", ")", "===", "Entity", "\\", "Reflection", "\\", "Property", "::", "TYPE_COLLECTION", ")", ")", "{", "throw", "new", "Exception", "\\", "InvalidArgumentException", "(", "\"Child validation can be used only on entities and collections!\"", ")", ";", "}", "$", "this", "->", "child", "=", "$", "child", ";", "return", "$", "this", "->", "endCondition", "(", ")", ";", "}" ]
Set property which is validation configured on @param string $name Property name in entity @param string $child Child property name @return \UniMapper\Validator @throws \Exception
[ "Set", "property", "which", "is", "validation", "configured", "on" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Validator.php#L126-L153
13,305
unimapper/unimapper
src/Validator.php
Validator.addRule
public function addRule($validation, $message, $severity = Validator\Rule::ERROR) { $this->rules[] = new Validator\Rule( $this->entity, $this->_getValidation($validation), $message, $this->property, $severity, $this->child ); return $this; }
php
public function addRule($validation, $message, $severity = Validator\Rule::ERROR) { $this->rules[] = new Validator\Rule( $this->entity, $this->_getValidation($validation), $message, $this->property, $severity, $this->child ); return $this; }
[ "public", "function", "addRule", "(", "$", "validation", ",", "$", "message", ",", "$", "severity", "=", "Validator", "\\", "Rule", "::", "ERROR", ")", "{", "$", "this", "->", "rules", "[", "]", "=", "new", "Validator", "\\", "Rule", "(", "$", "this", "->", "entity", ",", "$", "this", "->", "_getValidation", "(", "$", "validation", ")", ",", "$", "message", ",", "$", "this", "->", "property", ",", "$", "severity", ",", "$", "this", "->", "child", ")", ";", "return", "$", "this", ";", "}" ]
Addd validation rule @param mixed $validation Callable or some default validation method name @param string $message @param integer $severity @return \UniMapper\Validator
[ "Addd", "validation", "rule" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Validator.php#L176-L187
13,306
unimapper/unimapper
src/Validator.php
Validator.validate
public function validate($failOn = Validator\Rule::ERROR) { $this->warnings = []; $this->errors = []; foreach ($this->rules as $rule) { if ($rule instanceof Validator\Condition) { // Condition $condition = $rule; if ($condition->validate()) { // Conditions rules if (!$condition->getValidator()->validate($failOn)) { $this->errors = array_merge( $this->errors, $rule->getValidator()->getErrors() ); } $this->warnings = array_merge( $this->warnings, $rule->getValidator()->getWarnings() ); } } else { // Rule if (!$rule->validate()) { if ($rule->getSeverity() <= $failOn) { $this->errors[] = $rule; } else { $this->warnings[] = $rule; } } } } // Run nested validators - every entity may have its own validator foreach ($this->entity->getData() as $propertyName => $value) { if ($value instanceof Entity) { $validator = $value->getValidator(); if (!$validator->validate($failOn)) { foreach ($validator->getErrors() as $error) { $rule = clone $error; $rule->setPath( array_merge([$propertyName], $rule->getPath()) ); $this->errors[] = $rule; } } foreach ($validator->getWarnings() as $warning) { $rule = clone $warning; $rule->setPath( array_merge([$propertyName], $rule->getPath()) ); $this->warnings[] = $rule; } } } return count($this->errors) === 0; }
php
public function validate($failOn = Validator\Rule::ERROR) { $this->warnings = []; $this->errors = []; foreach ($this->rules as $rule) { if ($rule instanceof Validator\Condition) { // Condition $condition = $rule; if ($condition->validate()) { // Conditions rules if (!$condition->getValidator()->validate($failOn)) { $this->errors = array_merge( $this->errors, $rule->getValidator()->getErrors() ); } $this->warnings = array_merge( $this->warnings, $rule->getValidator()->getWarnings() ); } } else { // Rule if (!$rule->validate()) { if ($rule->getSeverity() <= $failOn) { $this->errors[] = $rule; } else { $this->warnings[] = $rule; } } } } // Run nested validators - every entity may have its own validator foreach ($this->entity->getData() as $propertyName => $value) { if ($value instanceof Entity) { $validator = $value->getValidator(); if (!$validator->validate($failOn)) { foreach ($validator->getErrors() as $error) { $rule = clone $error; $rule->setPath( array_merge([$propertyName], $rule->getPath()) ); $this->errors[] = $rule; } } foreach ($validator->getWarnings() as $warning) { $rule = clone $warning; $rule->setPath( array_merge([$propertyName], $rule->getPath()) ); $this->warnings[] = $rule; } } } return count($this->errors) === 0; }
[ "public", "function", "validate", "(", "$", "failOn", "=", "Validator", "\\", "Rule", "::", "ERROR", ")", "{", "$", "this", "->", "warnings", "=", "[", "]", ";", "$", "this", "->", "errors", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "rules", "as", "$", "rule", ")", "{", "if", "(", "$", "rule", "instanceof", "Validator", "\\", "Condition", ")", "{", "// Condition", "$", "condition", "=", "$", "rule", ";", "if", "(", "$", "condition", "->", "validate", "(", ")", ")", "{", "// Conditions rules", "if", "(", "!", "$", "condition", "->", "getValidator", "(", ")", "->", "validate", "(", "$", "failOn", ")", ")", "{", "$", "this", "->", "errors", "=", "array_merge", "(", "$", "this", "->", "errors", ",", "$", "rule", "->", "getValidator", "(", ")", "->", "getErrors", "(", ")", ")", ";", "}", "$", "this", "->", "warnings", "=", "array_merge", "(", "$", "this", "->", "warnings", ",", "$", "rule", "->", "getValidator", "(", ")", "->", "getWarnings", "(", ")", ")", ";", "}", "}", "else", "{", "// Rule", "if", "(", "!", "$", "rule", "->", "validate", "(", ")", ")", "{", "if", "(", "$", "rule", "->", "getSeverity", "(", ")", "<=", "$", "failOn", ")", "{", "$", "this", "->", "errors", "[", "]", "=", "$", "rule", ";", "}", "else", "{", "$", "this", "->", "warnings", "[", "]", "=", "$", "rule", ";", "}", "}", "}", "}", "// Run nested validators - every entity may have its own validator", "foreach", "(", "$", "this", "->", "entity", "->", "getData", "(", ")", "as", "$", "propertyName", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "Entity", ")", "{", "$", "validator", "=", "$", "value", "->", "getValidator", "(", ")", ";", "if", "(", "!", "$", "validator", "->", "validate", "(", "$", "failOn", ")", ")", "{", "foreach", "(", "$", "validator", "->", "getErrors", "(", ")", "as", "$", "error", ")", "{", "$", "rule", "=", "clone", "$", "error", ";", "$", "rule", "->", "setPath", "(", "array_merge", "(", "[", "$", "propertyName", "]", ",", "$", "rule", "->", "getPath", "(", ")", ")", ")", ";", "$", "this", "->", "errors", "[", "]", "=", "$", "rule", ";", "}", "}", "foreach", "(", "$", "validator", "->", "getWarnings", "(", ")", "as", "$", "warning", ")", "{", "$", "rule", "=", "clone", "$", "warning", ";", "$", "rule", "->", "setPath", "(", "array_merge", "(", "[", "$", "propertyName", "]", ",", "$", "rule", "->", "getPath", "(", ")", ")", ")", ";", "$", "this", "->", "warnings", "[", "]", "=", "$", "rule", ";", "}", "}", "}", "return", "count", "(", "$", "this", "->", "errors", ")", "===", "0", ";", "}" ]
Run all validations @param integer $failOn Severity level @return boolean
[ "Run", "all", "validations" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Validator.php#L204-L275
13,307
jfusion/org.jfusion.platform.joomla
src/Recaptcha/Captcha/Captcha.php
Captcha.html
public function html() { if (!$this->getPublicKey()) { throw new Exception('You must set public key provided by reCaptcha'); } $error = ($this->getError() ? '&amp;error=' . $this->getError() : null); $theme = null; // If user specified a reCaptcha theme, output it as one of the options if ($this->theme) { $theme = '<script> var RecaptchaOptions = {theme: "' . $this->theme . '"};</script>'; } return $theme . '<script type="text/javascript" src="' . self::SERVER . '/challenge?k=' . $this->getPublicKey() . $error . '"></script> <noscript> <iframe src="' . self::SERVER . '/noscript?k=' . $this->getPublicKey() . $error . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; }
php
public function html() { if (!$this->getPublicKey()) { throw new Exception('You must set public key provided by reCaptcha'); } $error = ($this->getError() ? '&amp;error=' . $this->getError() : null); $theme = null; // If user specified a reCaptcha theme, output it as one of the options if ($this->theme) { $theme = '<script> var RecaptchaOptions = {theme: "' . $this->theme . '"};</script>'; } return $theme . '<script type="text/javascript" src="' . self::SERVER . '/challenge?k=' . $this->getPublicKey() . $error . '"></script> <noscript> <iframe src="' . self::SERVER . '/noscript?k=' . $this->getPublicKey() . $error . '" height="300" width="500" frameborder="0"></iframe><br/> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"/> </noscript>'; }
[ "public", "function", "html", "(", ")", "{", "if", "(", "!", "$", "this", "->", "getPublicKey", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'You must set public key provided by reCaptcha'", ")", ";", "}", "$", "error", "=", "(", "$", "this", "->", "getError", "(", ")", "?", "'&amp;error='", ".", "$", "this", "->", "getError", "(", ")", ":", "null", ")", ";", "$", "theme", "=", "null", ";", "// If user specified a reCaptcha theme, output it as one of the options", "if", "(", "$", "this", "->", "theme", ")", "{", "$", "theme", "=", "'<script> var RecaptchaOptions = {theme: \"'", ".", "$", "this", "->", "theme", ".", "'\"};</script>'", ";", "}", "return", "$", "theme", ".", "'<script type=\"text/javascript\" src=\"'", ".", "self", "::", "SERVER", ".", "'/challenge?k='", ".", "$", "this", "->", "getPublicKey", "(", ")", ".", "$", "error", ".", "'\"></script>\n\n <noscript>\n <iframe src=\"'", ".", "self", "::", "SERVER", ".", "'/noscript?k='", ".", "$", "this", "->", "getPublicKey", "(", ")", ".", "$", "error", ".", "'\" height=\"300\" width=\"500\" frameborder=\"0\"></iframe><br/>\n <textarea name=\"recaptcha_challenge_field\" rows=\"3\" cols=\"40\"></textarea>\n <input type=\"hidden\" name=\"recaptcha_response_field\" value=\"manual_challenge\"/>\n </noscript>'", ";", "}" ]
Generates reCaptcha form to output to your end user @throws Exception @return string
[ "Generates", "reCaptcha", "form", "to", "output", "to", "your", "end", "user" ]
1f0591321909720e218b6381c41546685e999e13
https://github.com/jfusion/org.jfusion.platform.joomla/blob/1f0591321909720e218b6381c41546685e999e13/src/Recaptcha/Captcha/Captcha.php#L204-L226
13,308
jfusion/org.jfusion.platform.joomla
src/Recaptcha/Captcha/Captcha.php
Captcha.check
public function check($captcha_challenge = false, $captcha_response = false) { if (!$this->getPrivateKey()) { throw new Exception('You must set private key provided by reCaptcha'); } // Skip processing of empty data if (!$captcha_challenge && !$captcha_response) { if (isset($_POST['recaptcha_challenge_field']) && isset($_POST['recaptcha_response_field'])) { $captcha_challenge = $_POST['recaptcha_challenge_field']; $captcha_response = $_POST['recaptcha_response_field']; } } // Instance of response object $response = new Response(); // Discard SPAM submissions if (strlen($captcha_challenge) == 0 || strlen($captcha_response) == 0) { $response->setValid(false); $response->setError('Incorrect-captcha-sol'); return $response; } $process = $this->process( array( 'privatekey' => $this->getPrivateKey(), 'remoteip' => $this->getRemoteIp(), 'challenge' => $captcha_challenge, 'response' => $captcha_response ) ); $answers = explode("\n", $process [1]); if (trim($answers[0]) == 'true') { $response->setValid(true); } else { $response->setValid(false); $response->setError($answers[1]); } return $response; }
php
public function check($captcha_challenge = false, $captcha_response = false) { if (!$this->getPrivateKey()) { throw new Exception('You must set private key provided by reCaptcha'); } // Skip processing of empty data if (!$captcha_challenge && !$captcha_response) { if (isset($_POST['recaptcha_challenge_field']) && isset($_POST['recaptcha_response_field'])) { $captcha_challenge = $_POST['recaptcha_challenge_field']; $captcha_response = $_POST['recaptcha_response_field']; } } // Instance of response object $response = new Response(); // Discard SPAM submissions if (strlen($captcha_challenge) == 0 || strlen($captcha_response) == 0) { $response->setValid(false); $response->setError('Incorrect-captcha-sol'); return $response; } $process = $this->process( array( 'privatekey' => $this->getPrivateKey(), 'remoteip' => $this->getRemoteIp(), 'challenge' => $captcha_challenge, 'response' => $captcha_response ) ); $answers = explode("\n", $process [1]); if (trim($answers[0]) == 'true') { $response->setValid(true); } else { $response->setValid(false); $response->setError($answers[1]); } return $response; }
[ "public", "function", "check", "(", "$", "captcha_challenge", "=", "false", ",", "$", "captcha_response", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "getPrivateKey", "(", ")", ")", "{", "throw", "new", "Exception", "(", "'You must set private key provided by reCaptcha'", ")", ";", "}", "// Skip processing of empty data", "if", "(", "!", "$", "captcha_challenge", "&&", "!", "$", "captcha_response", ")", "{", "if", "(", "isset", "(", "$", "_POST", "[", "'recaptcha_challenge_field'", "]", ")", "&&", "isset", "(", "$", "_POST", "[", "'recaptcha_response_field'", "]", ")", ")", "{", "$", "captcha_challenge", "=", "$", "_POST", "[", "'recaptcha_challenge_field'", "]", ";", "$", "captcha_response", "=", "$", "_POST", "[", "'recaptcha_response_field'", "]", ";", "}", "}", "// Instance of response object", "$", "response", "=", "new", "Response", "(", ")", ";", "// Discard SPAM submissions", "if", "(", "strlen", "(", "$", "captcha_challenge", ")", "==", "0", "||", "strlen", "(", "$", "captcha_response", ")", "==", "0", ")", "{", "$", "response", "->", "setValid", "(", "false", ")", ";", "$", "response", "->", "setError", "(", "'Incorrect-captcha-sol'", ")", ";", "return", "$", "response", ";", "}", "$", "process", "=", "$", "this", "->", "process", "(", "array", "(", "'privatekey'", "=>", "$", "this", "->", "getPrivateKey", "(", ")", ",", "'remoteip'", "=>", "$", "this", "->", "getRemoteIp", "(", ")", ",", "'challenge'", "=>", "$", "captcha_challenge", ",", "'response'", "=>", "$", "captcha_response", ")", ")", ";", "$", "answers", "=", "explode", "(", "\"\\n\"", ",", "$", "process", "[", "1", "]", ")", ";", "if", "(", "trim", "(", "$", "answers", "[", "0", "]", ")", "==", "'true'", ")", "{", "$", "response", "->", "setValid", "(", "true", ")", ";", "}", "else", "{", "$", "response", "->", "setValid", "(", "false", ")", ";", "$", "response", "->", "setError", "(", "$", "answers", "[", "1", "]", ")", ";", "}", "return", "$", "response", ";", "}" ]
Checks and validates user's response @param bool|string $captcha_challenge Optional challenge string. If empty, value from $_POST will be used @param bool|string $captcha_response Optional response string. If empty, value from $_POST will be used @throws Exception @return Response
[ "Checks", "and", "validates", "user", "s", "response" ]
1f0591321909720e218b6381c41546685e999e13
https://github.com/jfusion/org.jfusion.platform.joomla/blob/1f0591321909720e218b6381c41546685e999e13/src/Recaptcha/Captcha/Captcha.php#L236-L278
13,309
jfusion/org.jfusion.platform.joomla
src/Recaptcha/Captcha/Captcha.php
Captcha.process
protected function process($parameters) { // Properly encode parameters $parameters = $this->encode($parameters); $request = "POST /recaptcha/api/verify HTTP/1.0\r\n"; $request .= "Host: " . self::VERIFY_SERVER . "\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $request .= "Content-Length: " . strlen($parameters) . "\r\n"; $request .= "User-Agent: reCAPTCHA/PHP5\r\n"; $request .= "\r\n"; $request .= $parameters; if (false == ($socket = @fsockopen(self::VERIFY_SERVER, 80))) { throw new Exception('Could not open socket to: ' . self::VERIFY_SERVER); } fwrite($socket, $request); $response = ''; while (!feof($socket) ) { $response .= fgets($socket, 1160); } fclose($socket); return explode("\r\n\r\n", $response, 2); }
php
protected function process($parameters) { // Properly encode parameters $parameters = $this->encode($parameters); $request = "POST /recaptcha/api/verify HTTP/1.0\r\n"; $request .= "Host: " . self::VERIFY_SERVER . "\r\n"; $request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $request .= "Content-Length: " . strlen($parameters) . "\r\n"; $request .= "User-Agent: reCAPTCHA/PHP5\r\n"; $request .= "\r\n"; $request .= $parameters; if (false == ($socket = @fsockopen(self::VERIFY_SERVER, 80))) { throw new Exception('Could not open socket to: ' . self::VERIFY_SERVER); } fwrite($socket, $request); $response = ''; while (!feof($socket) ) { $response .= fgets($socket, 1160); } fclose($socket); return explode("\r\n\r\n", $response, 2); }
[ "protected", "function", "process", "(", "$", "parameters", ")", "{", "// Properly encode parameters", "$", "parameters", "=", "$", "this", "->", "encode", "(", "$", "parameters", ")", ";", "$", "request", "=", "\"POST /recaptcha/api/verify HTTP/1.0\\r\\n\"", ";", "$", "request", ".=", "\"Host: \"", ".", "self", "::", "VERIFY_SERVER", ".", "\"\\r\\n\"", ";", "$", "request", ".=", "\"Content-Type: application/x-www-form-urlencoded;\\r\\n\"", ";", "$", "request", ".=", "\"Content-Length: \"", ".", "strlen", "(", "$", "parameters", ")", ".", "\"\\r\\n\"", ";", "$", "request", ".=", "\"User-Agent: reCAPTCHA/PHP5\\r\\n\"", ";", "$", "request", ".=", "\"\\r\\n\"", ";", "$", "request", ".=", "$", "parameters", ";", "if", "(", "false", "==", "(", "$", "socket", "=", "@", "fsockopen", "(", "self", "::", "VERIFY_SERVER", ",", "80", ")", ")", ")", "{", "throw", "new", "Exception", "(", "'Could not open socket to: '", ".", "self", "::", "VERIFY_SERVER", ")", ";", "}", "fwrite", "(", "$", "socket", ",", "$", "request", ")", ";", "$", "response", "=", "''", ";", "while", "(", "!", "feof", "(", "$", "socket", ")", ")", "{", "$", "response", ".=", "fgets", "(", "$", "socket", ",", "1160", ")", ";", "}", "fclose", "(", "$", "socket", ")", ";", "return", "explode", "(", "\"\\r\\n\\r\\n\"", ",", "$", "response", ",", "2", ")", ";", "}" ]
Make a signed validation request to reCaptcha's servers @throws Exception @param array $parameters @return string
[ "Make", "a", "signed", "validation", "request", "to", "reCaptcha", "s", "servers" ]
1f0591321909720e218b6381c41546685e999e13
https://github.com/jfusion/org.jfusion.platform.joomla/blob/1f0591321909720e218b6381c41546685e999e13/src/Recaptcha/Captcha/Captcha.php#L287-L315
13,310
jfusion/org.jfusion.platform.joomla
src/Recaptcha/Captcha/Captcha.php
Captcha.encode
protected function encode(array $parameters) { $uri = ''; if ($parameters) { foreach ($parameters as $parameter => $value) { $uri .= $parameter . '=' . urlencode(stripslashes($value)) . '&'; } } $uri = substr($uri, 0, strlen($uri)-1); return $uri; }
php
protected function encode(array $parameters) { $uri = ''; if ($parameters) { foreach ($parameters as $parameter => $value) { $uri .= $parameter . '=' . urlencode(stripslashes($value)) . '&'; } } $uri = substr($uri, 0, strlen($uri)-1); return $uri; }
[ "protected", "function", "encode", "(", "array", "$", "parameters", ")", "{", "$", "uri", "=", "''", ";", "if", "(", "$", "parameters", ")", "{", "foreach", "(", "$", "parameters", "as", "$", "parameter", "=>", "$", "value", ")", "{", "$", "uri", ".=", "$", "parameter", ".", "'='", ".", "urlencode", "(", "stripslashes", "(", "$", "value", ")", ")", ".", "'&'", ";", "}", "}", "$", "uri", "=", "substr", "(", "$", "uri", ",", "0", ",", "strlen", "(", "$", "uri", ")", "-", "1", ")", ";", "return", "$", "uri", ";", "}" ]
Construct encoded URI string from an array @param array $parameters @return string
[ "Construct", "encoded", "URI", "string", "from", "an", "array" ]
1f0591321909720e218b6381c41546685e999e13
https://github.com/jfusion/org.jfusion.platform.joomla/blob/1f0591321909720e218b6381c41546685e999e13/src/Recaptcha/Captcha/Captcha.php#L323-L336
13,311
jfusion/org.jfusion.platform.joomla
src/Recaptcha/Captcha/Captcha.php
Captcha.setTheme
public function setTheme($theme) { if (!self::isValidTheme($theme)) { throw new Exception( 'Theme ' . $theme . ' is not valid. Please use one of [' . join(', ', self::$themes) . ']' ); } $this->theme = $theme; }
php
public function setTheme($theme) { if (!self::isValidTheme($theme)) { throw new Exception( 'Theme ' . $theme . ' is not valid. Please use one of [' . join(', ', self::$themes) . ']' ); } $this->theme = $theme; }
[ "public", "function", "setTheme", "(", "$", "theme", ")", "{", "if", "(", "!", "self", "::", "isValidTheme", "(", "$", "theme", ")", ")", "{", "throw", "new", "Exception", "(", "'Theme '", ".", "$", "theme", ".", "' is not valid. Please use one of ['", ".", "join", "(", "', '", ",", "self", "::", "$", "themes", ")", ".", "']'", ")", ";", "}", "$", "this", "->", "theme", "=", "$", "theme", ";", "}" ]
Set a reCaptcha theme @param string $theme @throws Exception @see https://developers.google.com/recaptcha/docs/customization
[ "Set", "a", "reCaptcha", "theme" ]
1f0591321909720e218b6381c41546685e999e13
https://github.com/jfusion/org.jfusion.platform.joomla/blob/1f0591321909720e218b6381c41546685e999e13/src/Recaptcha/Captcha/Captcha.php#L356-L365
13,312
cicada/cicada
src/Invoker.php
Invoker.invoke
public function invoke($callable, array $namedParams = [], array $classParams = []) { $classParams = $this->reindexclassParams($classParams); if ($callable instanceof \Closure) { return $this->invokeFunction($callable, $namedParams, $classParams); } if (is_string($callable)) { if (strpos($callable, '::') !== false) { list($class, $method) = explode('::', $callable); return $this->invokeClassMethod($class, $method, $namedParams, $classParams); } else { return $this->invokeFunction($callable, $namedParams, $classParams); } } if (is_array($callable) && count($callable) == 2 && is_string($callable[1])) { if (is_object($callable[0])) { return $this->invokeObjectMethod($callable[0], $callable[1], $namedParams, $classParams); } if (is_string($callable[0])) { return $this->invokeClassMethod($callable[0], $callable[1], $namedParams, $classParams); } } throw new \InvalidArgumentException("Given argument is not callable."); }
php
public function invoke($callable, array $namedParams = [], array $classParams = []) { $classParams = $this->reindexclassParams($classParams); if ($callable instanceof \Closure) { return $this->invokeFunction($callable, $namedParams, $classParams); } if (is_string($callable)) { if (strpos($callable, '::') !== false) { list($class, $method) = explode('::', $callable); return $this->invokeClassMethod($class, $method, $namedParams, $classParams); } else { return $this->invokeFunction($callable, $namedParams, $classParams); } } if (is_array($callable) && count($callable) == 2 && is_string($callable[1])) { if (is_object($callable[0])) { return $this->invokeObjectMethod($callable[0], $callable[1], $namedParams, $classParams); } if (is_string($callable[0])) { return $this->invokeClassMethod($callable[0], $callable[1], $namedParams, $classParams); } } throw new \InvalidArgumentException("Given argument is not callable."); }
[ "public", "function", "invoke", "(", "$", "callable", ",", "array", "$", "namedParams", "=", "[", "]", ",", "array", "$", "classParams", "=", "[", "]", ")", "{", "$", "classParams", "=", "$", "this", "->", "reindexclassParams", "(", "$", "classParams", ")", ";", "if", "(", "$", "callable", "instanceof", "\\", "Closure", ")", "{", "return", "$", "this", "->", "invokeFunction", "(", "$", "callable", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}", "if", "(", "is_string", "(", "$", "callable", ")", ")", "{", "if", "(", "strpos", "(", "$", "callable", ",", "'::'", ")", "!==", "false", ")", "{", "list", "(", "$", "class", ",", "$", "method", ")", "=", "explode", "(", "'::'", ",", "$", "callable", ")", ";", "return", "$", "this", "->", "invokeClassMethod", "(", "$", "class", ",", "$", "method", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}", "else", "{", "return", "$", "this", "->", "invokeFunction", "(", "$", "callable", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}", "}", "if", "(", "is_array", "(", "$", "callable", ")", "&&", "count", "(", "$", "callable", ")", "==", "2", "&&", "is_string", "(", "$", "callable", "[", "1", "]", ")", ")", "{", "if", "(", "is_object", "(", "$", "callable", "[", "0", "]", ")", ")", "{", "return", "$", "this", "->", "invokeObjectMethod", "(", "$", "callable", "[", "0", "]", ",", "$", "callable", "[", "1", "]", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}", "if", "(", "is_string", "(", "$", "callable", "[", "0", "]", ")", ")", "{", "return", "$", "this", "->", "invokeClassMethod", "(", "$", "callable", "[", "0", "]", ",", "$", "callable", "[", "1", "]", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Given argument is not callable.\"", ")", ";", "}" ]
Invokes a method or anonymous function and returns the result. Parameter injection is done in two ways: 1. `$classParams` array may contain only objects. For each of the objects in the array, if the callable function has a parameter with a type hing to that class, it will be injected. For example, in the following case $req will be populated by the Request from `$classParams`: ``` $classParams = [new Request]; $callable = new function(Request $req) { }; $invoker->invoke($callable, [], $classParams); ``` 2. `$namedParams` may contain an associative array containing named parameters. If the callable function has a parameter of the same name as one of the given parameters, it's value will be injected. For example: ``` $namedParams = [ 'foo' => 1, 'bar' => 2 ]; $callable = new function($bar, $foo) { }; $invoker->invoke($callable, $namedParams); ``` In the above example $foo and $bar will be injected from the $namedParams. Note that the order of parameters in the callback function is not significant. If `$namedParams` or `$classParams` contain entries which are not matched to any parameter of the callback function, they will be ignored. If the callback function conatins any parameter which is not matched from `$namedParams` or `$classParams`, it will be set to NULL. @param string|callable $callable @param array $namedParams Parameters matched by name. @param array $classParams Parameters matched by class type hint. @return mixed The return value of the given callback function. @throws \InvalidArgumentException when the callable isn't callable @throws \InvalidArgumentException If `$classParams` contains non-objects. @throws \InvalidArgumentException If `$classParams` contains multiple objects of the same class.
[ "Invokes", "a", "method", "or", "anonymous", "function", "and", "returns", "the", "result", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Invoker.php#L75-L103
13,313
cicada/cicada
src/Invoker.php
Invoker.invokeClassMethod
private function invokeClassMethod($class, $method, $namedParams, $classParams) { if (!class_exists($class)) { throw new \InvalidArgumentException("Class $class does not exist."); } $object = new $class(); return $this->invokeObjectMethod($object, $method, $namedParams, $classParams); }
php
private function invokeClassMethod($class, $method, $namedParams, $classParams) { if (!class_exists($class)) { throw new \InvalidArgumentException("Class $class does not exist."); } $object = new $class(); return $this->invokeObjectMethod($object, $method, $namedParams, $classParams); }
[ "private", "function", "invokeClassMethod", "(", "$", "class", ",", "$", "method", ",", "$", "namedParams", ",", "$", "classParams", ")", "{", "if", "(", "!", "class_exists", "(", "$", "class", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Class $class does not exist.\"", ")", ";", "}", "$", "object", "=", "new", "$", "class", "(", ")", ";", "return", "$", "this", "->", "invokeObjectMethod", "(", "$", "object", ",", "$", "method", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "}" ]
Invokes a method on a class, by creating an instance of the class and then invoking the method.
[ "Invokes", "a", "method", "on", "a", "class", "by", "creating", "an", "instance", "of", "the", "class", "and", "then", "invoking", "the", "method", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Invoker.php#L109-L118
13,314
cicada/cicada
src/Invoker.php
Invoker.invokeObjectMethod
private function invokeObjectMethod($object, $method, $namedParams, $classParams) { if (!method_exists($object, $method)) { $class = get_class($object); throw new \InvalidArgumentException("Method $class::$method does not exist."); } $reflection = new \ReflectionMethod($object, $method); $params = $reflection->getParameters(); $invokeParams = $this->mapParameters($params, $namedParams, $classParams); return call_user_func_array([$object, $method], $invokeParams); }
php
private function invokeObjectMethod($object, $method, $namedParams, $classParams) { if (!method_exists($object, $method)) { $class = get_class($object); throw new \InvalidArgumentException("Method $class::$method does not exist."); } $reflection = new \ReflectionMethod($object, $method); $params = $reflection->getParameters(); $invokeParams = $this->mapParameters($params, $namedParams, $classParams); return call_user_func_array([$object, $method], $invokeParams); }
[ "private", "function", "invokeObjectMethod", "(", "$", "object", ",", "$", "method", ",", "$", "namedParams", ",", "$", "classParams", ")", "{", "if", "(", "!", "method_exists", "(", "$", "object", ",", "$", "method", ")", ")", "{", "$", "class", "=", "get_class", "(", "$", "object", ")", ";", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Method $class::$method does not exist.\"", ")", ";", "}", "$", "reflection", "=", "new", "\\", "ReflectionMethod", "(", "$", "object", ",", "$", "method", ")", ";", "$", "params", "=", "$", "reflection", "->", "getParameters", "(", ")", ";", "$", "invokeParams", "=", "$", "this", "->", "mapParameters", "(", "$", "params", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "return", "call_user_func_array", "(", "[", "$", "object", ",", "$", "method", "]", ",", "$", "invokeParams", ")", ";", "}" ]
Invokes a method on an object.
[ "Invokes", "a", "method", "on", "an", "object", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Invoker.php#L123-L136
13,315
cicada/cicada
src/Invoker.php
Invoker.invokeFunction
private function invokeFunction($function, $namedParams, $classParams) { $reflection = new \ReflectionFunction($function); $params = $reflection->getParameters(); $invokeParams = $this->mapParameters($params, $namedParams, $classParams); return call_user_func_array($function, $invokeParams); }
php
private function invokeFunction($function, $namedParams, $classParams) { $reflection = new \ReflectionFunction($function); $params = $reflection->getParameters(); $invokeParams = $this->mapParameters($params, $namedParams, $classParams); return call_user_func_array($function, $invokeParams); }
[ "private", "function", "invokeFunction", "(", "$", "function", ",", "$", "namedParams", ",", "$", "classParams", ")", "{", "$", "reflection", "=", "new", "\\", "ReflectionFunction", "(", "$", "function", ")", ";", "$", "params", "=", "$", "reflection", "->", "getParameters", "(", ")", ";", "$", "invokeParams", "=", "$", "this", "->", "mapParameters", "(", "$", "params", ",", "$", "namedParams", ",", "$", "classParams", ")", ";", "return", "call_user_func_array", "(", "$", "function", ",", "$", "invokeParams", ")", ";", "}" ]
Invokes an anonymous function.
[ "Invokes", "an", "anonymous", "function", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Invoker.php#L139-L147
13,316
cicada/cicada
src/Invoker.php
Invoker.reindexClassParams
private function reindexClassParams(array $classParams) { $reindexed = []; foreach ($classParams as $param) { if (!is_object($param)) { throw new \InvalidArgumentException("\$classParams entries must be objects."); } // Iterate for param class and all parent classes. This way you can // inject subclasses as well as the specified class for ($class = get_class($param); $class !== false; $class = get_parent_class($class)) { if (isset($reindexed[$class])) { throw new \InvalidArgumentException("\$classParams contains multiple objects of the same class [$class]."); } $reindexed[$class] = $param; } } return $reindexed; }
php
private function reindexClassParams(array $classParams) { $reindexed = []; foreach ($classParams as $param) { if (!is_object($param)) { throw new \InvalidArgumentException("\$classParams entries must be objects."); } // Iterate for param class and all parent classes. This way you can // inject subclasses as well as the specified class for ($class = get_class($param); $class !== false; $class = get_parent_class($class)) { if (isset($reindexed[$class])) { throw new \InvalidArgumentException("\$classParams contains multiple objects of the same class [$class]."); } $reindexed[$class] = $param; } } return $reindexed; }
[ "private", "function", "reindexClassParams", "(", "array", "$", "classParams", ")", "{", "$", "reindexed", "=", "[", "]", ";", "foreach", "(", "$", "classParams", "as", "$", "param", ")", "{", "if", "(", "!", "is_object", "(", "$", "param", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"\\$classParams entries must be objects.\"", ")", ";", "}", "// Iterate for param class and all parent classes. This way you can", "// inject subclasses as well as the specified class", "for", "(", "$", "class", "=", "get_class", "(", "$", "param", ")", ";", "$", "class", "!==", "false", ";", "$", "class", "=", "get_parent_class", "(", "$", "class", ")", ")", "{", "if", "(", "isset", "(", "$", "reindexed", "[", "$", "class", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"\\$classParams contains multiple objects of the same class [$class].\"", ")", ";", "}", "$", "reindexed", "[", "$", "class", "]", "=", "$", "param", ";", "}", "}", "return", "$", "reindexed", ";", "}" ]
Reindexes an array of objects by class name.
[ "Reindexes", "an", "array", "of", "objects", "by", "class", "name", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Invoker.php#L172-L193
13,317
gorkalaucirica/HipchatAPIv2Client
Model/Message.php
Message.toJson
public function toJson() { $json = array(); $json['id'] = $this->id; $json['from'] = $this->from; $json['color'] = $this->color; $json['message'] = $this->message; $json['notify'] = $this->notify; $json['message_format'] = $this->messageFormat; $json['date'] = $this->date; return $json; }
php
public function toJson() { $json = array(); $json['id'] = $this->id; $json['from'] = $this->from; $json['color'] = $this->color; $json['message'] = $this->message; $json['notify'] = $this->notify; $json['message_format'] = $this->messageFormat; $json['date'] = $this->date; return $json; }
[ "public", "function", "toJson", "(", ")", "{", "$", "json", "=", "array", "(", ")", ";", "$", "json", "[", "'id'", "]", "=", "$", "this", "->", "id", ";", "$", "json", "[", "'from'", "]", "=", "$", "this", "->", "from", ";", "$", "json", "[", "'color'", "]", "=", "$", "this", "->", "color", ";", "$", "json", "[", "'message'", "]", "=", "$", "this", "->", "message", ";", "$", "json", "[", "'notify'", "]", "=", "$", "this", "->", "notify", ";", "$", "json", "[", "'message_format'", "]", "=", "$", "this", "->", "messageFormat", ";", "$", "json", "[", "'date'", "]", "=", "$", "this", "->", "date", ";", "return", "$", "json", ";", "}" ]
Serializes Message object @return array
[ "Serializes", "Message", "object" ]
eef9c91d5efe5ae9cad27c503601ffff089c9547
https://github.com/gorkalaucirica/HipchatAPIv2Client/blob/eef9c91d5efe5ae9cad27c503601ffff089c9547/Model/Message.php#L65-L78
13,318
markwatkinson/luminous
src/Luminous/Scanners/EcmaScriptScanner.php
EcmaScriptScanner.scanChild
public function scanChild($lang) { assert(isset($this->childScanners[$lang])); $scanner = $this->childScanners[$lang]; $scanner->pos($this->pos()); $substr = $scanner->main(); $this->record($scanner->tagged(), 'XML', true); $this->pos($scanner->pos()); if ($scanner->interrupt) { $this->childState = array($lang, $this->pos()); } else { $this->childState = null; } }
php
public function scanChild($lang) { assert(isset($this->childScanners[$lang])); $scanner = $this->childScanners[$lang]; $scanner->pos($this->pos()); $substr = $scanner->main(); $this->record($scanner->tagged(), 'XML', true); $this->pos($scanner->pos()); if ($scanner->interrupt) { $this->childState = array($lang, $this->pos()); } else { $this->childState = null; } }
[ "public", "function", "scanChild", "(", "$", "lang", ")", "{", "assert", "(", "isset", "(", "$", "this", "->", "childScanners", "[", "$", "lang", "]", ")", ")", ";", "$", "scanner", "=", "$", "this", "->", "childScanners", "[", "$", "lang", "]", ";", "$", "scanner", "->", "pos", "(", "$", "this", "->", "pos", "(", ")", ")", ";", "$", "substr", "=", "$", "scanner", "->", "main", "(", ")", ";", "$", "this", "->", "record", "(", "$", "scanner", "->", "tagged", "(", ")", ",", "'XML'", ",", "true", ")", ";", "$", "this", "->", "pos", "(", "$", "scanner", "->", "pos", "(", ")", ")", ";", "if", "(", "$", "scanner", "->", "interrupt", ")", "{", "$", "this", "->", "childState", "=", "array", "(", "$", "lang", ",", "$", "this", "->", "pos", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "childState", "=", "null", ";", "}", "}" ]
c+p from HTML scanner
[ "c", "+", "p", "from", "HTML", "scanner" ]
4adc18f414534abe986133d6d38e8e9787d32e69
https://github.com/markwatkinson/luminous/blob/4adc18f414534abe986133d6d38e8e9787d32e69/src/Luminous/Scanners/EcmaScriptScanner.php#L223-L236
13,319
unimapper/unimapper
src/Entity.php
Entity.getValidator
public function getValidator() { if (!$this->validator) { $this->validator = new Validator($this); } return $this->validator->onEntity(); }
php
public function getValidator() { if (!$this->validator) { $this->validator = new Validator($this); } return $this->validator->onEntity(); }
[ "public", "function", "getValidator", "(", ")", "{", "if", "(", "!", "$", "this", "->", "validator", ")", "{", "$", "this", "->", "validator", "=", "new", "Validator", "(", "$", "this", ")", ";", "}", "return", "$", "this", "->", "validator", "->", "onEntity", "(", ")", ";", "}" ]
Get entity validator @return \UniMapper\Validator
[ "Get", "entity", "validator" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Entity.php#L371-L377
13,320
unimapper/unimapper
src/Entity.php
Entity.toArray
public function toArray($nesting = false) { $output = []; foreach ($this::getReflection()->getProperties() as $propertyName => $property) { $value = $this->{$propertyName}; if (($value instanceof Entity\Collection || $value instanceof Entity) && $nesting ) { $output[$propertyName] = $value->toArray($nesting); } else { $output[$propertyName] = $value; } } return $output; }
php
public function toArray($nesting = false) { $output = []; foreach ($this::getReflection()->getProperties() as $propertyName => $property) { $value = $this->{$propertyName}; if (($value instanceof Entity\Collection || $value instanceof Entity) && $nesting ) { $output[$propertyName] = $value->toArray($nesting); } else { $output[$propertyName] = $value; } } return $output; }
[ "public", "function", "toArray", "(", "$", "nesting", "=", "false", ")", "{", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "this", "::", "getReflection", "(", ")", "->", "getProperties", "(", ")", "as", "$", "propertyName", "=>", "$", "property", ")", "{", "$", "value", "=", "$", "this", "->", "{", "$", "propertyName", "}", ";", "if", "(", "(", "$", "value", "instanceof", "Entity", "\\", "Collection", "||", "$", "value", "instanceof", "Entity", ")", "&&", "$", "nesting", ")", "{", "$", "output", "[", "$", "propertyName", "]", "=", "$", "value", "->", "toArray", "(", "$", "nesting", ")", ";", "}", "else", "{", "$", "output", "[", "$", "propertyName", "]", "=", "$", "value", ";", "}", "}", "return", "$", "output", ";", "}" ]
Get entity values as array @param boolean $nesting Convert nested entities and collections too @return array
[ "Get", "entity", "values", "as", "array" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Entity.php#L396-L412
13,321
unimapper/unimapper
src/Entity.php
Entity.jsonSerialize
public function jsonSerialize() { $output = []; foreach ($this::getReflection()->getProperties() as $propertyName => $property) { $value = $this->{$propertyName}; if ($value instanceof Entity\Collection || $value instanceof Entity) { $output[$propertyName] = $value->jsonSerialize(); } elseif ($value instanceof \DateTime && $property->getType() === Entity\Reflection\Property::TYPE_DATE ) { $output[$propertyName] = (array) $value; $output[$propertyName]["date"] = $value->format(self::$dateFormat); } else { $output[$propertyName] = $value; } } return $output; }
php
public function jsonSerialize() { $output = []; foreach ($this::getReflection()->getProperties() as $propertyName => $property) { $value = $this->{$propertyName}; if ($value instanceof Entity\Collection || $value instanceof Entity) { $output[$propertyName] = $value->jsonSerialize(); } elseif ($value instanceof \DateTime && $property->getType() === Entity\Reflection\Property::TYPE_DATE ) { $output[$propertyName] = (array) $value; $output[$propertyName]["date"] = $value->format(self::$dateFormat); } else { $output[$propertyName] = $value; } } return $output; }
[ "public", "function", "jsonSerialize", "(", ")", "{", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "this", "::", "getReflection", "(", ")", "->", "getProperties", "(", ")", "as", "$", "propertyName", "=>", "$", "property", ")", "{", "$", "value", "=", "$", "this", "->", "{", "$", "propertyName", "}", ";", "if", "(", "$", "value", "instanceof", "Entity", "\\", "Collection", "||", "$", "value", "instanceof", "Entity", ")", "{", "$", "output", "[", "$", "propertyName", "]", "=", "$", "value", "->", "jsonSerialize", "(", ")", ";", "}", "elseif", "(", "$", "value", "instanceof", "\\", "DateTime", "&&", "$", "property", "->", "getType", "(", ")", "===", "Entity", "\\", "Reflection", "\\", "Property", "::", "TYPE_DATE", ")", "{", "$", "output", "[", "$", "propertyName", "]", "=", "(", "array", ")", "$", "value", ";", "$", "output", "[", "$", "propertyName", "]", "[", "\"date\"", "]", "=", "$", "value", "->", "format", "(", "self", "::", "$", "dateFormat", ")", ";", "}", "else", "{", "$", "output", "[", "$", "propertyName", "]", "=", "$", "value", ";", "}", "}", "return", "$", "output", ";", "}" ]
Gets data which should be serialized to JSON @return array
[ "Gets", "data", "which", "should", "be", "serialized", "to", "JSON" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Entity.php#L419-L438
13,322
liip/LiipDrupalConnectorModule
src/Liip/Drupal/Modules/DrupalConnector/Menu.php
Menu.menu_tree_all_data
public function menu_tree_all_data($menu_name, $link = NULL, $max_depth = NULL) { return menu_tree_all_data($menu_name, $link, $max_depth); }
php
public function menu_tree_all_data($menu_name, $link = NULL, $max_depth = NULL) { return menu_tree_all_data($menu_name, $link, $max_depth); }
[ "public", "function", "menu_tree_all_data", "(", "$", "menu_name", ",", "$", "link", "=", "NULL", ",", "$", "max_depth", "=", "NULL", ")", "{", "return", "menu_tree_all_data", "(", "$", "menu_name", ",", "$", "link", ",", "$", "max_depth", ")", ";", "}" ]
Get the data structure representing a named menu tree. Since this can be the full tree including hidden items, the data returned may be used for generating an an admin interface or a select. @param $menu_name The named menu links to return @param $link A fully loaded menu link, or NULL. If a link is supplied, only the path to root will be included in the returned tree - as if this link represented the current page in a visible menu. @param $max_depth Optional maximum depth of links to retrieve. Typically useful if only one or two levels of a sub tree are needed in conjunction with a non-NULL $link, in which case $max_depth should be greater than $link['depth']. @return An tree of menu links in an array, in the order they should be rendered.
[ "Get", "the", "data", "structure", "representing", "a", "named", "menu", "tree", "." ]
6ba161ef0d3a27c108e533f1adbea22ed73b78ce
https://github.com/liip/LiipDrupalConnectorModule/blob/6ba161ef0d3a27c108e533f1adbea22ed73b78ce/src/Liip/Drupal/Modules/DrupalConnector/Menu.php#L259-L262
13,323
liip/LiipDrupalConnectorModule
src/Liip/Drupal/Modules/DrupalConnector/Menu.php
Menu.menu_tree_page_data
public function menu_tree_page_data($menu_name, $max_depth = NULL, $only_active_trail = FALSE) { return menu_tree_page_data($menu_name, $max_depth, $only_active_trail); }
php
public function menu_tree_page_data($menu_name, $max_depth = NULL, $only_active_trail = FALSE) { return menu_tree_page_data($menu_name, $max_depth, $only_active_trail); }
[ "public", "function", "menu_tree_page_data", "(", "$", "menu_name", ",", "$", "max_depth", "=", "NULL", ",", "$", "only_active_trail", "=", "FALSE", ")", "{", "return", "menu_tree_page_data", "(", "$", "menu_name", ",", "$", "max_depth", ",", "$", "only_active_trail", ")", ";", "}" ]
Get the data structure representing a named menu tree, based on the current page. The tree order is maintained by storing each parent in an individual field, see http://drupal.org/node/141866 for more. @param $menu_name The named menu links to return. @param $max_depth (optional) The maximum depth of links to retrieve. @param $only_active_trail (optional) Whether to only return the links in the active trail (TRUE) instead of all links on every level of the menu link tree (FALSE). Defaults to FALSE. Internally used for breadcrumbs only. @return An array of menu links, in the order they should be rendered. The array is a list of associative arrays -- these have two keys, link and below. link is a menu item, ready for theming as a link. Below represents the submenu below the link if there is one, and it is a subtree that has the same structure described for the top-level array.
[ "Get", "the", "data", "structure", "representing", "a", "named", "menu", "tree", "based", "on", "the", "current", "page", "." ]
6ba161ef0d3a27c108e533f1adbea22ed73b78ce
https://github.com/liip/LiipDrupalConnectorModule/blob/6ba161ef0d3a27c108e533f1adbea22ed73b78ce/src/Liip/Drupal/Modules/DrupalConnector/Menu.php#L323-L326
13,324
liip/LiipDrupalConnectorModule
src/Liip/Drupal/Modules/DrupalConnector/Menu.php
Menu.menu_link_maintain
public function menu_link_maintain($module, $op, $link_path, $link_title) { return menu_link_maintain($module, $op, $link_path, $link_title); }
php
public function menu_link_maintain($module, $op, $link_path, $link_title) { return menu_link_maintain($module, $op, $link_path, $link_title); }
[ "public", "function", "menu_link_maintain", "(", "$", "module", ",", "$", "op", ",", "$", "link_path", ",", "$", "link_title", ")", "{", "return", "menu_link_maintain", "(", "$", "module", ",", "$", "op", ",", "$", "link_path", ",", "$", "link_title", ")", ";", "}" ]
Insert, update or delete an uncustomized menu link related to a module. @param $module The name of the module. @param $op Operation to perform: insert, update or delete. @param $link_path The path this link points to. @param $link_title Title of the link to insert or new title to update the link to. Unused for delete. @return The insert op returns the mlid of the new item. Others op return NULL.
[ "Insert", "update", "or", "delete", "an", "uncustomized", "menu", "link", "related", "to", "a", "module", "." ]
6ba161ef0d3a27c108e533f1adbea22ed73b78ce
https://github.com/liip/LiipDrupalConnectorModule/blob/6ba161ef0d3a27c108e533f1adbea22ed73b78ce/src/Liip/Drupal/Modules/DrupalConnector/Menu.php#L1038-L1041
13,325
PeeHaa/Minifine
src/Factory.php
Factory.build
public function build($basePath, $production = false) { $minifine = new Minifine($basePath, $production); $minifine->appendJsMinifier(new MatthiasMullieJs(new JS())); $minifine->appendCssMinifier(new MatthiasMullieCss(new Css())); return $minifine; }
php
public function build($basePath, $production = false) { $minifine = new Minifine($basePath, $production); $minifine->appendJsMinifier(new MatthiasMullieJs(new JS())); $minifine->appendCssMinifier(new MatthiasMullieCss(new Css())); return $minifine; }
[ "public", "function", "build", "(", "$", "basePath", ",", "$", "production", "=", "false", ")", "{", "$", "minifine", "=", "new", "Minifine", "(", "$", "basePath", ",", "$", "production", ")", ";", "$", "minifine", "->", "appendJsMinifier", "(", "new", "MatthiasMullieJs", "(", "new", "JS", "(", ")", ")", ")", ";", "$", "minifine", "->", "appendCssMinifier", "(", "new", "MatthiasMullieCss", "(", "new", "Css", "(", ")", ")", ")", ";", "return", "$", "minifine", ";", "}" ]
Builds a new minifine instance @param string $basePath The base path to the resources (under most common cases this will be the public web root directory) @param bool $production The current environment @return \Minifine\Minifine
[ "Builds", "a", "new", "minifine", "instance" ]
8f8841fa8503de1557af96f1d2546cc6d02cc0a2
https://github.com/PeeHaa/Minifine/blob/8f8841fa8503de1557af96f1d2546cc6d02cc0a2/src/Factory.php#L37-L45
13,326
unimapper/unimapper
src/Exception/ReflectionException.php
ReflectionException.getEntityLine
public function getEntityLine() { if ($this->definition) { foreach (file($this->getEntityPath(), FILE_IGNORE_NEW_LINES) as $lineNumber => $line ) { if (strpos($line, $this->definition) !== false) { return $lineNumber + 1; } } } return 0; }
php
public function getEntityLine() { if ($this->definition) { foreach (file($this->getEntityPath(), FILE_IGNORE_NEW_LINES) as $lineNumber => $line ) { if (strpos($line, $this->definition) !== false) { return $lineNumber + 1; } } } return 0; }
[ "public", "function", "getEntityLine", "(", ")", "{", "if", "(", "$", "this", "->", "definition", ")", "{", "foreach", "(", "file", "(", "$", "this", "->", "getEntityPath", "(", ")", ",", "FILE_IGNORE_NEW_LINES", ")", "as", "$", "lineNumber", "=>", "$", "line", ")", "{", "if", "(", "strpos", "(", "$", "line", ",", "$", "this", "->", "definition", ")", "!==", "false", ")", "{", "return", "$", "lineNumber", "+", "1", ";", "}", "}", "}", "return", "0", ";", "}" ]
Get problematic entity line number @return integer
[ "Get", "problematic", "entity", "line", "number" ]
a63b39f38a790fec7e852c8ef1e4c31653e689f7
https://github.com/unimapper/unimapper/blob/a63b39f38a790fec7e852c8ef1e4c31653e689f7/src/Exception/ReflectionException.php#L42-L54
13,327
terdia/legato-framework
src/Console/AbstractFileGenerator.php
AbstractFileGenerator.runFileGeneratorCommand
public function runFileGeneratorCommand($path, $argument) { if ($this->filesystem->exists($path)) { return 'File with the name '.$argument.' already exist'; } $folder_name = explode('/', $argument); $folder = ''; if (count($folder_name) > 1) { $folder_path = array_slice($folder_name, 0, -1); foreach ($folder_path as $f) { $folder .= "$f/"; } $filename = end($folder_name); } else { $filename = $argument; } $folder ? $location = "$this->basePath/$folder/$filename.php" : $location = "$this->basePath/$filename.php"; $template = $this->findTemplateAndReplacePlaceHolders('PlaceHolder', $filename, file_get_contents($this->getTemplate($this->type)) ); $this->filesystem->dumpFile($location, $template); return true; }
php
public function runFileGeneratorCommand($path, $argument) { if ($this->filesystem->exists($path)) { return 'File with the name '.$argument.' already exist'; } $folder_name = explode('/', $argument); $folder = ''; if (count($folder_name) > 1) { $folder_path = array_slice($folder_name, 0, -1); foreach ($folder_path as $f) { $folder .= "$f/"; } $filename = end($folder_name); } else { $filename = $argument; } $folder ? $location = "$this->basePath/$folder/$filename.php" : $location = "$this->basePath/$filename.php"; $template = $this->findTemplateAndReplacePlaceHolders('PlaceHolder', $filename, file_get_contents($this->getTemplate($this->type)) ); $this->filesystem->dumpFile($location, $template); return true; }
[ "public", "function", "runFileGeneratorCommand", "(", "$", "path", ",", "$", "argument", ")", "{", "if", "(", "$", "this", "->", "filesystem", "->", "exists", "(", "$", "path", ")", ")", "{", "return", "'File with the name '", ".", "$", "argument", ".", "' already exist'", ";", "}", "$", "folder_name", "=", "explode", "(", "'/'", ",", "$", "argument", ")", ";", "$", "folder", "=", "''", ";", "if", "(", "count", "(", "$", "folder_name", ")", ">", "1", ")", "{", "$", "folder_path", "=", "array_slice", "(", "$", "folder_name", ",", "0", ",", "-", "1", ")", ";", "foreach", "(", "$", "folder_path", "as", "$", "f", ")", "{", "$", "folder", ".=", "\"$f/\"", ";", "}", "$", "filename", "=", "end", "(", "$", "folder_name", ")", ";", "}", "else", "{", "$", "filename", "=", "$", "argument", ";", "}", "$", "folder", "?", "$", "location", "=", "\"$this->basePath/$folder/$filename.php\"", ":", "$", "location", "=", "\"$this->basePath/$filename.php\"", ";", "$", "template", "=", "$", "this", "->", "findTemplateAndReplacePlaceHolders", "(", "'PlaceHolder'", ",", "$", "filename", ",", "file_get_contents", "(", "$", "this", "->", "getTemplate", "(", "$", "this", "->", "type", ")", ")", ")", ";", "$", "this", "->", "filesystem", "->", "dumpFile", "(", "$", "location", ",", "$", "template", ")", ";", "return", "true", ";", "}" ]
Generate and move file to specified path. @param $path @param $argument @return string
[ "Generate", "and", "move", "file", "to", "specified", "path", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Console/AbstractFileGenerator.php#L105-L128
13,328
PandaPlatform/framework
src/Panda/Routing/RouteCollection.php
RouteCollection.getMatchingRoute
public function getMatchingRoute($routes, Request $request) { foreach ($routes as $matchingRoute) { if ($matchingRoute->matches($request)) { return $matchingRoute; } } return null; }
php
public function getMatchingRoute($routes, Request $request) { foreach ($routes as $matchingRoute) { if ($matchingRoute->matches($request)) { return $matchingRoute; } } return null; }
[ "public", "function", "getMatchingRoute", "(", "$", "routes", ",", "Request", "$", "request", ")", "{", "foreach", "(", "$", "routes", "as", "$", "matchingRoute", ")", "{", "if", "(", "$", "matchingRoute", "->", "matches", "(", "$", "request", ")", ")", "{", "return", "$", "matchingRoute", ";", "}", "}", "return", "null", ";", "}" ]
Check which of the given routes matches the given request. @param Route[] $routes @param Request $request @return Route|null @throws \LogicException
[ "Check", "which", "of", "the", "given", "routes", "matches", "the", "given", "request", "." ]
a78cf051b379896b5a4d5df620988e37a0e632f5
https://github.com/PandaPlatform/framework/blob/a78cf051b379896b5a4d5df620988e37a0e632f5/src/Panda/Routing/RouteCollection.php#L90-L99
13,329
PandaPlatform/framework
src/Panda/Routing/RouteCollection.php
RouteCollection.getByMethod
public function getByMethod($method = null) { if (is_null($method)) { return $this->getRoutes(); } // Filter routes by the given method return ArrayHelper::get($this->routes, $method, []); }
php
public function getByMethod($method = null) { if (is_null($method)) { return $this->getRoutes(); } // Filter routes by the given method return ArrayHelper::get($this->routes, $method, []); }
[ "public", "function", "getByMethod", "(", "$", "method", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "method", ")", ")", "{", "return", "$", "this", "->", "getRoutes", "(", ")", ";", "}", "// Filter routes by the given method", "return", "ArrayHelper", "::", "get", "(", "$", "this", "->", "routes", ",", "$", "method", ",", "[", "]", ")", ";", "}" ]
Get all matched routes according to the given request method. @param string|null $method @return array
[ "Get", "all", "matched", "routes", "according", "to", "the", "given", "request", "method", "." ]
a78cf051b379896b5a4d5df620988e37a0e632f5
https://github.com/PandaPlatform/framework/blob/a78cf051b379896b5a4d5df620988e37a0e632f5/src/Panda/Routing/RouteCollection.php#L108-L116
13,330
ptlis/conneg
src/Preference/Matched/MatchedPreferenceComparator.php
MatchedPreferenceComparator.compare
public function compare(MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue) { // Compare by quality factors - highest quality factor has precedence. $result = $this->compareQualityFactorPair($lValue, $rValue); // Quality factors are equal attempt to sort by match precedence if (0 === $result) { $result = $this->comparePrecedence($lValue, $rValue); } // Quality factors & precedences match, simply sort alphabetically as this ensures that the sort is stable if (0 === $result) { $result = $this->compareVariant($lValue, $rValue); } return $result; }
php
public function compare(MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue) { // Compare by quality factors - highest quality factor has precedence. $result = $this->compareQualityFactorPair($lValue, $rValue); // Quality factors are equal attempt to sort by match precedence if (0 === $result) { $result = $this->comparePrecedence($lValue, $rValue); } // Quality factors & precedences match, simply sort alphabetically as this ensures that the sort is stable if (0 === $result) { $result = $this->compareVariant($lValue, $rValue); } return $result; }
[ "public", "function", "compare", "(", "MatchedPreferenceInterface", "$", "lValue", ",", "MatchedPreferenceInterface", "$", "rValue", ")", "{", "// Compare by quality factors - highest quality factor has precedence.", "$", "result", "=", "$", "this", "->", "compareQualityFactorPair", "(", "$", "lValue", ",", "$", "rValue", ")", ";", "// Quality factors are equal attempt to sort by match precedence", "if", "(", "0", "===", "$", "result", ")", "{", "$", "result", "=", "$", "this", "->", "comparePrecedence", "(", "$", "lValue", ",", "$", "rValue", ")", ";", "}", "// Quality factors & precedences match, simply sort alphabetically as this ensures that the sort is stable", "if", "(", "0", "===", "$", "result", ")", "{", "$", "result", "=", "$", "this", "->", "compareVariant", "(", "$", "lValue", ",", "$", "rValue", ")", ";", "}", "return", "$", "result", ";", "}" ]
Comparison function used for ordering matched preferences. @param MatchedPreferenceInterface $lValue @param MatchedPreferenceInterface $rValue @return int -1, 0, 1 (see usort() callback for meaning)
[ "Comparison", "function", "used", "for", "ordering", "matched", "preferences", "." ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Preference/Matched/MatchedPreferenceComparator.php#L26-L42
13,331
ptlis/conneg
src/Preference/Matched/MatchedPreferenceComparator.php
MatchedPreferenceComparator.compareQualityFactorPair
private function compareQualityFactorPair( MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue ) { // Build a list of quality factor comparisons to perform; highest preference given to quality factor products, // followed by those provided by the client & finally the server provided. $compareList = array( array( 'left' => $lValue, 'right' => $rValue ), array( 'left' => $lValue->getClientPreference(), 'right' => $rValue->getClientPreference() ), array( 'left' => $lValue->getServerPreference(), 'right' => $rValue->getServerPreference() ) ); $result = 0; foreach ($compareList as $compare) { $result = $this->compareQualityFactor($compare['left'], $compare['right']); // If a non matching result was found then we have the result of our comparison if (0 !== $result) { break; } } return $result; }
php
private function compareQualityFactorPair( MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue ) { // Build a list of quality factor comparisons to perform; highest preference given to quality factor products, // followed by those provided by the client & finally the server provided. $compareList = array( array( 'left' => $lValue, 'right' => $rValue ), array( 'left' => $lValue->getClientPreference(), 'right' => $rValue->getClientPreference() ), array( 'left' => $lValue->getServerPreference(), 'right' => $rValue->getServerPreference() ) ); $result = 0; foreach ($compareList as $compare) { $result = $this->compareQualityFactor($compare['left'], $compare['right']); // If a non matching result was found then we have the result of our comparison if (0 !== $result) { break; } } return $result; }
[ "private", "function", "compareQualityFactorPair", "(", "MatchedPreferenceInterface", "$", "lValue", ",", "MatchedPreferenceInterface", "$", "rValue", ")", "{", "// Build a list of quality factor comparisons to perform; highest preference given to quality factor products,", "// followed by those provided by the client & finally the server provided.", "$", "compareList", "=", "array", "(", "array", "(", "'left'", "=>", "$", "lValue", ",", "'right'", "=>", "$", "rValue", ")", ",", "array", "(", "'left'", "=>", "$", "lValue", "->", "getClientPreference", "(", ")", ",", "'right'", "=>", "$", "rValue", "->", "getClientPreference", "(", ")", ")", ",", "array", "(", "'left'", "=>", "$", "lValue", "->", "getServerPreference", "(", ")", ",", "'right'", "=>", "$", "rValue", "->", "getServerPreference", "(", ")", ")", ")", ";", "$", "result", "=", "0", ";", "foreach", "(", "$", "compareList", "as", "$", "compare", ")", "{", "$", "result", "=", "$", "this", "->", "compareQualityFactor", "(", "$", "compare", "[", "'left'", "]", ",", "$", "compare", "[", "'right'", "]", ")", ";", "// If a non matching result was found then we have the result of our comparison", "if", "(", "0", "!==", "$", "result", ")", "{", "break", ";", "}", "}", "return", "$", "result", ";", "}" ]
Comparison function for quality factors of matched preferences. @param MatchedPreferenceInterface $lValue @param MatchedPreferenceInterface $rValue @return int -1, 0, 1 (see usort() callback for meaning)
[ "Comparison", "function", "for", "quality", "factors", "of", "matched", "preferences", "." ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Preference/Matched/MatchedPreferenceComparator.php#L52-L84
13,332
ptlis/conneg
src/Preference/Matched/MatchedPreferenceComparator.php
MatchedPreferenceComparator.compareQualityFactor
private function compareQualityFactor(PreferenceInterface $lValue, PreferenceInterface $rValue) { if ($rValue->getQualityFactor() < $lValue->getQualityFactor()) { return -1; } elseif ($rValue->getQualityFactor() > $lValue->getQualityFactor()) { return 1; } else { return 0; } }
php
private function compareQualityFactor(PreferenceInterface $lValue, PreferenceInterface $rValue) { if ($rValue->getQualityFactor() < $lValue->getQualityFactor()) { return -1; } elseif ($rValue->getQualityFactor() > $lValue->getQualityFactor()) { return 1; } else { return 0; } }
[ "private", "function", "compareQualityFactor", "(", "PreferenceInterface", "$", "lValue", ",", "PreferenceInterface", "$", "rValue", ")", "{", "if", "(", "$", "rValue", "->", "getQualityFactor", "(", ")", "<", "$", "lValue", "->", "getQualityFactor", "(", ")", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "rValue", "->", "getQualityFactor", "(", ")", ">", "$", "lValue", "->", "getQualityFactor", "(", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Compare quality factors of preferences. @param PreferenceInterface $lValue @param PreferenceInterface $rValue @return int -1, 0, 1 (see usort() callback for meaning)
[ "Compare", "quality", "factors", "of", "preferences", "." ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Preference/Matched/MatchedPreferenceComparator.php#L94-L103
13,333
ptlis/conneg
src/Preference/Matched/MatchedPreferenceComparator.php
MatchedPreferenceComparator.comparePrecedence
private function comparePrecedence(PreferenceInterface $lValue, PreferenceInterface $rValue) { if ($rValue->getPrecedence() < $lValue->getPrecedence()) { return -1; } elseif ($rValue->getPrecedence() > $lValue->getPrecedence()) { return 1; } else { return 0; } }
php
private function comparePrecedence(PreferenceInterface $lValue, PreferenceInterface $rValue) { if ($rValue->getPrecedence() < $lValue->getPrecedence()) { return -1; } elseif ($rValue->getPrecedence() > $lValue->getPrecedence()) { return 1; } else { return 0; } }
[ "private", "function", "comparePrecedence", "(", "PreferenceInterface", "$", "lValue", ",", "PreferenceInterface", "$", "rValue", ")", "{", "if", "(", "$", "rValue", "->", "getPrecedence", "(", ")", "<", "$", "lValue", "->", "getPrecedence", "(", ")", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "rValue", "->", "getPrecedence", "(", ")", ">", "$", "lValue", "->", "getPrecedence", "(", ")", ")", "{", "return", "1", ";", "}", "else", "{", "return", "0", ";", "}", "}" ]
Compare precedences of preferences. @param PreferenceInterface $lValue @param PreferenceInterface $rValue @return int -1, 0, 1 (see usort() callback for meaning)
[ "Compare", "precedences", "of", "preferences", "." ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Preference/Matched/MatchedPreferenceComparator.php#L113-L122
13,334
ptlis/conneg
src/Preference/Matched/MatchedPreferenceComparator.php
MatchedPreferenceComparator.compareVariant
private function compareVariant(MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue) { return strcasecmp($lValue->getVariant(), $rValue->getVariant()); }
php
private function compareVariant(MatchedPreferenceInterface $lValue, MatchedPreferenceInterface $rValue) { return strcasecmp($lValue->getVariant(), $rValue->getVariant()); }
[ "private", "function", "compareVariant", "(", "MatchedPreferenceInterface", "$", "lValue", ",", "MatchedPreferenceInterface", "$", "rValue", ")", "{", "return", "strcasecmp", "(", "$", "lValue", "->", "getVariant", "(", ")", ",", "$", "rValue", "->", "getVariant", "(", ")", ")", ";", "}" ]
Compare preferences alphabetically @param MatchedPreferenceInterface $lValue @param MatchedPreferenceInterface $rValue @return int -1, 0, 1 (see usort() callback for meaning)
[ "Compare", "preferences", "alphabetically" ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Preference/Matched/MatchedPreferenceComparator.php#L132-L135
13,335
incraigulous/contentful-sdk
src/ManagementResources/ResourceBase.php
ResourceBase.post
function post($payload) { $this->requestDecorator->setPayload($payload); $result = $this->client->post($this->requestDecorator->makeResource(), $this->requestDecorator->makePayload(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
php
function post($payload) { $this->requestDecorator->setPayload($payload); $result = $this->client->post($this->requestDecorator->makeResource(), $this->requestDecorator->makePayload(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
[ "function", "post", "(", "$", "payload", ")", "{", "$", "this", "->", "requestDecorator", "->", "setPayload", "(", "$", "payload", ")", ";", "$", "result", "=", "$", "this", "->", "client", "->", "post", "(", "$", "this", "->", "requestDecorator", "->", "makeResource", "(", ")", ",", "$", "this", "->", "requestDecorator", "->", "makePayload", "(", ")", ",", "$", "this", "->", "requestDecorator", "->", "makeHeaders", "(", ")", ")", ";", "$", "this", "->", "refresh", "(", ")", ";", "return", "$", "result", ";", "}" ]
Make a post request. @param $payload @return mixed
[ "Make", "a", "post", "request", "." ]
29399b11b0e085a06ea5976661378c379fe5a731
https://github.com/incraigulous/contentful-sdk/blob/29399b11b0e085a06ea5976661378c379fe5a731/src/ManagementResources/ResourceBase.php#L14-L20
13,336
incraigulous/contentful-sdk
src/ManagementResources/ResourceBase.php
ResourceBase.put
function put($id, $payload) { $this->requestDecorator->setId($id); $this->requestDecorator->setPayload($payload); if ((is_array($payload)) && (!empty($payload['sys']['version']))) { $this->requestDecorator->addHeader('X-Contentful-Version', $payload['sys']['version']); } $result = $this->client->put($this->requestDecorator->makeResource(), $this->requestDecorator->makePayload(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
php
function put($id, $payload) { $this->requestDecorator->setId($id); $this->requestDecorator->setPayload($payload); if ((is_array($payload)) && (!empty($payload['sys']['version']))) { $this->requestDecorator->addHeader('X-Contentful-Version', $payload['sys']['version']); } $result = $this->client->put($this->requestDecorator->makeResource(), $this->requestDecorator->makePayload(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
[ "function", "put", "(", "$", "id", ",", "$", "payload", ")", "{", "$", "this", "->", "requestDecorator", "->", "setId", "(", "$", "id", ")", ";", "$", "this", "->", "requestDecorator", "->", "setPayload", "(", "$", "payload", ")", ";", "if", "(", "(", "is_array", "(", "$", "payload", ")", ")", "&&", "(", "!", "empty", "(", "$", "payload", "[", "'sys'", "]", "[", "'version'", "]", ")", ")", ")", "{", "$", "this", "->", "requestDecorator", "->", "addHeader", "(", "'X-Contentful-Version'", ",", "$", "payload", "[", "'sys'", "]", "[", "'version'", "]", ")", ";", "}", "$", "result", "=", "$", "this", "->", "client", "->", "put", "(", "$", "this", "->", "requestDecorator", "->", "makeResource", "(", ")", ",", "$", "this", "->", "requestDecorator", "->", "makePayload", "(", ")", ",", "$", "this", "->", "requestDecorator", "->", "makeHeaders", "(", ")", ")", ";", "$", "this", "->", "refresh", "(", ")", ";", "return", "$", "result", ";", "}" ]
Make a put request. @param $id @param $payload @return mixed
[ "Make", "a", "put", "request", "." ]
29399b11b0e085a06ea5976661378c379fe5a731
https://github.com/incraigulous/contentful-sdk/blob/29399b11b0e085a06ea5976661378c379fe5a731/src/ManagementResources/ResourceBase.php#L28-L38
13,337
incraigulous/contentful-sdk
src/ManagementResources/ResourceBase.php
ResourceBase.delete
function delete($id) { $this->requestDecorator->setId($id); $result = $this->client->delete($this->requestDecorator->makeResource(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
php
function delete($id) { $this->requestDecorator->setId($id); $result = $this->client->delete($this->requestDecorator->makeResource(), $this->requestDecorator->makeHeaders()); $this->refresh(); return $result; }
[ "function", "delete", "(", "$", "id", ")", "{", "$", "this", "->", "requestDecorator", "->", "setId", "(", "$", "id", ")", ";", "$", "result", "=", "$", "this", "->", "client", "->", "delete", "(", "$", "this", "->", "requestDecorator", "->", "makeResource", "(", ")", ",", "$", "this", "->", "requestDecorator", "->", "makeHeaders", "(", ")", ")", ";", "$", "this", "->", "refresh", "(", ")", ";", "return", "$", "result", ";", "}" ]
Make a delete request. @param $id @return mixed
[ "Make", "a", "delete", "request", "." ]
29399b11b0e085a06ea5976661378c379fe5a731
https://github.com/incraigulous/contentful-sdk/blob/29399b11b0e085a06ea5976661378c379fe5a731/src/ManagementResources/ResourceBase.php#L45-L51
13,338
wangsir0624/queue
src/RedisQueue.php
RedisQueue.push
public function push(AbstractJob $job) { if($job->getRunAt() > time()) { return $this->addJobToRetrySet($job, $job->getRunAt()); } return (bool)$this->client->rpush( $this->getQueueNameWithPrefix($job->getQueue()), serialize($job) ); }
php
public function push(AbstractJob $job) { if($job->getRunAt() > time()) { return $this->addJobToRetrySet($job, $job->getRunAt()); } return (bool)$this->client->rpush( $this->getQueueNameWithPrefix($job->getQueue()), serialize($job) ); }
[ "public", "function", "push", "(", "AbstractJob", "$", "job", ")", "{", "if", "(", "$", "job", "->", "getRunAt", "(", ")", ">", "time", "(", ")", ")", "{", "return", "$", "this", "->", "addJobToRetrySet", "(", "$", "job", ",", "$", "job", "->", "getRunAt", "(", ")", ")", ";", "}", "return", "(", "bool", ")", "$", "this", "->", "client", "->", "rpush", "(", "$", "this", "->", "getQueueNameWithPrefix", "(", "$", "job", "->", "getQueue", "(", ")", ")", ",", "serialize", "(", "$", "job", ")", ")", ";", "}" ]
push a job to the queue @param AbstractJob $job @return bool
[ "push", "a", "job", "to", "the", "queue" ]
10541f9694b5d9759329ae908033dd3097ce6923
https://github.com/wangsir0624/queue/blob/10541f9694b5d9759329ae908033dd3097ce6923/src/RedisQueue.php#L38-L48
13,339
wangsir0624/queue
src/RedisQueue.php
RedisQueue.pop
public function pop($queue) { //migrate the retry jobs $this->migrateRetryJobs($queue); $data = $this->client->lpop($this->getQueueNameWithPrefix($queue)); if (!empty($data)) { $job = @unserialize($data); if ($job instanceof AbstractJob) { return $job; } } return null; }
php
public function pop($queue) { //migrate the retry jobs $this->migrateRetryJobs($queue); $data = $this->client->lpop($this->getQueueNameWithPrefix($queue)); if (!empty($data)) { $job = @unserialize($data); if ($job instanceof AbstractJob) { return $job; } } return null; }
[ "public", "function", "pop", "(", "$", "queue", ")", "{", "//migrate the retry jobs", "$", "this", "->", "migrateRetryJobs", "(", "$", "queue", ")", ";", "$", "data", "=", "$", "this", "->", "client", "->", "lpop", "(", "$", "this", "->", "getQueueNameWithPrefix", "(", "$", "queue", ")", ")", ";", "if", "(", "!", "empty", "(", "$", "data", ")", ")", "{", "$", "job", "=", "@", "unserialize", "(", "$", "data", ")", ";", "if", "(", "$", "job", "instanceof", "AbstractJob", ")", "{", "return", "$", "job", ";", "}", "}", "return", "null", ";", "}" ]
get a job from the queue @param string $queue @return AbstractJob|null
[ "get", "a", "job", "from", "the", "queue" ]
10541f9694b5d9759329ae908033dd3097ce6923
https://github.com/wangsir0624/queue/blob/10541f9694b5d9759329ae908033dd3097ce6923/src/RedisQueue.php#L55-L70
13,340
wangsir0624/queue
src/RedisQueue.php
RedisQueue.retry
public function retry(AbstractJob $job) { if ($job->shouldRetry()) { return $this->addJobToRetrySet($job, $job->getRetryTime()); } return false; }
php
public function retry(AbstractJob $job) { if ($job->shouldRetry()) { return $this->addJobToRetrySet($job, $job->getRetryTime()); } return false; }
[ "public", "function", "retry", "(", "AbstractJob", "$", "job", ")", "{", "if", "(", "$", "job", "->", "shouldRetry", "(", ")", ")", "{", "return", "$", "this", "->", "addJobToRetrySet", "(", "$", "job", ",", "$", "job", "->", "getRetryTime", "(", ")", ")", ";", "}", "return", "false", ";", "}" ]
retry a job @param AbstractJob $job @return bool
[ "retry", "a", "job" ]
10541f9694b5d9759329ae908033dd3097ce6923
https://github.com/wangsir0624/queue/blob/10541f9694b5d9759329ae908033dd3097ce6923/src/RedisQueue.php#L77-L84
13,341
wangsir0624/queue
src/RedisQueue.php
RedisQueue.migrateRetryJobs
protected function migrateRetryJobs($queue) { $luaScript = <<<LUA -- Get all of the jobs with an expired "score"... local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1]) -- If we have values in the array, we will remove them from the first queue -- and add them onto the destination queue in chunks of 100, which moves -- all of the appropriate jobs onto the destination queue very safely. if(next(val) ~= nil) then redis.call('zremrangebyrank', KEYS[1], 0, #val - 1) for i = 1, #val, 100 do redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val))) end end return val LUA; return $this->client->eval( $luaScript, 2, $this->getRetryZsetNameWithPrefix($queue), $this->getQueueNameWithPrefix($queue), time() ); }
php
protected function migrateRetryJobs($queue) { $luaScript = <<<LUA -- Get all of the jobs with an expired "score"... local val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1]) -- If we have values in the array, we will remove them from the first queue -- and add them onto the destination queue in chunks of 100, which moves -- all of the appropriate jobs onto the destination queue very safely. if(next(val) ~= nil) then redis.call('zremrangebyrank', KEYS[1], 0, #val - 1) for i = 1, #val, 100 do redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val))) end end return val LUA; return $this->client->eval( $luaScript, 2, $this->getRetryZsetNameWithPrefix($queue), $this->getQueueNameWithPrefix($queue), time() ); }
[ "protected", "function", "migrateRetryJobs", "(", "$", "queue", ")", "{", "$", "luaScript", "=", " <<<LUA\n-- Get all of the jobs with an expired \"score\"...\nlocal val = redis.call('zrangebyscore', KEYS[1], '-inf', ARGV[1])\n\n-- If we have values in the array, we will remove them from the first queue\n-- and add them onto the destination queue in chunks of 100, which moves\n-- all of the appropriate jobs onto the destination queue very safely.\nif(next(val) ~= nil) then\n redis.call('zremrangebyrank', KEYS[1], 0, #val - 1)\n\n for i = 1, #val, 100 do\n redis.call('rpush', KEYS[2], unpack(val, i, math.min(i+99, #val)))\n end\nend\n\nreturn val\nLUA", ";", "return", "$", "this", "->", "client", "->", "eval", "(", "$", "luaScript", ",", "2", ",", "$", "this", "->", "getRetryZsetNameWithPrefix", "(", "$", "queue", ")", ",", "$", "this", "->", "getQueueNameWithPrefix", "(", "$", "queue", ")", ",", "time", "(", ")", ")", ";", "}" ]
migrate the retry jobs of a queue @param string $queue @return array
[ "migrate", "the", "retry", "jobs", "of", "a", "queue" ]
10541f9694b5d9759329ae908033dd3097ce6923
https://github.com/wangsir0624/queue/blob/10541f9694b5d9759329ae908033dd3097ce6923/src/RedisQueue.php#L91-L118
13,342
wangsir0624/queue
src/RedisQueue.php
RedisQueue.addJobToRetrySet
protected function addJobToRetrySet($job, $retryAt) { return (bool)$this->client->zadd( $this->getRetryZsetNameWithPrefix($job->getQueue()), $retryAt, serialize($job) ); }
php
protected function addJobToRetrySet($job, $retryAt) { return (bool)$this->client->zadd( $this->getRetryZsetNameWithPrefix($job->getQueue()), $retryAt, serialize($job) ); }
[ "protected", "function", "addJobToRetrySet", "(", "$", "job", ",", "$", "retryAt", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "client", "->", "zadd", "(", "$", "this", "->", "getRetryZsetNameWithPrefix", "(", "$", "job", "->", "getQueue", "(", ")", ")", ",", "$", "retryAt", ",", "serialize", "(", "$", "job", ")", ")", ";", "}" ]
add job to the retry set @param AbstractJob $job @param int $retryAt @return bool
[ "add", "job", "to", "the", "retry", "set" ]
10541f9694b5d9759329ae908033dd3097ce6923
https://github.com/wangsir0624/queue/blob/10541f9694b5d9759329ae908033dd3097ce6923/src/RedisQueue.php#L126-L133
13,343
csun-metalab/laravel-directory-authentication
src/Authentication/Factories/LDAPPasswordFactory.php
LDAPPasswordFactory.SSHA
public static function SSHA($password, $salt=null) { if(empty($salt)) { if(function_exists('openssl_random_pseudo_bytes')) { // salts should be four bytes $salt = bin2hex(openssl_random_pseudo_bytes(4)); } else { throw new Exception( "You must have the openssl extension installed and enabled to use a random salt" ); } } return "{SSHA}" . base64_encode(sha1($password . $salt, true) . $salt); }
php
public static function SSHA($password, $salt=null) { if(empty($salt)) { if(function_exists('openssl_random_pseudo_bytes')) { // salts should be four bytes $salt = bin2hex(openssl_random_pseudo_bytes(4)); } else { throw new Exception( "You must have the openssl extension installed and enabled to use a random salt" ); } } return "{SSHA}" . base64_encode(sha1($password . $salt, true) . $salt); }
[ "public", "static", "function", "SSHA", "(", "$", "password", ",", "$", "salt", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "salt", ")", ")", "{", "if", "(", "function_exists", "(", "'openssl_random_pseudo_bytes'", ")", ")", "{", "// salts should be four bytes", "$", "salt", "=", "bin2hex", "(", "openssl_random_pseudo_bytes", "(", "4", ")", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "\"You must have the openssl extension installed and enabled to use a random salt\"", ")", ";", "}", "}", "return", "\"{SSHA}\"", ".", "base64_encode", "(", "sha1", "(", "$", "password", ".", "$", "salt", ",", "true", ")", ".", "$", "salt", ")", ";", "}" ]
Generates and returns a new password as a SSHA hash for use in LDAP. If the salt is not specified, one will be generated using the openssl extension and have a length of four bytes. @param string $password The plaintext password to hash @param string $salt Optional salt for the algorithm @return string
[ "Generates", "and", "returns", "a", "new", "password", "as", "a", "SSHA", "hash", "for", "use", "in", "LDAP", ".", "If", "the", "salt", "is", "not", "specified", "one", "will", "be", "generated", "using", "the", "openssl", "extension", "and", "have", "a", "length", "of", "four", "bytes", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Factories/LDAPPasswordFactory.php#L23-L37
13,344
dphn/ScContent
src/ScContent/Controller/Back/ArticleController.php
ArticleController.editAction
public function editAction() { $id = $this->params()->fromRoute('id'); if (! is_numeric($id)) { $this->flashMessenger()->addMessage( $this->scTranslate('The article identifier was not specified.') ); return $this->redirect() ->toRoute('sc-admin/content-manager') ->setStatusCode(303); } try { $article = $this->getArticleService()->getArticle($id); } catch (RuntimeException $e) { $this->flashMessenger()->addMessage($e->getMessage()); return $this->redirect() ->toRoute('sc-admin/content-manager') ->setStatusCode(303); } $form = $this->getArticleForm(); $form->setAttribute( 'action', $this->url()->fromRoute('sc-admin/article/edit', ['id' => $id]) ); $form->bind($article); if ($this->getRequest()->isPost()) { $form->setData($this->getRequest()->getPost()); if ($form->isValid()) { $this->getArticleService()->saveContent($form->getData()); } } return new ViewModel([ 'content' => $article, 'form' => $form, ]); }
php
public function editAction() { $id = $this->params()->fromRoute('id'); if (! is_numeric($id)) { $this->flashMessenger()->addMessage( $this->scTranslate('The article identifier was not specified.') ); return $this->redirect() ->toRoute('sc-admin/content-manager') ->setStatusCode(303); } try { $article = $this->getArticleService()->getArticle($id); } catch (RuntimeException $e) { $this->flashMessenger()->addMessage($e->getMessage()); return $this->redirect() ->toRoute('sc-admin/content-manager') ->setStatusCode(303); } $form = $this->getArticleForm(); $form->setAttribute( 'action', $this->url()->fromRoute('sc-admin/article/edit', ['id' => $id]) ); $form->bind($article); if ($this->getRequest()->isPost()) { $form->setData($this->getRequest()->getPost()); if ($form->isValid()) { $this->getArticleService()->saveContent($form->getData()); } } return new ViewModel([ 'content' => $article, 'form' => $form, ]); }
[ "public", "function", "editAction", "(", ")", "{", "$", "id", "=", "$", "this", "->", "params", "(", ")", "->", "fromRoute", "(", "'id'", ")", ";", "if", "(", "!", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "this", "->", "flashMessenger", "(", ")", "->", "addMessage", "(", "$", "this", "->", "scTranslate", "(", "'The article identifier was not specified.'", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", ")", "->", "toRoute", "(", "'sc-admin/content-manager'", ")", "->", "setStatusCode", "(", "303", ")", ";", "}", "try", "{", "$", "article", "=", "$", "this", "->", "getArticleService", "(", ")", "->", "getArticle", "(", "$", "id", ")", ";", "}", "catch", "(", "RuntimeException", "$", "e", ")", "{", "$", "this", "->", "flashMessenger", "(", ")", "->", "addMessage", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", ")", "->", "toRoute", "(", "'sc-admin/content-manager'", ")", "->", "setStatusCode", "(", "303", ")", ";", "}", "$", "form", "=", "$", "this", "->", "getArticleForm", "(", ")", ";", "$", "form", "->", "setAttribute", "(", "'action'", ",", "$", "this", "->", "url", "(", ")", "->", "fromRoute", "(", "'sc-admin/article/edit'", ",", "[", "'id'", "=>", "$", "id", "]", ")", ")", ";", "$", "form", "->", "bind", "(", "$", "article", ")", ";", "if", "(", "$", "this", "->", "getRequest", "(", ")", "->", "isPost", "(", ")", ")", "{", "$", "form", "->", "setData", "(", "$", "this", "->", "getRequest", "(", ")", "->", "getPost", "(", ")", ")", ";", "if", "(", "$", "form", "->", "isValid", "(", ")", ")", "{", "$", "this", "->", "getArticleService", "(", ")", "->", "saveContent", "(", "$", "form", "->", "getData", "(", ")", ")", ";", "}", "}", "return", "new", "ViewModel", "(", "[", "'content'", "=>", "$", "article", ",", "'form'", "=>", "$", "form", ",", "]", ")", ";", "}" ]
Edit File. @return \Zend\Stdlib\ResponseInterface|\Zend\View\Model\ViewModel
[ "Edit", "File", "." ]
9dd5732490c45fd788b96cedf7b3c7adfacb30d2
https://github.com/dphn/ScContent/blob/9dd5732490c45fd788b96cedf7b3c7adfacb30d2/src/ScContent/Controller/Back/ArticleController.php#L70-L108
13,345
christophe-brachet/aspi-framework
src/Framework/Routing/RouteGenerator/StrictLocaleRouteGenerator.php
StrictLocaleRouteGenerator.generateRoutes
public function generateRoutes($name, array $localesWithPaths, Route $baseRoute) { $this->assertLocalesAreSupported(array_keys($localesWithPaths)); return $this->routeGenerator->generateRoutes($name, $localesWithPaths, $baseRoute); }
php
public function generateRoutes($name, array $localesWithPaths, Route $baseRoute) { $this->assertLocalesAreSupported(array_keys($localesWithPaths)); return $this->routeGenerator->generateRoutes($name, $localesWithPaths, $baseRoute); }
[ "public", "function", "generateRoutes", "(", "$", "name", ",", "array", "$", "localesWithPaths", ",", "Route", "$", "baseRoute", ")", "{", "$", "this", "->", "assertLocalesAreSupported", "(", "array_keys", "(", "$", "localesWithPaths", ")", ")", ";", "return", "$", "this", "->", "routeGenerator", "->", "generateRoutes", "(", "$", "name", ",", "$", "localesWithPaths", ",", "$", "baseRoute", ")", ";", "}" ]
Generate localized versions of the given route. @param $name @param array $localesWithPaths @param Route $baseRoute @return RouteCollection
[ "Generate", "localized", "versions", "of", "the", "given", "route", "." ]
17a36c8a8582e0b8d8bff7087590c09a9bd4af1e
https://github.com/christophe-brachet/aspi-framework/blob/17a36c8a8582e0b8d8bff7087590c09a9bd4af1e/src/Framework/Routing/RouteGenerator/StrictLocaleRouteGenerator.php#L60-L64
13,346
DevGroup-ru/yii2-data-structure-tools
src/traits/PropertiesTrait.php
PropertiesTrait.buildTableName
protected static function buildTableName($suffix = '') { if (true === empty(static::$tablePrefix)) { if (strpos(static::tableName(), '}}') !== false) { $name = str_replace('}}', $suffix . '}}', static::tableName()); } else { $name = static::tableName() . $suffix; } } else { $name = static::$tablePrefix . $suffix; } return $name; }
php
protected static function buildTableName($suffix = '') { if (true === empty(static::$tablePrefix)) { if (strpos(static::tableName(), '}}') !== false) { $name = str_replace('}}', $suffix . '}}', static::tableName()); } else { $name = static::tableName() . $suffix; } } else { $name = static::$tablePrefix . $suffix; } return $name; }
[ "protected", "static", "function", "buildTableName", "(", "$", "suffix", "=", "''", ")", "{", "if", "(", "true", "===", "empty", "(", "static", "::", "$", "tablePrefix", ")", ")", "{", "if", "(", "strpos", "(", "static", "::", "tableName", "(", ")", ",", "'}}'", ")", "!==", "false", ")", "{", "$", "name", "=", "str_replace", "(", "'}}'", ",", "$", "suffix", ".", "'}}'", ",", "static", "::", "tableName", "(", ")", ")", ";", "}", "else", "{", "$", "name", "=", "static", "::", "tableName", "(", ")", ".", "$", "suffix", ";", "}", "}", "else", "{", "$", "name", "=", "static", "::", "$", "tablePrefix", ".", "$", "suffix", ";", "}", "return", "$", "name", ";", "}" ]
Build a valid table name with suffix @param string $suffix @return mixed|string
[ "Build", "a", "valid", "table", "name", "with", "suffix" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/traits/PropertiesTrait.php#L45-L57
13,347
DevGroup-ru/yii2-data-structure-tools
src/traits/PropertiesTrait.php
PropertiesTrait.propertiesRules
public function propertiesRules() { $rules = []; $this->ensurePropertiesAttributes(); if (empty($this->propertiesIds) === false) { foreach ($this->propertiesIds as $propertyId) { /** @var Property $property */ $property = Property::findById($propertyId); $handler = $property->handler(); $rules = ArrayHelper::merge($rules, $handler->getValidationRules($property)); if ($property->isRequired()) { $rules = ArrayHelper::merge($rules, [[$property->key, 'required']]); } } } return $rules; }
php
public function propertiesRules() { $rules = []; $this->ensurePropertiesAttributes(); if (empty($this->propertiesIds) === false) { foreach ($this->propertiesIds as $propertyId) { /** @var Property $property */ $property = Property::findById($propertyId); $handler = $property->handler(); $rules = ArrayHelper::merge($rules, $handler->getValidationRules($property)); if ($property->isRequired()) { $rules = ArrayHelper::merge($rules, [[$property->key, 'required']]); } } } return $rules; }
[ "public", "function", "propertiesRules", "(", ")", "{", "$", "rules", "=", "[", "]", ";", "$", "this", "->", "ensurePropertiesAttributes", "(", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "propertiesIds", ")", "===", "false", ")", "{", "foreach", "(", "$", "this", "->", "propertiesIds", "as", "$", "propertyId", ")", "{", "/** @var Property $property */", "$", "property", "=", "Property", "::", "findById", "(", "$", "propertyId", ")", ";", "$", "handler", "=", "$", "property", "->", "handler", "(", ")", ";", "$", "rules", "=", "ArrayHelper", "::", "merge", "(", "$", "rules", ",", "$", "handler", "->", "getValidationRules", "(", "$", "property", ")", ")", ";", "if", "(", "$", "property", "->", "isRequired", "(", ")", ")", "{", "$", "rules", "=", "ArrayHelper", "::", "merge", "(", "$", "rules", ",", "[", "[", "$", "property", "->", "key", ",", "'required'", "]", "]", ")", ";", "}", "}", "}", "return", "$", "rules", ";", "}" ]
Array of validation rules for properties @return array
[ "Array", "of", "validation", "rules", "for", "properties" ]
a5b24d7c0b24d4b0d58cacd91ec7fd876e979097
https://github.com/DevGroup-ru/yii2-data-structure-tools/blob/a5b24d7c0b24d4b0d58cacd91ec7fd876e979097/src/traits/PropertiesTrait.php#L214-L232
13,348
liip/LiipDrupalConnectorModule
src/Liip/Drupal/Modules/DrupalConnector/Bootstrap.php
Bootstrap.drupal_set_message
public function drupal_set_message($message = null, $type = 'status', $repeat = true) { return drupal_set_message($message, $type, $repeat); }
php
public function drupal_set_message($message = null, $type = 'status', $repeat = true) { return drupal_set_message($message, $type, $repeat); }
[ "public", "function", "drupal_set_message", "(", "$", "message", "=", "null", ",", "$", "type", "=", "'status'", ",", "$", "repeat", "=", "true", ")", "{", "return", "drupal_set_message", "(", "$", "message", ",", "$", "type", ",", "$", "repeat", ")", ";", "}" ]
Sets a message to display to the user. Messages are stored in a session variable and displayed in page.tpl.php via the $messages theme variable. Example usage: @code drupal_set_message(t('An error occurred and processing did not complete.'), 'error'); @endcode @param string $message (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period. @param string $type (optional) The message's type. Defaults to 'status'. These values are supported: - 'status' - 'warning' - 'error' @param bool $repeat (optional) If this is FALSE and the message is already set, then the message won't be repeated. Defaults to TRUE. @return array|null A multidimensional array with keys corresponding to the set message types. The indexed array values of each contain the set messages for that type. Or, if there are no messages set, the function returns NULL. @see drupal_get_messages() @see theme_status_messages()
[ "Sets", "a", "message", "to", "display", "to", "the", "user", "." ]
6ba161ef0d3a27c108e533f1adbea22ed73b78ce
https://github.com/liip/LiipDrupalConnectorModule/blob/6ba161ef0d3a27c108e533f1adbea22ed73b78ce/src/Liip/Drupal/Modules/DrupalConnector/Bootstrap.php#L103-L106
13,349
liip/LiipDrupalConnectorModule
src/Liip/Drupal/Modules/DrupalConnector/Bootstrap.php
Bootstrap.&
public function &drupal_static($name, $default_value = null, $reset = false) { return drupal_static($name, $default_value, $reset); }
php
public function &drupal_static($name, $default_value = null, $reset = false) { return drupal_static($name, $default_value, $reset); }
[ "public", "function", "&", "drupal_static", "(", "$", "name", ",", "$", "default_value", "=", "null", ",", "$", "reset", "=", "false", ")", "{", "return", "drupal_static", "(", "$", "name", ",", "$", "default_value", ",", "$", "reset", ")", ";", "}" ]
Provides central static variable storage. All functions requiring a static variable to persist or cache data within a single page request are encouraged to use this function unless it is absolutely certain that the static variable will not need to be reset during the page request. By centralizing static variable storage through this function, other functions can rely on a consistent API for resetting any other function's static variables. Example: @code function language_list($field = 'language') { $languages = &drupal_static(__FUNCTION__); if (!isset($languages)) { // If this function is being called for the first time after a reset, // query the database and execute any other code needed to retrieve // information about the supported languages. ... } if (!isset($languages[$field])) { // If this function is being called for the first time for a particular // index field, then execute code needed to index the information already // available in $languages by the desired field. ... } // Subsequent invocations of this function for a particular index field // skip the above two code blocks and quickly return the already indexed // information. return $languages[$field]; } function locale_translate_overview_screen() { // When building the content for the translations overview page, make // sure to get completely fresh information about the supported languages. drupal_static_reset('language_list'); ... } @endcode In a few cases, a function can have certainty that there is no legitimate use-case for resetting that function's static variable. This is rare, because when writing a function, it's hard to forecast all the situations in which it will be used. A guideline is that if a function's static variable does not depend on any information outside of the function that might change during a single page request, then it's ok to use the "static" keyword instead of the drupal_static() function. Example: @code function actions_do(...) { // $stack tracks the number of recursive calls. static $stack; $stack++; if ($stack > variable_get('actions_max_stack', 35)) { ... return; } ... $stack--; } @endcode In a few cases, a function needs a resettable static variable, but the function is called many times (100+) during a single page request, so every microsecond of execution time that can be removed from the function counts. These functions can use a more cumbersome, but faster variant of calling drupal_static(). It works by storing the reference returned by drupal_static() in the calling function's own static variable, thereby removing the need to call drupal_static() for each iteration of the function. Conceptually, it replaces: @code $foo = &drupal_static(__FUNCTION__); @endcode with: @code // Unfortunately, this does not work. static $foo = &drupal_static(__FUNCTION__); @endcode However, the above line of code does not work, because PHP only allows static variables to be initializied by literal values, and does not allow static variables to be assigned to references. - http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static - http://php.net/manual/en/language.variables.scope.php#language.variables.scope.references The example below shows the syntax needed to work around both limitations. For benchmarks and more information, see http://drupal.org/node/619666. Example: @code function user_access($string, $account = null) { // Use the advanced drupal_static() pattern, since this is called very often. static $drupal_static_fast; if (!isset($drupal_static_fast)) { $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__); } $perm = &$drupal_static_fast['perm']; ... } @endcode @param string $name Globally unique name for the variable. For a function with only one static, variable, the function name (e.g. via the PHP magic __FUNCTION__ constant) is recommended. For a function with multiple static variables add a distinguishing suffix to the function name for each one. @param mixed $default_value Optional default value. @param boolean $reset true to reset a specific named variable, or all variables if $name is null. Resetting every variable should only be used, for example, for running unit tests with a clean environment. Should be used only though via function drupal_static_reset() and the return value should not be used in this case. @return mixed Returns a variable by reference. @see drupal_static_reset()
[ "Provides", "central", "static", "variable", "storage", "." ]
6ba161ef0d3a27c108e533f1adbea22ed73b78ce
https://github.com/liip/LiipDrupalConnectorModule/blob/6ba161ef0d3a27c108e533f1adbea22ed73b78ce/src/Liip/Drupal/Modules/DrupalConnector/Bootstrap.php#L220-L223
13,350
taskforcedev/laravel-support
src/Http/Controllers/Controller.php
Controller.getModel
public function getModel($model) { /* Get the namespace */ $ns = $this->getAppNamespace(); if ($ns) { /* Try laravel default convention (models in the app folder). */ $qm = $ns . $model; if (class_exists($qm)) { return new $qm; } /* Try secondary convention of having a models directory. */ $qm = $ns . 'Models' . '\\' . $model; if (class_exists($qm)) { return new $qm; } } return false; }
php
public function getModel($model) { /* Get the namespace */ $ns = $this->getAppNamespace(); if ($ns) { /* Try laravel default convention (models in the app folder). */ $qm = $ns . $model; if (class_exists($qm)) { return new $qm; } /* Try secondary convention of having a models directory. */ $qm = $ns . 'Models' . '\\' . $model; if (class_exists($qm)) { return new $qm; } } return false; }
[ "public", "function", "getModel", "(", "$", "model", ")", "{", "/* Get the namespace */", "$", "ns", "=", "$", "this", "->", "getAppNamespace", "(", ")", ";", "if", "(", "$", "ns", ")", "{", "/* Try laravel default convention (models in the app folder). */", "$", "qm", "=", "$", "ns", ".", "$", "model", ";", "if", "(", "class_exists", "(", "$", "qm", ")", ")", "{", "return", "new", "$", "qm", ";", "}", "/* Try secondary convention of having a models directory. */", "$", "qm", "=", "$", "ns", ".", "'Models'", ".", "'\\\\'", ".", "$", "model", ";", "if", "(", "class_exists", "(", "$", "qm", ")", ")", "{", "return", "new", "$", "qm", ";", "}", "}", "return", "false", ";", "}" ]
Attempt to get an apps model from namespace. @param $model @return bool
[ "Attempt", "to", "get", "an", "apps", "model", "from", "namespace", "." ]
fdfa90ca10ffd57bc6f7aca20d2f3db7dc259221
https://github.com/taskforcedev/laravel-support/blob/fdfa90ca10ffd57bc6f7aca20d2f3db7dc259221/src/Http/Controllers/Controller.php#L96-L113
13,351
wpup/digster
src/extensions/class-filter-extensions.php
Filter_Extensions.apply_filters
public function apply_filters() { $args = func_get_args(); $tag = current( array_splice( $args, 1, 1 ) ); return apply_filters_ref_array( $tag, $args ); }
php
public function apply_filters() { $args = func_get_args(); $tag = current( array_splice( $args, 1, 1 ) ); return apply_filters_ref_array( $tag, $args ); }
[ "public", "function", "apply_filters", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "tag", "=", "current", "(", "array_splice", "(", "$", "args", ",", "1", ",", "1", ")", ")", ";", "return", "apply_filters_ref_array", "(", "$", "tag", ",", "$", "args", ")", ";", "}" ]
Call WordPress filter. @return mixed
[ "Call", "WordPress", "filter", "." ]
9ef9626ce82673af698bc0976d6c38a532e4a6d9
https://github.com/wpup/digster/blob/9ef9626ce82673af698bc0976d6c38a532e4a6d9/src/extensions/class-filter-extensions.php#L12-L16
13,352
peridot-php/peridot-httpkernel-plugin
src/HttpKernelPlugin.php
HttpKernelPlugin.onRunnerStart
public function onRunnerStart() { $rootSuite = Context::getInstance()->getCurrentSuite(); $rootSuite->getScope()->peridotAddChildScope($this->scope); }
php
public function onRunnerStart() { $rootSuite = Context::getInstance()->getCurrentSuite(); $rootSuite->getScope()->peridotAddChildScope($this->scope); }
[ "public", "function", "onRunnerStart", "(", ")", "{", "$", "rootSuite", "=", "Context", "::", "getInstance", "(", ")", "->", "getCurrentSuite", "(", ")", ";", "$", "rootSuite", "->", "getScope", "(", ")", "->", "peridotAddChildScope", "(", "$", "this", "->", "scope", ")", ";", "}" ]
When the runner starts we will mix in the http kernel scope into the root suite, thereby making it available EVERYWHERE.
[ "When", "the", "runner", "starts", "we", "will", "mix", "in", "the", "http", "kernel", "scope", "into", "the", "root", "suite", "thereby", "making", "it", "available", "EVERYWHERE", "." ]
db53e0b756f92da9423e5bfc4e9c36affa55473f
https://github.com/peridot-php/peridot-httpkernel-plugin/blob/db53e0b756f92da9423e5bfc4e9c36affa55473f/src/HttpKernelPlugin.php#L35-L39
13,353
skeeks-cms/cms-rbac
src/controllers/AdminPermissionController.php
AdminPermissionController.actionDelete
public function actionDelete() { $rr = new RequestResponse(); if ($rr->isRequestAjaxPost()) { try { $model = $this->model; $id = $model->name; $model = $this->findModel($id); if (!in_array($model->item->name, CmsManager::protectedPermissions())) { if (\Yii::$app->getAuthManager()->remove($model->item)) { $rr->message = \Yii::t('app', 'Record deleted successfully'); $rr->success = true; } else { $rr->message = \Yii::t('app', 'Record deleted unsuccessfully'); $rr->success = false; } } else { $rr->message = \Yii::t('app', 'This entry can not be deleted!'); $rr->success = false; } } catch (\Exception $e) { $rr->message = $e->getMessage(); $rr->success = false; } return (array)$rr; } }
php
public function actionDelete() { $rr = new RequestResponse(); if ($rr->isRequestAjaxPost()) { try { $model = $this->model; $id = $model->name; $model = $this->findModel($id); if (!in_array($model->item->name, CmsManager::protectedPermissions())) { if (\Yii::$app->getAuthManager()->remove($model->item)) { $rr->message = \Yii::t('app', 'Record deleted successfully'); $rr->success = true; } else { $rr->message = \Yii::t('app', 'Record deleted unsuccessfully'); $rr->success = false; } } else { $rr->message = \Yii::t('app', 'This entry can not be deleted!'); $rr->success = false; } } catch (\Exception $e) { $rr->message = $e->getMessage(); $rr->success = false; } return (array)$rr; } }
[ "public", "function", "actionDelete", "(", ")", "{", "$", "rr", "=", "new", "RequestResponse", "(", ")", ";", "if", "(", "$", "rr", "->", "isRequestAjaxPost", "(", ")", ")", "{", "try", "{", "$", "model", "=", "$", "this", "->", "model", ";", "$", "id", "=", "$", "model", "->", "name", ";", "$", "model", "=", "$", "this", "->", "findModel", "(", "$", "id", ")", ";", "if", "(", "!", "in_array", "(", "$", "model", "->", "item", "->", "name", ",", "CmsManager", "::", "protectedPermissions", "(", ")", ")", ")", "{", "if", "(", "\\", "Yii", "::", "$", "app", "->", "getAuthManager", "(", ")", "->", "remove", "(", "$", "model", "->", "item", ")", ")", "{", "$", "rr", "->", "message", "=", "\\", "Yii", "::", "t", "(", "'app'", ",", "'Record deleted successfully'", ")", ";", "$", "rr", "->", "success", "=", "true", ";", "}", "else", "{", "$", "rr", "->", "message", "=", "\\", "Yii", "::", "t", "(", "'app'", ",", "'Record deleted unsuccessfully'", ")", ";", "$", "rr", "->", "success", "=", "false", ";", "}", "}", "else", "{", "$", "rr", "->", "message", "=", "\\", "Yii", "::", "t", "(", "'app'", ",", "'This entry can not be deleted!'", ")", ";", "$", "rr", "->", "success", "=", "false", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "rr", "->", "message", "=", "$", "e", "->", "getMessage", "(", ")", ";", "$", "rr", "->", "success", "=", "false", ";", "}", "return", "(", "array", ")", "$", "rr", ";", "}", "}" ]
Deletes an existing Game model. If deletion is successful, the browser will be redirected to the 'index' page. @return mixed
[ "Deletes", "an", "existing", "Game", "model", ".", "If", "deletion", "is", "successful", "the", "browser", "will", "be", "redirected", "to", "the", "index", "page", "." ]
1e5b17c1eb405f1ea87279da2ce56162c0281def
https://github.com/skeeks-cms/cms-rbac/blob/1e5b17c1eb405f1ea87279da2ce56162c0281def/src/controllers/AdminPermissionController.php#L281-L307
13,354
dphn/ScContent
src/ScContent/Migration/Schema.php
Schema.down
public function down() { try { $this->buildMapper( 'ScContent.Migration.MapperBase.Content' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Search' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Garbage' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Layout' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Widgets' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Users' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Roles' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.RolesLinker' ) ->down(); } catch (Exception $e) { // } }
php
public function down() { try { $this->buildMapper( 'ScContent.Migration.MapperBase.Content' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Search' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Garbage' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Layout' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Widgets' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Users' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.Roles' ) ->down(); } catch (Exception $e) { // } try { $this->buildMapper( 'ScContent.Migration.MapperBase.RolesLinker' ) ->down(); } catch (Exception $e) { // } }
[ "public", "function", "down", "(", ")", "{", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Content'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Search'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Garbage'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Layout'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Widgets'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Users'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.Roles'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "try", "{", "$", "this", "->", "buildMapper", "(", "'ScContent.Migration.MapperBase.RolesLinker'", ")", "->", "down", "(", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "//", "}", "}" ]
Remove migration from the database. @return void
[ "Remove", "migration", "from", "the", "database", "." ]
9dd5732490c45fd788b96cedf7b3c7adfacb30d2
https://github.com/dphn/ScContent/blob/9dd5732490c45fd788b96cedf7b3c7adfacb30d2/src/ScContent/Migration/Schema.php#L87-L160
13,355
MissAllSunday/Ohara
src/Suki/Config.php
Config.get
public function get($name = '') { // This needs to be extended by somebody else! if(!$this->_app->name) return []; // Not defined huh? if (!$this->_config) $this->getConfig(); return $name ? (isset($this->_config['_'. $name]) ? $this->_config['_'. $name] : []) : $this->_config; }
php
public function get($name = '') { // This needs to be extended by somebody else! if(!$this->_app->name) return []; // Not defined huh? if (!$this->_config) $this->getConfig(); return $name ? (isset($this->_config['_'. $name]) ? $this->_config['_'. $name] : []) : $this->_config; }
[ "public", "function", "get", "(", "$", "name", "=", "''", ")", "{", "// This needs to be extended by somebody else!", "if", "(", "!", "$", "this", "->", "_app", "->", "name", ")", "return", "[", "]", ";", "// Not defined huh?", "if", "(", "!", "$", "this", "->", "_config", ")", "$", "this", "->", "getConfig", "(", ")", ";", "return", "$", "name", "?", "(", "isset", "(", "$", "this", "->", "_config", "[", "'_'", ".", "$", "name", "]", ")", "?", "$", "this", "->", "_config", "[", "'_'", ".", "$", "name", "]", ":", "[", "]", ")", ":", "$", "this", "->", "_config", ";", "}" ]
Gets a specific mod config array. @access public @param string $name The name of an specific setting, if empty it will return the entire array. @return array
[ "Gets", "a", "specific", "mod", "config", "array", "." ]
7753500cde1d51a0d7b37593aeaf2fc05fefd903
https://github.com/MissAllSunday/Ohara/blob/7753500cde1d51a0d7b37593aeaf2fc05fefd903/src/Suki/Config.php#L62-L73
13,356
cicada/cicada
src/Routing/Route.php
Route.matches
public function matches($url) { $pattern = $this->getRegexPattern(); if (preg_match($pattern, $url, $matches)) { // Remove entries with int keys to filter out only named matches foreach ($matches as $key => $value) { if (is_int($key)) { unset($matches[$key]); } } return $matches; } return false; }
php
public function matches($url) { $pattern = $this->getRegexPattern(); if (preg_match($pattern, $url, $matches)) { // Remove entries with int keys to filter out only named matches foreach ($matches as $key => $value) { if (is_int($key)) { unset($matches[$key]); } } return $matches; } return false; }
[ "public", "function", "matches", "(", "$", "url", ")", "{", "$", "pattern", "=", "$", "this", "->", "getRegexPattern", "(", ")", ";", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "url", ",", "$", "matches", ")", ")", "{", "// Remove entries with int keys to filter out only named matches", "foreach", "(", "$", "matches", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "unset", "(", "$", "matches", "[", "$", "key", "]", ")", ";", "}", "}", "return", "$", "matches", ";", "}", "return", "false", ";", "}" ]
Checks whether this route matches the given url.
[ "Checks", "whether", "this", "route", "matches", "the", "given", "url", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Routing/Route.php#L92-L109
13,357
cicada/cicada
src/Routing/Route.php
Route.run
public function run(Application $app, Request $request, array $arguments = []) { return $this->processRequest($app, $request, $this->callback, $arguments); }
php
public function run(Application $app, Request $request, array $arguments = []) { return $this->processRequest($app, $request, $this->callback, $arguments); }
[ "public", "function", "run", "(", "Application", "$", "app", ",", "Request", "$", "request", ",", "array", "$", "arguments", "=", "[", "]", ")", "{", "return", "$", "this", "->", "processRequest", "(", "$", "app", ",", "$", "request", ",", "$", "this", "->", "callback", ",", "$", "arguments", ")", ";", "}" ]
Processes the Request and returns a Response. @throws UnexpectedValueException If the route callback returns a value which is not a string or Response object.
[ "Processes", "the", "Request", "and", "returns", "a", "Response", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Routing/Route.php#L117-L120
13,358
cicada/cicada
src/Routing/Route.php
Route.method
public function method($method) { if (!in_array($method, $this->methods)) { throw new \InvalidArgumentException("Unknown HTTP method: $method"); } $this->method = $method; return $this; }
php
public function method($method) { if (!in_array($method, $this->methods)) { throw new \InvalidArgumentException("Unknown HTTP method: $method"); } $this->method = $method; return $this; }
[ "public", "function", "method", "(", "$", "method", ")", "{", "if", "(", "!", "in_array", "(", "$", "method", ",", "$", "this", "->", "methods", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unknown HTTP method: $method\"", ")", ";", "}", "$", "this", "->", "method", "=", "$", "method", ";", "return", "$", "this", ";", "}" ]
Sets the route's HTTP method.
[ "Sets", "the", "route", "s", "HTTP", "method", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Routing/Route.php#L174-L183
13,359
cicada/cicada
src/Routing/Route.php
Route.compileRegex
private function compileRegex() { // Prepend the prefix $path = $this->prefix . $this->path; $asserts = $this->asserts; // Replace placeholders in curly braces with named regex groups $callback = function ($matches) use ($asserts) { $name = $matches[1]; $pattern = isset($asserts[$name]) ? $asserts[$name] : ".+"; return "(?<$name>$pattern)"; }; $pattern = preg_replace_callback('/{([^}]+)}/', $callback, $path); // Avoid double slashes $pattern = preg_replace('/\/+/', '/', $pattern); // Escape slashes, used as delimiter in regex $pattern = str_replace('/', '\\/', $pattern); // Add start and and delimiters return "/^$pattern$/"; }
php
private function compileRegex() { // Prepend the prefix $path = $this->prefix . $this->path; $asserts = $this->asserts; // Replace placeholders in curly braces with named regex groups $callback = function ($matches) use ($asserts) { $name = $matches[1]; $pattern = isset($asserts[$name]) ? $asserts[$name] : ".+"; return "(?<$name>$pattern)"; }; $pattern = preg_replace_callback('/{([^}]+)}/', $callback, $path); // Avoid double slashes $pattern = preg_replace('/\/+/', '/', $pattern); // Escape slashes, used as delimiter in regex $pattern = str_replace('/', '\\/', $pattern); // Add start and and delimiters return "/^$pattern$/"; }
[ "private", "function", "compileRegex", "(", ")", "{", "// Prepend the prefix", "$", "path", "=", "$", "this", "->", "prefix", ".", "$", "this", "->", "path", ";", "$", "asserts", "=", "$", "this", "->", "asserts", ";", "// Replace placeholders in curly braces with named regex groups", "$", "callback", "=", "function", "(", "$", "matches", ")", "use", "(", "$", "asserts", ")", "{", "$", "name", "=", "$", "matches", "[", "1", "]", ";", "$", "pattern", "=", "isset", "(", "$", "asserts", "[", "$", "name", "]", ")", "?", "$", "asserts", "[", "$", "name", "]", ":", "\".+\"", ";", "return", "\"(?<$name>$pattern)\"", ";", "}", ";", "$", "pattern", "=", "preg_replace_callback", "(", "'/{([^}]+)}/'", ",", "$", "callback", ",", "$", "path", ")", ";", "// Avoid double slashes", "$", "pattern", "=", "preg_replace", "(", "'/\\/+/'", ",", "'/'", ",", "$", "pattern", ")", ";", "// Escape slashes, used as delimiter in regex", "$", "pattern", "=", "str_replace", "(", "'/'", ",", "'\\\\/'", ",", "$", "pattern", ")", ";", "// Add start and and delimiters", "return", "\"/^$pattern$/\"", ";", "}" ]
Compiles a regex pattern which matches this route.
[ "Compiles", "a", "regex", "pattern", "which", "matches", "this", "route", "." ]
5a54bd05dfa1df38e7aa3d704d270853f0329e13
https://github.com/cicada/cicada/blob/5a54bd05dfa1df38e7aa3d704d270853f0329e13/src/Routing/Route.php#L281-L306
13,360
leadthread/php-bitly
src/Bitly.php
Bitly.fixUrl
protected function fixUrl($url, $encode){ if(strpos($url, "http") !== 0){ $url = "http://".$url; } if($encode){ $url = urlencode($url); } return $url; }
php
protected function fixUrl($url, $encode){ if(strpos($url, "http") !== 0){ $url = "http://".$url; } if($encode){ $url = urlencode($url); } return $url; }
[ "protected", "function", "fixUrl", "(", "$", "url", ",", "$", "encode", ")", "{", "if", "(", "strpos", "(", "$", "url", ",", "\"http\"", ")", "!==", "0", ")", "{", "$", "url", "=", "\"http://\"", ".", "$", "url", ";", "}", "if", "(", "$", "encode", ")", "{", "$", "url", "=", "urlencode", "(", "$", "url", ")", ";", "}", "return", "$", "url", ";", "}" ]
Returns a corrected URL @param string $url The URL to modify @param boolean $encode Whether or not to encode the URL @return string The corrected URL
[ "Returns", "a", "corrected", "URL" ]
1ffdac16afbb192862f71abe2e263161727dee84
https://github.com/leadthread/php-bitly/blob/1ffdac16afbb192862f71abe2e263161727dee84/src/Bitly.php#L82-L92
13,361
leadthread/php-bitly
src/Bitly.php
Bitly.exec
protected function exec($url) { $client = $this->getRequest(); $response = $client->request('GET',$url); return $this->handleResponse($response->getBody()); }
php
protected function exec($url) { $client = $this->getRequest(); $response = $client->request('GET',$url); return $this->handleResponse($response->getBody()); }
[ "protected", "function", "exec", "(", "$", "url", ")", "{", "$", "client", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "response", "=", "$", "client", "->", "request", "(", "'GET'", ",", "$", "url", ")", ";", "return", "$", "this", "->", "handleResponse", "(", "$", "response", "->", "getBody", "(", ")", ")", ";", "}" ]
Executes a CURL request to the Bitly API @param string $url The URL to send to @return mixed The response data
[ "Executes", "a", "CURL", "request", "to", "the", "Bitly", "API" ]
1ffdac16afbb192862f71abe2e263161727dee84
https://github.com/leadthread/php-bitly/blob/1ffdac16afbb192862f71abe2e263161727dee84/src/Bitly.php#L121-L126
13,362
serverdensity/sd-php-wrapper
lib/serverdensity/Api/Services.php
Services.search
public function search($filter, $fields){ $param = array( 'filter' => json_encode($filter), 'fields' => json_encode($fields) ); return $this->get('inventory/resources/', $param); }
php
public function search($filter, $fields){ $param = array( 'filter' => json_encode($filter), 'fields' => json_encode($fields) ); return $this->get('inventory/resources/', $param); }
[ "public", "function", "search", "(", "$", "filter", ",", "$", "fields", ")", "{", "$", "param", "=", "array", "(", "'filter'", "=>", "json_encode", "(", "$", "filter", ")", ",", "'fields'", "=>", "json_encode", "(", "$", "fields", ")", ")", ";", "return", "$", "this", "->", "get", "(", "'inventory/resources/'", ",", "$", "param", ")", ";", "}" ]
Search a service @link https://developer.serverdensity.com/docs/searching-for-a-service @param array $filter an array of arrays of fields to filter on @param array $fields an array of fields to keep in search @return an array of arrays with all services.
[ "Search", "a", "service" ]
9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e
https://github.com/serverdensity/sd-php-wrapper/blob/9c742a9ee61e32a9bc4ed17b5fe0eca1f4c3015e/lib/serverdensity/Api/Services.php#L58-L65
13,363
chippyash/Strong-Type
src/Chippyash/Type/Number/Rational/RationalTypeFactory.php
RationalTypeFactory.fromFloat
public static function fromFloat($float, $tolerance = null) { if ($float instanceof FloatType) { $float = $float(); } if ($float == 0.0) { return new RationalType(new IntType(0), new IntType(1)); } if ($tolerance instanceof FloatType) { $tolerance = $tolerance(); } elseif (is_null($tolerance)) { $tolerance = self::$defaultTolerance; } $negative = ($float < 0); if ($negative) { $float = abs($float); } $num1 = 1; $num2 = 0; $den1 = 0; $den2 = 1; $oneOver = 1 / $float; do { $oneOver = 1 / $oneOver; $floor = floor($oneOver); $aux = $num1; $num1 = $floor * $num1 + $num2; $num2 = $aux; $aux = $den1; $den1 = $floor * $den1 + $den2; $den2 = $aux; $oneOver = $oneOver - $floor; } while (abs($float - $num1 / $den1) > $float * $tolerance); if ($negative) { $num1 *= -1; } return self::createCorrectRational($num1, $den1); }
php
public static function fromFloat($float, $tolerance = null) { if ($float instanceof FloatType) { $float = $float(); } if ($float == 0.0) { return new RationalType(new IntType(0), new IntType(1)); } if ($tolerance instanceof FloatType) { $tolerance = $tolerance(); } elseif (is_null($tolerance)) { $tolerance = self::$defaultTolerance; } $negative = ($float < 0); if ($negative) { $float = abs($float); } $num1 = 1; $num2 = 0; $den1 = 0; $den2 = 1; $oneOver = 1 / $float; do { $oneOver = 1 / $oneOver; $floor = floor($oneOver); $aux = $num1; $num1 = $floor * $num1 + $num2; $num2 = $aux; $aux = $den1; $den1 = $floor * $den1 + $den2; $den2 = $aux; $oneOver = $oneOver - $floor; } while (abs($float - $num1 / $den1) > $float * $tolerance); if ($negative) { $num1 *= -1; } return self::createCorrectRational($num1, $den1); }
[ "public", "static", "function", "fromFloat", "(", "$", "float", ",", "$", "tolerance", "=", "null", ")", "{", "if", "(", "$", "float", "instanceof", "FloatType", ")", "{", "$", "float", "=", "$", "float", "(", ")", ";", "}", "if", "(", "$", "float", "==", "0.0", ")", "{", "return", "new", "RationalType", "(", "new", "IntType", "(", "0", ")", ",", "new", "IntType", "(", "1", ")", ")", ";", "}", "if", "(", "$", "tolerance", "instanceof", "FloatType", ")", "{", "$", "tolerance", "=", "$", "tolerance", "(", ")", ";", "}", "elseif", "(", "is_null", "(", "$", "tolerance", ")", ")", "{", "$", "tolerance", "=", "self", "::", "$", "defaultTolerance", ";", "}", "$", "negative", "=", "(", "$", "float", "<", "0", ")", ";", "if", "(", "$", "negative", ")", "{", "$", "float", "=", "abs", "(", "$", "float", ")", ";", "}", "$", "num1", "=", "1", ";", "$", "num2", "=", "0", ";", "$", "den1", "=", "0", ";", "$", "den2", "=", "1", ";", "$", "oneOver", "=", "1", "/", "$", "float", ";", "do", "{", "$", "oneOver", "=", "1", "/", "$", "oneOver", ";", "$", "floor", "=", "floor", "(", "$", "oneOver", ")", ";", "$", "aux", "=", "$", "num1", ";", "$", "num1", "=", "$", "floor", "*", "$", "num1", "+", "$", "num2", ";", "$", "num2", "=", "$", "aux", ";", "$", "aux", "=", "$", "den1", ";", "$", "den1", "=", "$", "floor", "*", "$", "den1", "+", "$", "den2", ";", "$", "den2", "=", "$", "aux", ";", "$", "oneOver", "=", "$", "oneOver", "-", "$", "floor", ";", "}", "while", "(", "abs", "(", "$", "float", "-", "$", "num1", "/", "$", "den1", ")", ">", "$", "float", "*", "$", "tolerance", ")", ";", "if", "(", "$", "negative", ")", "{", "$", "num1", "*=", "-", "1", ";", "}", "return", "self", "::", "createCorrectRational", "(", "$", "num1", ",", "$", "den1", ")", ";", "}" ]
Create a rational number from a float or FloatType Use Continued Fractions method of determining the rational number @param float|FloatType $float @param float|FloatType $tolerance - Default is whatever is currently set but normally self::CF_DEFAULT_TOLERANCE @return \Chippyash\Type\Number\Rational\RationalType|\Chippyash\Type\Number\Rational\GMPRationalType @throws \InvalidArgumentException
[ "Create", "a", "rational", "number", "from", "a", "float", "or", "FloatType", "Use", "Continued", "Fractions", "method", "of", "determining", "the", "rational", "number" ]
9d364c10c68c10f768254fb25b0b1db3dbef6fa9
https://github.com/chippyash/Strong-Type/blob/9d364c10c68c10f768254fb25b0b1db3dbef6fa9/src/Chippyash/Type/Number/Rational/RationalTypeFactory.php#L94-L134
13,364
chippyash/Strong-Type
src/Chippyash/Type/Number/Rational/RationalTypeFactory.php
RationalTypeFactory.createCorrectRational
protected static function createCorrectRational($num, $den) { if (self::getRequiredType() == self::TYPE_GMP) { // @codeCoverageIgnoreStart return new GMPRationalType(new GMPIntType($num), new GMPIntType($den)); // @codeCoverageIgnoreEnd } return new RationalType(new IntType($num), new IntType($den)); }
php
protected static function createCorrectRational($num, $den) { if (self::getRequiredType() == self::TYPE_GMP) { // @codeCoverageIgnoreStart return new GMPRationalType(new GMPIntType($num), new GMPIntType($den)); // @codeCoverageIgnoreEnd } return new RationalType(new IntType($num), new IntType($den)); }
[ "protected", "static", "function", "createCorrectRational", "(", "$", "num", ",", "$", "den", ")", "{", "if", "(", "self", "::", "getRequiredType", "(", ")", "==", "self", "::", "TYPE_GMP", ")", "{", "// @codeCoverageIgnoreStart", "return", "new", "GMPRationalType", "(", "new", "GMPIntType", "(", "$", "num", ")", ",", "new", "GMPIntType", "(", "$", "den", ")", ")", ";", "// @codeCoverageIgnoreEnd", "}", "return", "new", "RationalType", "(", "new", "IntType", "(", "$", "num", ")", ",", "new", "IntType", "(", "$", "den", ")", ")", ";", "}" ]
Create and return the correct number type rational @param int $num @param int $den @return \Chippyash\Type\Number\Rational\RationalType|\Chippyash\Type\Number\Rational\GMPRationalType
[ "Create", "and", "return", "the", "correct", "number", "type", "rational" ]
9d364c10c68c10f768254fb25b0b1db3dbef6fa9
https://github.com/chippyash/Strong-Type/blob/9d364c10c68c10f768254fb25b0b1db3dbef6fa9/src/Chippyash/Type/Number/Rational/RationalTypeFactory.php#L197-L207
13,365
chippyash/Strong-Type
src/Chippyash/Type/Number/Rational/RationalTypeFactory.php
RationalTypeFactory.createFromNumericNumerator
private static function createFromNumericNumerator($numerator, $denominator) { if (is_null($denominator)) { return self::createCorrectRational($numerator, 1); } if (is_numeric($denominator)) { return self::createCorrectRational($numerator, $denominator); } if ($denominator instanceof IntType) { return self::createCorrectRational($numerator, $denominator()); } self::throwCreateException($numerator, $denominator); }
php
private static function createFromNumericNumerator($numerator, $denominator) { if (is_null($denominator)) { return self::createCorrectRational($numerator, 1); } if (is_numeric($denominator)) { return self::createCorrectRational($numerator, $denominator); } if ($denominator instanceof IntType) { return self::createCorrectRational($numerator, $denominator()); } self::throwCreateException($numerator, $denominator); }
[ "private", "static", "function", "createFromNumericNumerator", "(", "$", "numerator", ",", "$", "denominator", ")", "{", "if", "(", "is_null", "(", "$", "denominator", ")", ")", "{", "return", "self", "::", "createCorrectRational", "(", "$", "numerator", ",", "1", ")", ";", "}", "if", "(", "is_numeric", "(", "$", "denominator", ")", ")", "{", "return", "self", "::", "createCorrectRational", "(", "$", "numerator", ",", "$", "denominator", ")", ";", "}", "if", "(", "$", "denominator", "instanceof", "IntType", ")", "{", "return", "self", "::", "createCorrectRational", "(", "$", "numerator", ",", "$", "denominator", "(", ")", ")", ";", "}", "self", "::", "throwCreateException", "(", "$", "numerator", ",", "$", "denominator", ")", ";", "}" ]
Create where numerator is known to be numeric @param mixed $numerator Conforms to is_numeric() @param mixed $denominator @return GMPRationalType|RationalType @throws InvalidTypeException
[ "Create", "where", "numerator", "is", "known", "to", "be", "numeric" ]
9d364c10c68c10f768254fb25b0b1db3dbef6fa9
https://github.com/chippyash/Strong-Type/blob/9d364c10c68c10f768254fb25b0b1db3dbef6fa9/src/Chippyash/Type/Number/Rational/RationalTypeFactory.php#L219-L234
13,366
chippyash/Strong-Type
src/Chippyash/Type/Number/Rational/RationalTypeFactory.php
RationalTypeFactory.throwCreateException
private static function throwCreateException($numerator, $denominator) { $typeN = gettype($numerator); $typeD = gettype($denominator); throw new InvalidTypeException("{$typeN}:{$typeD} for Rational type construction"); }
php
private static function throwCreateException($numerator, $denominator) { $typeN = gettype($numerator); $typeD = gettype($denominator); throw new InvalidTypeException("{$typeN}:{$typeD} for Rational type construction"); }
[ "private", "static", "function", "throwCreateException", "(", "$", "numerator", ",", "$", "denominator", ")", "{", "$", "typeN", "=", "gettype", "(", "$", "numerator", ")", ";", "$", "typeD", "=", "gettype", "(", "$", "denominator", ")", ";", "throw", "new", "InvalidTypeException", "(", "\"{$typeN}:{$typeD} for Rational type construction\"", ")", ";", "}" ]
Throw a create exception @param $numerator @param $denominator @throws InvalidTypeException
[ "Throw", "a", "create", "exception" ]
9d364c10c68c10f768254fb25b0b1db3dbef6fa9
https://github.com/chippyash/Strong-Type/blob/9d364c10c68c10f768254fb25b0b1db3dbef6fa9/src/Chippyash/Type/Number/Rational/RationalTypeFactory.php#L271-L276
13,367
PandaPlatform/framework
src/Panda/Support/Helpers/DateTimeHelper.php
DateTimeHelper.getWorkingDaysCount
public static function getWorkingDaysCount($beginDate, $endDate, $nonWorkingDays = []) { $workdays = 0; if (!is_null($beginDate) && !is_null($endDate)) { if ($beginDate > $endDate) { $temp = $beginDate; $beginDate = $endDate; $endDate = $temp; } $oneDayInterval = new DateInterval('P1D'); $date = clone $beginDate; while (self::compareDateWithoutTime($date, $endDate) <= 0) { $weekday = $date->format('N'); if (!in_array($weekday, $nonWorkingDays)) { $workdays++; } $date->add($oneDayInterval); } } return $workdays; }
php
public static function getWorkingDaysCount($beginDate, $endDate, $nonWorkingDays = []) { $workdays = 0; if (!is_null($beginDate) && !is_null($endDate)) { if ($beginDate > $endDate) { $temp = $beginDate; $beginDate = $endDate; $endDate = $temp; } $oneDayInterval = new DateInterval('P1D'); $date = clone $beginDate; while (self::compareDateWithoutTime($date, $endDate) <= 0) { $weekday = $date->format('N'); if (!in_array($weekday, $nonWorkingDays)) { $workdays++; } $date->add($oneDayInterval); } } return $workdays; }
[ "public", "static", "function", "getWorkingDaysCount", "(", "$", "beginDate", ",", "$", "endDate", ",", "$", "nonWorkingDays", "=", "[", "]", ")", "{", "$", "workdays", "=", "0", ";", "if", "(", "!", "is_null", "(", "$", "beginDate", ")", "&&", "!", "is_null", "(", "$", "endDate", ")", ")", "{", "if", "(", "$", "beginDate", ">", "$", "endDate", ")", "{", "$", "temp", "=", "$", "beginDate", ";", "$", "beginDate", "=", "$", "endDate", ";", "$", "endDate", "=", "$", "temp", ";", "}", "$", "oneDayInterval", "=", "new", "DateInterval", "(", "'P1D'", ")", ";", "$", "date", "=", "clone", "$", "beginDate", ";", "while", "(", "self", "::", "compareDateWithoutTime", "(", "$", "date", ",", "$", "endDate", ")", "<=", "0", ")", "{", "$", "weekday", "=", "$", "date", "->", "format", "(", "'N'", ")", ";", "if", "(", "!", "in_array", "(", "$", "weekday", ",", "$", "nonWorkingDays", ")", ")", "{", "$", "workdays", "++", ";", "}", "$", "date", "->", "add", "(", "$", "oneDayInterval", ")", ";", "}", "}", "return", "$", "workdays", ";", "}" ]
Count working days between the two given dates. The comparison includes both begin and end dates. @param DateTime $beginDate @param DateTime $endDate @param int[] $nonWorkingDays array containing the non working days (i.e. [6,7] for Saturday and Sunday) @return int Number of working days
[ "Count", "working", "days", "between", "the", "two", "given", "dates", ".", "The", "comparison", "includes", "both", "begin", "and", "end", "dates", "." ]
a78cf051b379896b5a4d5df620988e37a0e632f5
https://github.com/PandaPlatform/framework/blob/a78cf051b379896b5a4d5df620988e37a0e632f5/src/Panda/Support/Helpers/DateTimeHelper.php#L88-L109
13,368
PandaPlatform/framework
src/Panda/Support/Helpers/DateTimeHelper.php
DateTimeHelper.getAverageTimeForArrayOfDateTimes
public static function getAverageTimeForArrayOfDateTimes($array) { if (!is_array($array)) { return false; } $averageTime = null; $averageSecondsFromDateBeginSum = 0; $processedItemsCounter = 0; foreach ($array as $datetime) { if (!is_object($datetime) || !($datetime instanceof \DateTime)) { continue; } $hours = (int)$datetime->format('H'); $minutes = (int)$datetime->format('i'); $seconds = (int)$datetime->format('s'); $averageSecondsFromDateBeginSum += $hours * 3600 + $minutes * 60 + $seconds; $processedItemsCounter += 1; } $averageTime = gmdate('H:i:s', intval($averageSecondsFromDateBeginSum / $processedItemsCounter) % 86400); return $averageTime; }
php
public static function getAverageTimeForArrayOfDateTimes($array) { if (!is_array($array)) { return false; } $averageTime = null; $averageSecondsFromDateBeginSum = 0; $processedItemsCounter = 0; foreach ($array as $datetime) { if (!is_object($datetime) || !($datetime instanceof \DateTime)) { continue; } $hours = (int)$datetime->format('H'); $minutes = (int)$datetime->format('i'); $seconds = (int)$datetime->format('s'); $averageSecondsFromDateBeginSum += $hours * 3600 + $minutes * 60 + $seconds; $processedItemsCounter += 1; } $averageTime = gmdate('H:i:s', intval($averageSecondsFromDateBeginSum / $processedItemsCounter) % 86400); return $averageTime; }
[ "public", "static", "function", "getAverageTimeForArrayOfDateTimes", "(", "$", "array", ")", "{", "if", "(", "!", "is_array", "(", "$", "array", ")", ")", "{", "return", "false", ";", "}", "$", "averageTime", "=", "null", ";", "$", "averageSecondsFromDateBeginSum", "=", "0", ";", "$", "processedItemsCounter", "=", "0", ";", "foreach", "(", "$", "array", "as", "$", "datetime", ")", "{", "if", "(", "!", "is_object", "(", "$", "datetime", ")", "||", "!", "(", "$", "datetime", "instanceof", "\\", "DateTime", ")", ")", "{", "continue", ";", "}", "$", "hours", "=", "(", "int", ")", "$", "datetime", "->", "format", "(", "'H'", ")", ";", "$", "minutes", "=", "(", "int", ")", "$", "datetime", "->", "format", "(", "'i'", ")", ";", "$", "seconds", "=", "(", "int", ")", "$", "datetime", "->", "format", "(", "'s'", ")", ";", "$", "averageSecondsFromDateBeginSum", "+=", "$", "hours", "*", "3600", "+", "$", "minutes", "*", "60", "+", "$", "seconds", ";", "$", "processedItemsCounter", "+=", "1", ";", "}", "$", "averageTime", "=", "gmdate", "(", "'H:i:s'", ",", "intval", "(", "$", "averageSecondsFromDateBeginSum", "/", "$", "processedItemsCounter", ")", "%", "86400", ")", ";", "return", "$", "averageTime", ";", "}" ]
Method find the average time for given array of datetime objects it ignores any non DateTIme values in the given array @param DateTime[] $array @return string|bool
[ "Method", "find", "the", "average", "time", "for", "given", "array", "of", "datetime", "objects", "it", "ignores", "any", "non", "DateTIme", "values", "in", "the", "given", "array" ]
a78cf051b379896b5a4d5df620988e37a0e632f5
https://github.com/PandaPlatform/framework/blob/a78cf051b379896b5a4d5df620988e37a0e632f5/src/Panda/Support/Helpers/DateTimeHelper.php#L157-L184
13,369
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.limit
public function limit($limit, $skip = null) { $this->pipeline['$limit'] = $limit; if (!empty($skip)) { $this->pipeline['$skip'] = $skip; } return $this; }
php
public function limit($limit, $skip = null) { $this->pipeline['$limit'] = $limit; if (!empty($skip)) { $this->pipeline['$skip'] = $skip; } return $this; }
[ "public", "function", "limit", "(", "$", "limit", ",", "$", "skip", "=", "null", ")", "{", "$", "this", "->", "pipeline", "[", "'$limit'", "]", "=", "$", "limit", ";", "if", "(", "!", "empty", "(", "$", "skip", ")", ")", "{", "$", "this", "->", "pipeline", "[", "'$skip'", "]", "=", "$", "skip", ";", "}", "return", "$", "this", ";", "}" ]
Set the result limit and offset. @param int $limit How many results to return. @param int|null $skip How many results to skip. @return $this
[ "Set", "the", "result", "limit", "and", "offset", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L91-L99
13,370
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.getResult
public function getResult() { $result = $this->mongo->aggregate($this->getCollectionName(), $this->getPipeline()); return $result->toArray(); }
php
public function getResult() { $result = $this->mongo->aggregate($this->getCollectionName(), $this->getPipeline()); return $result->toArray(); }
[ "public", "function", "getResult", "(", ")", "{", "$", "result", "=", "$", "this", "->", "mongo", "->", "aggregate", "(", "$", "this", "->", "getCollectionName", "(", ")", ",", "$", "this", "->", "getPipeline", "(", ")", ")", ";", "return", "$", "result", "->", "toArray", "(", ")", ";", "}" ]
This method does your query lookup and returns the result in form of an array. In case if there are no records to return, false is returned. @return bool
[ "This", "method", "does", "your", "query", "lookup", "and", "returns", "the", "result", "in", "form", "of", "an", "array", ".", "In", "case", "if", "there", "are", "no", "records", "to", "return", "false", "is", "returned", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L117-L121
13,371
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.sortByTimestamp
public function sortByTimestamp($direction) { if ($this->id != '$ts') { throw new AnalyticsDbException('In order to sort by timestamp, you need to first group by timestamp.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
php
public function sortByTimestamp($direction) { if ($this->id != '$ts') { throw new AnalyticsDbException('In order to sort by timestamp, you need to first group by timestamp.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
[ "public", "function", "sortByTimestamp", "(", "$", "direction", ")", "{", "if", "(", "$", "this", "->", "id", "!=", "'$ts'", ")", "{", "throw", "new", "AnalyticsDbException", "(", "'In order to sort by timestamp, you need to first group by timestamp.'", ")", ";", "}", "$", "direction", "=", "(", "int", ")", "$", "direction", ";", "$", "this", "->", "pipeline", "[", "'$sort'", "]", "=", "[", "'_id'", "=>", "$", "direction", "]", ";", "return", "$", "this", ";", "}" ]
Sorts the result by timestamp. @param string $direction Mongo sort direction: 1 => ascending; -1 => descending @return $this @throws AnalyticsDbException
[ "Sorts", "the", "result", "by", "timestamp", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L131-L141
13,372
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.sortByEntityName
public function sortByEntityName($direction) { if ($this->id != '$entity') { throw new AnalyticsDbException('In order to sort by entity name, you need to first group by entity name.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
php
public function sortByEntityName($direction) { if ($this->id != '$entity') { throw new AnalyticsDbException('In order to sort by entity name, you need to first group by entity name.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
[ "public", "function", "sortByEntityName", "(", "$", "direction", ")", "{", "if", "(", "$", "this", "->", "id", "!=", "'$entity'", ")", "{", "throw", "new", "AnalyticsDbException", "(", "'In order to sort by entity name, you need to first group by entity name.'", ")", ";", "}", "$", "direction", "=", "(", "int", ")", "$", "direction", ";", "$", "this", "->", "pipeline", "[", "'$sort'", "]", "=", "[", "'_id'", "=>", "$", "direction", "]", ";", "return", "$", "this", ";", "}" ]
Sorts the result by entity name. @param string $direction Mongo sort direction: 1 => ascending; -1 => descending @return $this @throws AnalyticsDbException
[ "Sorts", "the", "result", "by", "entity", "name", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L166-L176
13,373
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.sortByRef
public function sortByRef($direction) { if ($this->id != '$ref') { throw new AnalyticsDbException('In order to sort by ref, you need to first group by ref.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
php
public function sortByRef($direction) { if ($this->id != '$ref') { throw new AnalyticsDbException('In order to sort by ref, you need to first group by ref.'); } $direction = (int)$direction; $this->pipeline['$sort'] = ['_id' => $direction]; return $this; }
[ "public", "function", "sortByRef", "(", "$", "direction", ")", "{", "if", "(", "$", "this", "->", "id", "!=", "'$ref'", ")", "{", "throw", "new", "AnalyticsDbException", "(", "'In order to sort by ref, you need to first group by ref.'", ")", ";", "}", "$", "direction", "=", "(", "int", ")", "$", "direction", ";", "$", "this", "->", "pipeline", "[", "'$sort'", "]", "=", "[", "'_id'", "=>", "$", "direction", "]", ";", "return", "$", "this", ";", "}" ]
Sorts the result by referrer value. @param string $direction Mongo sort direction: 1 => ascending; -1 => descending @return $this @throws AnalyticsDbException
[ "Sorts", "the", "result", "by", "referrer", "value", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L186-L196
13,374
Webiny/AnalyticsDb
src/Webiny/AnalyticsDb/Query/AbstractQuery.php
AbstractQuery.getPipeline
public function getPipeline() { $pipeline = []; foreach ($this->pipeline as $k => $v) { $pipeline[] = [$k => $v]; } return $pipeline; }
php
public function getPipeline() { $pipeline = []; foreach ($this->pipeline as $k => $v) { $pipeline[] = [$k => $v]; } return $pipeline; }
[ "public", "function", "getPipeline", "(", ")", "{", "$", "pipeline", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "pipeline", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "pipeline", "[", "]", "=", "[", "$", "k", "=>", "$", "v", "]", ";", "}", "return", "$", "pipeline", ";", "}" ]
Returns the pipeline array. @return array
[ "Returns", "the", "pipeline", "array", "." ]
e0b1e920643cd63071406520767243736004052e
https://github.com/Webiny/AnalyticsDb/blob/e0b1e920643cd63071406520767243736004052e/src/Webiny/AnalyticsDb/Query/AbstractQuery.php#L262-L270
13,375
wpup/digster
src/engines/class-engine.php
Engine.config
public function config( $key, $value = null ) { if ( is_array( $key ) ) { foreach ( $key as $id => $val ) { $this->config( $id, $val ); } } else { if ( ! is_null( $value ) ) { return $this->bind( $key, $value ); } if ( $this->bound( $key ) ) { return $this->make( $key ); } else { $default = $this->get_default_config(); return isset( $default[$key] ) ? $default[$key] : null; } } }
php
public function config( $key, $value = null ) { if ( is_array( $key ) ) { foreach ( $key as $id => $val ) { $this->config( $id, $val ); } } else { if ( ! is_null( $value ) ) { return $this->bind( $key, $value ); } if ( $this->bound( $key ) ) { return $this->make( $key ); } else { $default = $this->get_default_config(); return isset( $default[$key] ) ? $default[$key] : null; } } }
[ "public", "function", "config", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "foreach", "(", "$", "key", "as", "$", "id", "=>", "$", "val", ")", "{", "$", "this", "->", "config", "(", "$", "id", ",", "$", "val", ")", ";", "}", "}", "else", "{", "if", "(", "!", "is_null", "(", "$", "value", ")", ")", "{", "return", "$", "this", "->", "bind", "(", "$", "key", ",", "$", "value", ")", ";", "}", "if", "(", "$", "this", "->", "bound", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "make", "(", "$", "key", ")", ";", "}", "else", "{", "$", "default", "=", "$", "this", "->", "get_default_config", "(", ")", ";", "return", "isset", "(", "$", "default", "[", "$", "key", "]", ")", "?", "$", "default", "[", "$", "key", "]", ":", "null", ";", "}", "}", "}" ]
Get or set configuration values. @param array|string $key @param mixed $value @return mixed
[ "Get", "or", "set", "configuration", "values", "." ]
9ef9626ce82673af698bc0976d6c38a532e4a6d9
https://github.com/wpup/digster/blob/9ef9626ce82673af698bc0976d6c38a532e4a6d9/src/engines/class-engine.php#L24-L41
13,376
wpup/digster
src/engines/class-engine.php
Engine.get_engine_config
protected function get_engine_config() { $config = $this->prepare_engine_config(); $locations = $config['locations']; unset( $config['locations'] ); $locations = array_filter( (array) $locations, function ( $location ) { return file_exists( $location ); } ); return [$locations, $config]; }
php
protected function get_engine_config() { $config = $this->prepare_engine_config(); $locations = $config['locations']; unset( $config['locations'] ); $locations = array_filter( (array) $locations, function ( $location ) { return file_exists( $location ); } ); return [$locations, $config]; }
[ "protected", "function", "get_engine_config", "(", ")", "{", "$", "config", "=", "$", "this", "->", "prepare_engine_config", "(", ")", ";", "$", "locations", "=", "$", "config", "[", "'locations'", "]", ";", "unset", "(", "$", "config", "[", "'locations'", "]", ")", ";", "$", "locations", "=", "array_filter", "(", "(", "array", ")", "$", "locations", ",", "function", "(", "$", "location", ")", "{", "return", "file_exists", "(", "$", "location", ")", ";", "}", ")", ";", "return", "[", "$", "locations", ",", "$", "config", "]", ";", "}" ]
Get engine config. @return array
[ "Get", "engine", "config", "." ]
9ef9626ce82673af698bc0976d6c38a532e4a6d9
https://github.com/wpup/digster/blob/9ef9626ce82673af698bc0976d6c38a532e4a6d9/src/engines/class-engine.php#L70-L81
13,377
wpup/digster
src/engines/class-engine.php
Engine.prepare_config
protected function prepare_config( $arr ) { $result = []; if ( ! is_array( $arr ) ) { return $result; } $arr = array_merge( $this->get_default_config(), $arr ); foreach ( $arr as $key => $value ) { $res = $this->config( $key ); $result[$key] = is_null( $res ) ? $value : $res; } return apply_filters( 'digster/config', $result ); }
php
protected function prepare_config( $arr ) { $result = []; if ( ! is_array( $arr ) ) { return $result; } $arr = array_merge( $this->get_default_config(), $arr ); foreach ( $arr as $key => $value ) { $res = $this->config( $key ); $result[$key] = is_null( $res ) ? $value : $res; } return apply_filters( 'digster/config', $result ); }
[ "protected", "function", "prepare_config", "(", "$", "arr", ")", "{", "$", "result", "=", "[", "]", ";", "if", "(", "!", "is_array", "(", "$", "arr", ")", ")", "{", "return", "$", "result", ";", "}", "$", "arr", "=", "array_merge", "(", "$", "this", "->", "get_default_config", "(", ")", ",", "$", "arr", ")", ";", "foreach", "(", "$", "arr", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "res", "=", "$", "this", "->", "config", "(", "$", "key", ")", ";", "$", "result", "[", "$", "key", "]", "=", "is_null", "(", "$", "res", ")", "?", "$", "value", ":", "$", "res", ";", "}", "return", "apply_filters", "(", "'digster/config'", ",", "$", "result", ")", ";", "}" ]
Prepare the template engines real configuration. @param array $arr @return array
[ "Prepare", "the", "template", "engines", "real", "configuration", "." ]
9ef9626ce82673af698bc0976d6c38a532e4a6d9
https://github.com/wpup/digster/blob/9ef9626ce82673af698bc0976d6c38a532e4a6d9/src/engines/class-engine.php#L90-L105
13,378
vi-kon/laravel-parser
src/ViKon/Parser/rule/AbstractBlockRule.php
AbstractBlockRule.finish
public function finish(Lexer $lexer) { if (is_array($this->exitPattern)) { foreach ($this->exitPattern as $exitPattern) { $lexer->addExitPattern($exitPattern, $this->name); } } else { $lexer->addExitPattern($this->exitPattern, $this->name); } return $this; }
php
public function finish(Lexer $lexer) { if (is_array($this->exitPattern)) { foreach ($this->exitPattern as $exitPattern) { $lexer->addExitPattern($exitPattern, $this->name); } } else { $lexer->addExitPattern($this->exitPattern, $this->name); } return $this; }
[ "public", "function", "finish", "(", "Lexer", "$", "lexer", ")", "{", "if", "(", "is_array", "(", "$", "this", "->", "exitPattern", ")", ")", "{", "foreach", "(", "$", "this", "->", "exitPattern", "as", "$", "exitPattern", ")", "{", "$", "lexer", "->", "addExitPattern", "(", "$", "exitPattern", ",", "$", "this", "->", "name", ")", ";", "}", "}", "else", "{", "$", "lexer", "->", "addExitPattern", "(", "$", "this", "->", "exitPattern", ",", "$", "this", "->", "name", ")", ";", "}", "return", "$", "this", ";", "}" ]
Finish rule after connecting @param \ViKon\Parser\Lexer\Lexer $lexer lexer instance @return $this
[ "Finish", "rule", "after", "connecting" ]
070f0bb9120cb9ca6ff836d4f418e78ee33ee182
https://github.com/vi-kon/laravel-parser/blob/070f0bb9120cb9ca6ff836d4f418e78ee33ee182/src/ViKon/Parser/rule/AbstractBlockRule.php#L66-L76
13,379
vi-kon/laravel-parser
src/ViKon/Parser/rule/AbstractBlockRule.php
AbstractBlockRule.handleEndState
protected function handleEndState($content, $position, TokenList $tokenList) { if (!empty($content)) { $tokenList->addToken($this->name, $position) ->set('content', $content); } }
php
protected function handleEndState($content, $position, TokenList $tokenList) { if (!empty($content)) { $tokenList->addToken($this->name, $position) ->set('content', $content); } }
[ "protected", "function", "handleEndState", "(", "$", "content", ",", "$", "position", ",", "TokenList", "$", "tokenList", ")", "{", "if", "(", "!", "empty", "(", "$", "content", ")", ")", "{", "$", "tokenList", "->", "addToken", "(", "$", "this", "->", "name", ",", "$", "position", ")", "->", "set", "(", "'content'", ",", "$", "content", ")", ";", "}", "}" ]
Handle lexers end state @param string $content @param int $position @param \ViKon\Parser\TokenList $tokenList
[ "Handle", "lexers", "end", "state" ]
070f0bb9120cb9ca6ff836d4f418e78ee33ee182
https://github.com/vi-kon/laravel-parser/blob/070f0bb9120cb9ca6ff836d4f418e78ee33ee182/src/ViKon/Parser/rule/AbstractBlockRule.php#L170-L175
13,380
terdia/legato-framework
src/Security/Encryption.php
Encryption.valid
public static function valid($key, $cipher) { $keyLength = mb_strlen($key, '8bit'); if (static::SUPPORTED_CIPHER_32_LENGTH === $keyLength && $cipher === static::SUPPORTED_CIPHER_32) { return true; } if (static::SUPPORTED_CIPHER_16_LENGTH == $keyLength && $cipher === static::SUPPORTED_CIPHER_16) { return true; } return false; }
php
public static function valid($key, $cipher) { $keyLength = mb_strlen($key, '8bit'); if (static::SUPPORTED_CIPHER_32_LENGTH === $keyLength && $cipher === static::SUPPORTED_CIPHER_32) { return true; } if (static::SUPPORTED_CIPHER_16_LENGTH == $keyLength && $cipher === static::SUPPORTED_CIPHER_16) { return true; } return false; }
[ "public", "static", "function", "valid", "(", "$", "key", ",", "$", "cipher", ")", "{", "$", "keyLength", "=", "mb_strlen", "(", "$", "key", ",", "'8bit'", ")", ";", "if", "(", "static", "::", "SUPPORTED_CIPHER_32_LENGTH", "===", "$", "keyLength", "&&", "$", "cipher", "===", "static", "::", "SUPPORTED_CIPHER_32", ")", "{", "return", "true", ";", "}", "if", "(", "static", "::", "SUPPORTED_CIPHER_16_LENGTH", "==", "$", "keyLength", "&&", "$", "cipher", "===", "static", "::", "SUPPORTED_CIPHER_16", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check if the given key and cipher have valid length and name. @param $key @param $cipher @return bool
[ "Check", "if", "the", "given", "key", "and", "cipher", "have", "valid", "length", "and", "name", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Security/Encryption.php#L59-L74
13,381
terdia/legato-framework
src/Security/Encryption.php
Encryption.generateEncryptionKey
public static function generateEncryptionKey($cipher) { if ($cipher === static::SUPPORTED_CIPHER_32) { return random_bytes(static::SUPPORTED_CIPHER_32_LENGTH); } if ($cipher === static::SUPPORTED_CIPHER_16) { return random_bytes(static::SUPPORTED_CIPHER_16_LENGTH); } }
php
public static function generateEncryptionKey($cipher) { if ($cipher === static::SUPPORTED_CIPHER_32) { return random_bytes(static::SUPPORTED_CIPHER_32_LENGTH); } if ($cipher === static::SUPPORTED_CIPHER_16) { return random_bytes(static::SUPPORTED_CIPHER_16_LENGTH); } }
[ "public", "static", "function", "generateEncryptionKey", "(", "$", "cipher", ")", "{", "if", "(", "$", "cipher", "===", "static", "::", "SUPPORTED_CIPHER_32", ")", "{", "return", "random_bytes", "(", "static", "::", "SUPPORTED_CIPHER_32_LENGTH", ")", ";", "}", "if", "(", "$", "cipher", "===", "static", "::", "SUPPORTED_CIPHER_16", ")", "{", "return", "random_bytes", "(", "static", "::", "SUPPORTED_CIPHER_16_LENGTH", ")", ";", "}", "}" ]
Generate encryption key. @param $cipher @throws \Exception @return string
[ "Generate", "encryption", "key", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Security/Encryption.php#L85-L94
13,382
terdia/legato-framework
src/Security/Encryption.php
Encryption.encrypt
public function encrypt($value) { /** * Gets the cipher iv length. */ $iv = random_bytes(openssl_cipher_iv_length($this->cipher)); /** * Encrypts the given value. */ $value = \openssl_encrypt($value, $this->cipher, $this->key, 0, $iv); $hash_mac = $this->mac($iv = base64_encode($iv), $value); if (!$value) { throw new Exception('Unable to encrypt given value'); } $encrypted = json_encode(compact('iv', 'value', 'hash_mac')); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('Unable to encrypt given value.'); } return base64_encode($encrypted); }
php
public function encrypt($value) { /** * Gets the cipher iv length. */ $iv = random_bytes(openssl_cipher_iv_length($this->cipher)); /** * Encrypts the given value. */ $value = \openssl_encrypt($value, $this->cipher, $this->key, 0, $iv); $hash_mac = $this->mac($iv = base64_encode($iv), $value); if (!$value) { throw new Exception('Unable to encrypt given value'); } $encrypted = json_encode(compact('iv', 'value', 'hash_mac')); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('Unable to encrypt given value.'); } return base64_encode($encrypted); }
[ "public", "function", "encrypt", "(", "$", "value", ")", "{", "/**\n * Gets the cipher iv length.\n */", "$", "iv", "=", "random_bytes", "(", "openssl_cipher_iv_length", "(", "$", "this", "->", "cipher", ")", ")", ";", "/**\n * Encrypts the given value.\n */", "$", "value", "=", "\\", "openssl_encrypt", "(", "$", "value", ",", "$", "this", "->", "cipher", ",", "$", "this", "->", "key", ",", "0", ",", "$", "iv", ")", ";", "$", "hash_mac", "=", "$", "this", "->", "mac", "(", "$", "iv", "=", "base64_encode", "(", "$", "iv", ")", ",", "$", "value", ")", ";", "if", "(", "!", "$", "value", ")", "{", "throw", "new", "Exception", "(", "'Unable to encrypt given value'", ")", ";", "}", "$", "encrypted", "=", "json_encode", "(", "compact", "(", "'iv'", ",", "'value'", ",", "'hash_mac'", ")", ")", ";", "if", "(", "json_last_error", "(", ")", "!==", "JSON_ERROR_NONE", ")", "{", "throw", "new", "Exception", "(", "'Unable to encrypt given value.'", ")", ";", "}", "return", "base64_encode", "(", "$", "encrypted", ")", ";", "}" ]
Encrypt the value. @param $value @throws Exception @return string
[ "Encrypt", "the", "value", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Security/Encryption.php#L105-L130
13,383
terdia/legato-framework
src/Security/Encryption.php
Encryption.decrypt
public function decrypt($data) { $data = json_decode(base64_decode($data), true); $iv = base64_decode($data['iv']); if (!$this->isEncryptedDataValid($data)) { throw new Exception('The given encrypted data is invalid.'); } if (!$this->isMacValid($data, 16)) { throw new Exception('The hash is invalid.'); } /** * try to decrypt. */ $decrypted = \openssl_decrypt( $data['value'], $this->cipher, $this->key, 0, $iv ); /* * throw exception is we cannot decrypt */ if ($decrypted === false) { throw new Exception('Data could not be decrypted.'); } return $decrypted; }
php
public function decrypt($data) { $data = json_decode(base64_decode($data), true); $iv = base64_decode($data['iv']); if (!$this->isEncryptedDataValid($data)) { throw new Exception('The given encrypted data is invalid.'); } if (!$this->isMacValid($data, 16)) { throw new Exception('The hash is invalid.'); } /** * try to decrypt. */ $decrypted = \openssl_decrypt( $data['value'], $this->cipher, $this->key, 0, $iv ); /* * throw exception is we cannot decrypt */ if ($decrypted === false) { throw new Exception('Data could not be decrypted.'); } return $decrypted; }
[ "public", "function", "decrypt", "(", "$", "data", ")", "{", "$", "data", "=", "json_decode", "(", "base64_decode", "(", "$", "data", ")", ",", "true", ")", ";", "$", "iv", "=", "base64_decode", "(", "$", "data", "[", "'iv'", "]", ")", ";", "if", "(", "!", "$", "this", "->", "isEncryptedDataValid", "(", "$", "data", ")", ")", "{", "throw", "new", "Exception", "(", "'The given encrypted data is invalid.'", ")", ";", "}", "if", "(", "!", "$", "this", "->", "isMacValid", "(", "$", "data", ",", "16", ")", ")", "{", "throw", "new", "Exception", "(", "'The hash is invalid.'", ")", ";", "}", "/**\n * try to decrypt.\n */", "$", "decrypted", "=", "\\", "openssl_decrypt", "(", "$", "data", "[", "'value'", "]", ",", "$", "this", "->", "cipher", ",", "$", "this", "->", "key", ",", "0", ",", "$", "iv", ")", ";", "/*\n * throw exception is we cannot decrypt\n */", "if", "(", "$", "decrypted", "===", "false", ")", "{", "throw", "new", "Exception", "(", "'Data could not be decrypted.'", ")", ";", "}", "return", "$", "decrypted", ";", "}" ]
Decrypt the given data and return plain text. @param $data @throws Exception @return string
[ "Decrypt", "the", "given", "data", "and", "return", "plain", "text", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Security/Encryption.php#L141-L168
13,384
terdia/legato-framework
src/Security/Encryption.php
Encryption.isMacValid
protected function isMacValid($data, $bytes) { $calculated = hash_hmac( 'sha384', $this->mac($data['iv'], $data['value']), $bytes, true ); return hash_equals( hash_hmac('sha384', $data['hash_mac'], $bytes, true), $calculated ); }
php
protected function isMacValid($data, $bytes) { $calculated = hash_hmac( 'sha384', $this->mac($data['iv'], $data['value']), $bytes, true ); return hash_equals( hash_hmac('sha384', $data['hash_mac'], $bytes, true), $calculated ); }
[ "protected", "function", "isMacValid", "(", "$", "data", ",", "$", "bytes", ")", "{", "$", "calculated", "=", "hash_hmac", "(", "'sha384'", ",", "$", "this", "->", "mac", "(", "$", "data", "[", "'iv'", "]", ",", "$", "data", "[", "'value'", "]", ")", ",", "$", "bytes", ",", "true", ")", ";", "return", "hash_equals", "(", "hash_hmac", "(", "'sha384'", ",", "$", "data", "[", "'hash_mac'", "]", ",", "$", "bytes", ",", "true", ")", ",", "$", "calculated", ")", ";", "}" ]
Determine if hash is valid. @param $data @param $bytes @return bool
[ "Determine", "if", "hash", "is", "valid", "." ]
44057c1c3c6f3e9643e9fade51bd417860fafda8
https://github.com/terdia/legato-framework/blob/44057c1c3c6f3e9643e9fade51bd417860fafda8/src/Security/Encryption.php#L192-L201
13,385
chippyash/Strong-Type
src/Chippyash/Type/Number/Rational/GMPRationalType.php
GMPRationalType.get
public function get() { if ($this->isInteger()) { /** @noinspection PhpUndefinedMethodInspection */ return $this->value['num']->get(); } $num = intval(gmp_strval($this->value['num']->gmp())); $den = intval(gmp_strval($this->value['den']->gmp())); return $num/$den; }
php
public function get() { if ($this->isInteger()) { /** @noinspection PhpUndefinedMethodInspection */ return $this->value['num']->get(); } $num = intval(gmp_strval($this->value['num']->gmp())); $den = intval(gmp_strval($this->value['den']->gmp())); return $num/$den; }
[ "public", "function", "get", "(", ")", "{", "if", "(", "$", "this", "->", "isInteger", "(", ")", ")", "{", "/** @noinspection PhpUndefinedMethodInspection */", "return", "$", "this", "->", "value", "[", "'num'", "]", "->", "get", "(", ")", ";", "}", "$", "num", "=", "intval", "(", "gmp_strval", "(", "$", "this", "->", "value", "[", "'num'", "]", "->", "gmp", "(", ")", ")", ")", ";", "$", "den", "=", "intval", "(", "gmp_strval", "(", "$", "this", "->", "value", "[", "'den'", "]", "->", "gmp", "(", ")", ")", ")", ";", "return", "$", "num", "/", "$", "den", ";", "}" ]
Get the value of the object typed properly as a PHP Native type @return integer|float
[ "Get", "the", "value", "of", "the", "object", "typed", "properly", "as", "a", "PHP", "Native", "type" ]
9d364c10c68c10f768254fb25b0b1db3dbef6fa9
https://github.com/chippyash/Strong-Type/blob/9d364c10c68c10f768254fb25b0b1db3dbef6fa9/src/Chippyash/Type/Number/Rational/GMPRationalType.php#L59-L70
13,386
ptlis/conneg
src/Negotiator/Matcher/ExactMatcher.php
ExactMatcher.getMatchingIndex
private function getMatchingIndex(array $matchingList, PreferenceInterface $pref) { $index = -1; foreach ($matchingList as $key => $match) { if ($match->getVariant() === $pref->getVariant()) { $index = $key; } } return $index; }
php
private function getMatchingIndex(array $matchingList, PreferenceInterface $pref) { $index = -1; foreach ($matchingList as $key => $match) { if ($match->getVariant() === $pref->getVariant()) { $index = $key; } } return $index; }
[ "private", "function", "getMatchingIndex", "(", "array", "$", "matchingList", ",", "PreferenceInterface", "$", "pref", ")", "{", "$", "index", "=", "-", "1", ";", "foreach", "(", "$", "matchingList", "as", "$", "key", "=>", "$", "match", ")", "{", "if", "(", "$", "match", "->", "getVariant", "(", ")", "===", "$", "pref", "->", "getVariant", "(", ")", ")", "{", "$", "index", "=", "$", "key", ";", "}", "}", "return", "$", "index", ";", "}" ]
Returns the first index containing a matching variant, or -1 if not present. @param MatchedPreferenceInterface[] $matchingList @param PreferenceInterface $pref @return int
[ "Returns", "the", "first", "index", "containing", "a", "matching", "variant", "or", "-", "1", "if", "not", "present", "." ]
04afb568f368ecdd81c13277006c4be041ccb58b
https://github.com/ptlis/conneg/blob/04afb568f368ecdd81c13277006c4be041ccb58b/src/Negotiator/Matcher/ExactMatcher.php#L75-L86
13,387
psecio/propauth
src/Resolve.php
Resolve.execute
public function execute($path) { $parts = (!is_array($path)) ? explode('.', $path) : $path; $source = $this->subject; foreach ($parts as $index => $part) { $source = $this->resolve($part, $source); } return $source; }
php
public function execute($path) { $parts = (!is_array($path)) ? explode('.', $path) : $path; $source = $this->subject; foreach ($parts as $index => $part) { $source = $this->resolve($part, $source); } return $source; }
[ "public", "function", "execute", "(", "$", "path", ")", "{", "$", "parts", "=", "(", "!", "is_array", "(", "$", "path", ")", ")", "?", "explode", "(", "'.'", ",", "$", "path", ")", ":", "$", "path", ";", "$", "source", "=", "$", "this", "->", "subject", ";", "foreach", "(", "$", "parts", "as", "$", "index", "=>", "$", "part", ")", "{", "$", "source", "=", "$", "this", "->", "resolve", "(", "$", "part", ",", "$", "source", ")", ";", "}", "return", "$", "source", ";", "}" ]
Execute the data search using the path provided @param string|array $path Path to locate the data @return void
[ "Execute", "the", "data", "search", "using", "the", "path", "provided" ]
cb24fcc0a3fa459f2ef40a867c334951aabf7b83
https://github.com/psecio/propauth/blob/cb24fcc0a3fa459f2ef40a867c334951aabf7b83/src/Resolve.php#L31-L40
13,388
psecio/propauth
src/Resolve.php
Resolve.resolve
public function resolve($part, $source) { if (is_array($source)) { $source = $this->handleArray($part, $source); } elseif (is_object($source)) { $source = $this->handleObject($part, $source); } return $source; }
php
public function resolve($part, $source) { if (is_array($source)) { $source = $this->handleArray($part, $source); } elseif (is_object($source)) { $source = $this->handleObject($part, $source); } return $source; }
[ "public", "function", "resolve", "(", "$", "part", ",", "$", "source", ")", "{", "if", "(", "is_array", "(", "$", "source", ")", ")", "{", "$", "source", "=", "$", "this", "->", "handleArray", "(", "$", "part", ",", "$", "source", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "source", ")", ")", "{", "$", "source", "=", "$", "this", "->", "handleObject", "(", "$", "part", ",", "$", "source", ")", ";", "}", "return", "$", "source", ";", "}" ]
Using the path part given, locate the data on the current source @param string $part Path "part" @param mixed $source Partial data from the subject @return mixed Result of resolving the part path on the source data
[ "Using", "the", "path", "part", "given", "locate", "the", "data", "on", "the", "current", "source" ]
cb24fcc0a3fa459f2ef40a867c334951aabf7b83
https://github.com/psecio/propauth/blob/cb24fcc0a3fa459f2ef40a867c334951aabf7b83/src/Resolve.php#L50-L59
13,389
psecio/propauth
src/Resolve.php
Resolve.handleArray
public function handleArray($path, $subject) { $set = []; foreach ($subject as $subj) { $result = $this->resolve($path, $subj); if (is_array($result)) { $set = array_merge($set, $result); } else { $set = $result; } } return $set; }
php
public function handleArray($path, $subject) { $set = []; foreach ($subject as $subj) { $result = $this->resolve($path, $subj); if (is_array($result)) { $set = array_merge($set, $result); } else { $set = $result; } } return $set; }
[ "public", "function", "handleArray", "(", "$", "path", ",", "$", "subject", ")", "{", "$", "set", "=", "[", "]", ";", "foreach", "(", "$", "subject", "as", "$", "subj", ")", "{", "$", "result", "=", "$", "this", "->", "resolve", "(", "$", "path", ",", "$", "subj", ")", ";", "if", "(", "is_array", "(", "$", "result", ")", ")", "{", "$", "set", "=", "array_merge", "(", "$", "set", ",", "$", "result", ")", ";", "}", "else", "{", "$", "set", "=", "$", "result", ";", "}", "}", "return", "$", "set", ";", "}" ]
Handle the location of the value when the source is an array @param string $path Part of the path to locate @param mixed $subject Source to search @return mixed Result of the search on the array
[ "Handle", "the", "location", "of", "the", "value", "when", "the", "source", "is", "an", "array" ]
cb24fcc0a3fa459f2ef40a867c334951aabf7b83
https://github.com/psecio/propauth/blob/cb24fcc0a3fa459f2ef40a867c334951aabf7b83/src/Resolve.php#L83-L95
13,390
PandaPlatform/framework
src/Panda/Localization/Processors/JsonProcessor.php
JsonProcessor.loadTranslations
public function loadTranslations($locale, $package = 'default') { $package = $package ?: 'default'; if (empty(static::$translations[$locale])) { // Get full file path $fileName = $locale . DIRECTORY_SEPARATOR . $package . '.json'; $filePath = $this->getBaseDirectory() . DIRECTORY_SEPARATOR . $fileName; // Check if is valid and load translations if (is_file($filePath)) { $fileContents = file_get_contents($filePath); static::$translations[$locale] = json_decode($fileContents, true); } else { throw new FileNotFoundException($fileName); } } }
php
public function loadTranslations($locale, $package = 'default') { $package = $package ?: 'default'; if (empty(static::$translations[$locale])) { // Get full file path $fileName = $locale . DIRECTORY_SEPARATOR . $package . '.json'; $filePath = $this->getBaseDirectory() . DIRECTORY_SEPARATOR . $fileName; // Check if is valid and load translations if (is_file($filePath)) { $fileContents = file_get_contents($filePath); static::$translations[$locale] = json_decode($fileContents, true); } else { throw new FileNotFoundException($fileName); } } }
[ "public", "function", "loadTranslations", "(", "$", "locale", ",", "$", "package", "=", "'default'", ")", "{", "$", "package", "=", "$", "package", "?", ":", "'default'", ";", "if", "(", "empty", "(", "static", "::", "$", "translations", "[", "$", "locale", "]", ")", ")", "{", "// Get full file path", "$", "fileName", "=", "$", "locale", ".", "DIRECTORY_SEPARATOR", ".", "$", "package", ".", "'.json'", ";", "$", "filePath", "=", "$", "this", "->", "getBaseDirectory", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "fileName", ";", "// Check if is valid and load translations", "if", "(", "is_file", "(", "$", "filePath", ")", ")", "{", "$", "fileContents", "=", "file_get_contents", "(", "$", "filePath", ")", ";", "static", "::", "$", "translations", "[", "$", "locale", "]", "=", "json_decode", "(", "$", "fileContents", ",", "true", ")", ";", "}", "else", "{", "throw", "new", "FileNotFoundException", "(", "$", "fileName", ")", ";", "}", "}", "}" ]
Load translations from file. @param string $locale @param string $package @throws FileNotFoundException
[ "Load", "translations", "from", "file", "." ]
a78cf051b379896b5a4d5df620988e37a0e632f5
https://github.com/PandaPlatform/framework/blob/a78cf051b379896b5a4d5df620988e37a0e632f5/src/Panda/Localization/Processors/JsonProcessor.php#L30-L46
13,391
crysalead/net
src/Http/Cgi/Request.php
Request.is
public function is($flag) { if (!isset($this->_detectors[$flag])) { return $flag === $this->format(); } $detector = $this->_detectors[$flag]; if (is_callable($detector)) { return $detector($this); } if (!is_array($detector)) { throw new Exception("Invalid `'{$flag}'` detector definition."); } $key = key($detector); $check = current($detector); $value = $this->attr($key); if (is_array($check)) { return !!preg_match('~' . join('|', $check) . '~i', $value); } if (preg_match('~^(?P<char>\~|/|@|#).*?(?P=char)$~', $check)) { return !!preg_match($check, $value); } return $check === $value; }
php
public function is($flag) { if (!isset($this->_detectors[$flag])) { return $flag === $this->format(); } $detector = $this->_detectors[$flag]; if (is_callable($detector)) { return $detector($this); } if (!is_array($detector)) { throw new Exception("Invalid `'{$flag}'` detector definition."); } $key = key($detector); $check = current($detector); $value = $this->attr($key); if (is_array($check)) { return !!preg_match('~' . join('|', $check) . '~i', $value); } if (preg_match('~^(?P<char>\~|/|@|#).*?(?P=char)$~', $check)) { return !!preg_match($check, $value); } return $check === $value; }
[ "public", "function", "is", "(", "$", "flag", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_detectors", "[", "$", "flag", "]", ")", ")", "{", "return", "$", "flag", "===", "$", "this", "->", "format", "(", ")", ";", "}", "$", "detector", "=", "$", "this", "->", "_detectors", "[", "$", "flag", "]", ";", "if", "(", "is_callable", "(", "$", "detector", ")", ")", "{", "return", "$", "detector", "(", "$", "this", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "detector", ")", ")", "{", "throw", "new", "Exception", "(", "\"Invalid `'{$flag}'` detector definition.\"", ")", ";", "}", "$", "key", "=", "key", "(", "$", "detector", ")", ";", "$", "check", "=", "current", "(", "$", "detector", ")", ";", "$", "value", "=", "$", "this", "->", "attr", "(", "$", "key", ")", ";", "if", "(", "is_array", "(", "$", "check", ")", ")", "{", "return", "!", "!", "preg_match", "(", "'~'", ".", "join", "(", "'|'", ",", "$", "check", ")", ".", "'~i'", ",", "$", "value", ")", ";", "}", "if", "(", "preg_match", "(", "'~^(?P<char>\\~|/|@|#).*?(?P=char)$~'", ",", "$", "check", ")", ")", "{", "return", "!", "!", "preg_match", "(", "$", "check", ",", "$", "value", ")", ";", "}", "return", "$", "check", "===", "$", "value", ";", "}" ]
Provides a simple syntax for making assertions about the properties of a request. The default detectors include the following: - `'mobile'`: Uses a regular expression to match common mobile browser user agents. - `'ajax'`: Checks to see if the `X-Requested-With` header is present, and matches the value `'XMLHttpRequest'`. - `'flash'`: Checks to see if the user agent is `'Shockwave Flash'`. - `'ssl'`: Verifies that the request is SSL-secured. - `'get'` / `'post'` / `'put'` / `'delete'` / `'head'` / `'options'`: Checks that the HTTP request method matches the one specified. In addition to the above, this method also accepts media format names to make assertions against the format of the request body (for POST or PUT requests), i.e. `$request->is('json')`. This will return `true` if the client has made a POST request with JSON data. For information about adding custom detectors or overriding the ones in the core, see the `detect()` method. @param string $flag The name of the flag to check, which should be the name of a valid detector of media format. @return boolean Returns `true` if the detector check succeeds of the request match the media format, otherwise `false`.
[ "Provides", "a", "simple", "syntax", "for", "making", "assertions", "about", "the", "properties", "of", "a", "request", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cgi/Request.php#L352-L376
13,392
crysalead/net
src/Http/Cgi/Request.php
Request.locale
public function locale($locale = null) { if ($locale) { $this->_locale = $locale; } if ($this->_locale) { return $this->_locale; } if (isset($this->_params['locale'])) { return $this->_params['locale']; } }
php
public function locale($locale = null) { if ($locale) { $this->_locale = $locale; } if ($this->_locale) { return $this->_locale; } if (isset($this->_params['locale'])) { return $this->_params['locale']; } }
[ "public", "function", "locale", "(", "$", "locale", "=", "null", ")", "{", "if", "(", "$", "locale", ")", "{", "$", "this", "->", "_locale", "=", "$", "locale", ";", "}", "if", "(", "$", "this", "->", "_locale", ")", "{", "return", "$", "this", "->", "_locale", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "_params", "[", "'locale'", "]", ")", ")", "{", "return", "$", "this", "->", "_params", "[", "'locale'", "]", ";", "}", "}" ]
Sets or returns the current locale string. @param string $locale An optional locale string like `'en'`, `'en_US'` or `'de_DE'`. If specified, will overwrite the existing locale. @return string|null Returns the currently set locale string.
[ "Sets", "or", "returns", "the", "current", "locale", "string", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cgi/Request.php#L448-L459
13,393
crysalead/net
src/Http/Cgi/Request.php
Request.ingoing
public static function ingoing($config = []) { $config['env'] = isset($config['env']) ? $config['env'] : $_SERVER; if (!isset($config['env']['REQUEST_URI'])) { throw new NetException("Missing `'REQUEST_URI'` environment variable, unable to create the main request."); } if (!isset($config['env']['SCRIPT_NAME'])) { throw new NetException("Missing `'SCRIPT_NAME'` environment variable, unable to create the main request."); } return new static($config + [ 'body' => new Part(['filename' => 'php://input', 'mode' => 'r']), 'query' => isset($_GET) ? $_GET : [], 'cookies' => $_COOKIE ]); }
php
public static function ingoing($config = []) { $config['env'] = isset($config['env']) ? $config['env'] : $_SERVER; if (!isset($config['env']['REQUEST_URI'])) { throw new NetException("Missing `'REQUEST_URI'` environment variable, unable to create the main request."); } if (!isset($config['env']['SCRIPT_NAME'])) { throw new NetException("Missing `'SCRIPT_NAME'` environment variable, unable to create the main request."); } return new static($config + [ 'body' => new Part(['filename' => 'php://input', 'mode' => 'r']), 'query' => isset($_GET) ? $_GET : [], 'cookies' => $_COOKIE ]); }
[ "public", "static", "function", "ingoing", "(", "$", "config", "=", "[", "]", ")", "{", "$", "config", "[", "'env'", "]", "=", "isset", "(", "$", "config", "[", "'env'", "]", ")", "?", "$", "config", "[", "'env'", "]", ":", "$", "_SERVER", ";", "if", "(", "!", "isset", "(", "$", "config", "[", "'env'", "]", "[", "'REQUEST_URI'", "]", ")", ")", "{", "throw", "new", "NetException", "(", "\"Missing `'REQUEST_URI'` environment variable, unable to create the main request.\"", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "config", "[", "'env'", "]", "[", "'SCRIPT_NAME'", "]", ")", ")", "{", "throw", "new", "NetException", "(", "\"Missing `'SCRIPT_NAME'` environment variable, unable to create the main request.\"", ")", ";", "}", "return", "new", "static", "(", "$", "config", "+", "[", "'body'", "=>", "new", "Part", "(", "[", "'filename'", "=>", "'php://input'", ",", "'mode'", "=>", "'r'", "]", ")", ",", "'query'", "=>", "isset", "(", "$", "_GET", ")", "?", "$", "_GET", ":", "[", "]", ",", "'cookies'", "=>", "$", "_COOKIE", "]", ")", ";", "}" ]
Creates a request extracted from CGI globals. @param array $config The config array. - `'env'` _array_: Environment variable (defaults: `$_SERVER`). @return self
[ "Creates", "a", "request", "extracted", "from", "CGI", "globals", "." ]
4d75abead39e954529b56cbffa3841a9cd3044bb
https://github.com/crysalead/net/blob/4d75abead39e954529b56cbffa3841a9cd3044bb/src/Http/Cgi/Request.php#L544-L561
13,394
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.setDefaultManipulationInformation
private function setDefaultManipulationInformation() { $this->add_base_dn = $this->basedn_array[0]; $this->add_dn = $this->dn; $this->add_pw = $this->password; $this->modify_method = "self"; $this->modify_base_dn = $this->add_base_dn; $this->modify_dn = $this->add_dn; $this->modify_pw = $this->add_pw; }
php
private function setDefaultManipulationInformation() { $this->add_base_dn = $this->basedn_array[0]; $this->add_dn = $this->dn; $this->add_pw = $this->password; $this->modify_method = "self"; $this->modify_base_dn = $this->add_base_dn; $this->modify_dn = $this->add_dn; $this->modify_pw = $this->add_pw; }
[ "private", "function", "setDefaultManipulationInformation", "(", ")", "{", "$", "this", "->", "add_base_dn", "=", "$", "this", "->", "basedn_array", "[", "0", "]", ";", "$", "this", "->", "add_dn", "=", "$", "this", "->", "dn", ";", "$", "this", "->", "add_pw", "=", "$", "this", "->", "password", ";", "$", "this", "->", "modify_method", "=", "\"self\"", ";", "$", "this", "->", "modify_base_dn", "=", "$", "this", "->", "add_base_dn", ";", "$", "this", "->", "modify_dn", "=", "$", "this", "->", "add_dn", ";", "$", "this", "->", "modify_pw", "=", "$", "this", "->", "add_pw", ";", "}" ]
Sets the base DN and credentials for add and modify operations based on the search base DN and credentials. This is done to provide sensible defaults in case the specific setter methods are not invoked.
[ "Sets", "the", "base", "DN", "and", "credentials", "for", "add", "and", "modify", "operations", "based", "on", "the", "search", "base", "DN", "and", "credentials", ".", "This", "is", "done", "to", "provide", "sensible", "defaults", "in", "case", "the", "specific", "setter", "methods", "are", "not", "invoked", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L120-L129
13,395
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.connect
public function connect($username="", $password="") { // make sure the ldap extension has been loaded if(!extension_loaded('ldap')) { throw new LdapExtensionNotLoadedException(); } $params = array( 'hostname' => $this->host, 'base_dn' => $this->basedn, 'options' => [ ConnectionInterface::OPT_PROTOCOL_VERSION => $this->version, ], ); // if there is an overlay, use that as the base DN instead if(!empty($this->overlay_dn)) { $params['base_dn'] = $this->overlay_dn; } $this->ldap = new Manager($params, new Driver()); // connect to the server and bind with the credentials try { $this->ldap->connect(); // if override parameters have been specified then use those // for the binding operation if(!empty($username)) { foreach($this->basedn_array as $basedn) { try { // bind by uid; append the overlay DN if one has been specified $selectedUsername = $this->search_username . "=" . $username; if(!empty($basedn)) { $selectedUsername .= "," . $basedn; } $selectedPassword = ""; // do we allow empty passwords for bind attempts? if(empty($password)) { if($this->allowNoPass) { // yes so use the constructor-provided DN and password $selectedUsername = $this->dn; $selectedPassword = $this->password; } } else { // password provided so use what we were given $selectedPassword = $password; } // append the overlay DN if it exists if(!empty($this->overlay_dn)) { $selectedUsername .= "," . $this->overlay_dn; } // now perform the bind $this->bind($selectedUsername, $selectedPassword); // if we get here without hitting an exception, the bind // was successful return true; } catch(BindException $e) { // just because we hit a bind exception it doesn't mean // that there was an error; this could have been the // result of bad credentials so we will continue with // the next element in the array } } } else { // use the admin bind credentials $dn = $this->dn; if(!empty($this->overlay_dn)) { $dn .= "," . $this->overlay_dn; } $this->bind($dn, $this->password); } // if it hits this return then the connection was successful and // the binding was also successful return true; } catch(BindException $be) { // could not bind with the provided credentials (admin bind) return false; } catch(Exception $e) { throw $e; } // could not bind with the provided credentials (regular user bind) or // something else went wrong return false; }
php
public function connect($username="", $password="") { // make sure the ldap extension has been loaded if(!extension_loaded('ldap')) { throw new LdapExtensionNotLoadedException(); } $params = array( 'hostname' => $this->host, 'base_dn' => $this->basedn, 'options' => [ ConnectionInterface::OPT_PROTOCOL_VERSION => $this->version, ], ); // if there is an overlay, use that as the base DN instead if(!empty($this->overlay_dn)) { $params['base_dn'] = $this->overlay_dn; } $this->ldap = new Manager($params, new Driver()); // connect to the server and bind with the credentials try { $this->ldap->connect(); // if override parameters have been specified then use those // for the binding operation if(!empty($username)) { foreach($this->basedn_array as $basedn) { try { // bind by uid; append the overlay DN if one has been specified $selectedUsername = $this->search_username . "=" . $username; if(!empty($basedn)) { $selectedUsername .= "," . $basedn; } $selectedPassword = ""; // do we allow empty passwords for bind attempts? if(empty($password)) { if($this->allowNoPass) { // yes so use the constructor-provided DN and password $selectedUsername = $this->dn; $selectedPassword = $this->password; } } else { // password provided so use what we were given $selectedPassword = $password; } // append the overlay DN if it exists if(!empty($this->overlay_dn)) { $selectedUsername .= "," . $this->overlay_dn; } // now perform the bind $this->bind($selectedUsername, $selectedPassword); // if we get here without hitting an exception, the bind // was successful return true; } catch(BindException $e) { // just because we hit a bind exception it doesn't mean // that there was an error; this could have been the // result of bad credentials so we will continue with // the next element in the array } } } else { // use the admin bind credentials $dn = $this->dn; if(!empty($this->overlay_dn)) { $dn .= "," . $this->overlay_dn; } $this->bind($dn, $this->password); } // if it hits this return then the connection was successful and // the binding was also successful return true; } catch(BindException $be) { // could not bind with the provided credentials (admin bind) return false; } catch(Exception $e) { throw $e; } // could not bind with the provided credentials (regular user bind) or // something else went wrong return false; }
[ "public", "function", "connect", "(", "$", "username", "=", "\"\"", ",", "$", "password", "=", "\"\"", ")", "{", "// make sure the ldap extension has been loaded", "if", "(", "!", "extension_loaded", "(", "'ldap'", ")", ")", "{", "throw", "new", "LdapExtensionNotLoadedException", "(", ")", ";", "}", "$", "params", "=", "array", "(", "'hostname'", "=>", "$", "this", "->", "host", ",", "'base_dn'", "=>", "$", "this", "->", "basedn", ",", "'options'", "=>", "[", "ConnectionInterface", "::", "OPT_PROTOCOL_VERSION", "=>", "$", "this", "->", "version", ",", "]", ",", ")", ";", "// if there is an overlay, use that as the base DN instead", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "$", "params", "[", "'base_dn'", "]", "=", "$", "this", "->", "overlay_dn", ";", "}", "$", "this", "->", "ldap", "=", "new", "Manager", "(", "$", "params", ",", "new", "Driver", "(", ")", ")", ";", "// connect to the server and bind with the credentials", "try", "{", "$", "this", "->", "ldap", "->", "connect", "(", ")", ";", "// if override parameters have been specified then use those", "// for the binding operation", "if", "(", "!", "empty", "(", "$", "username", ")", ")", "{", "foreach", "(", "$", "this", "->", "basedn_array", "as", "$", "basedn", ")", "{", "try", "{", "// bind by uid; append the overlay DN if one has been specified", "$", "selectedUsername", "=", "$", "this", "->", "search_username", ".", "\"=\"", ".", "$", "username", ";", "if", "(", "!", "empty", "(", "$", "basedn", ")", ")", "{", "$", "selectedUsername", ".=", "\",\"", ".", "$", "basedn", ";", "}", "$", "selectedPassword", "=", "\"\"", ";", "// do we allow empty passwords for bind attempts?", "if", "(", "empty", "(", "$", "password", ")", ")", "{", "if", "(", "$", "this", "->", "allowNoPass", ")", "{", "// yes so use the constructor-provided DN and password", "$", "selectedUsername", "=", "$", "this", "->", "dn", ";", "$", "selectedPassword", "=", "$", "this", "->", "password", ";", "}", "}", "else", "{", "// password provided so use what we were given", "$", "selectedPassword", "=", "$", "password", ";", "}", "// append the overlay DN if it exists", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "$", "selectedUsername", ".=", "\",\"", ".", "$", "this", "->", "overlay_dn", ";", "}", "// now perform the bind", "$", "this", "->", "bind", "(", "$", "selectedUsername", ",", "$", "selectedPassword", ")", ";", "// if we get here without hitting an exception, the bind", "// was successful", "return", "true", ";", "}", "catch", "(", "BindException", "$", "e", ")", "{", "// just because we hit a bind exception it doesn't mean", "// that there was an error; this could have been the", "// result of bad credentials so we will continue with", "// the next element in the array", "}", "}", "}", "else", "{", "// use the admin bind credentials", "$", "dn", "=", "$", "this", "->", "dn", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "$", "dn", ".=", "\",\"", ".", "$", "this", "->", "overlay_dn", ";", "}", "$", "this", "->", "bind", "(", "$", "dn", ",", "$", "this", "->", "password", ")", ";", "}", "// if it hits this return then the connection was successful and", "// the binding was also successful", "return", "true", ";", "}", "catch", "(", "BindException", "$", "be", ")", "{", "// could not bind with the provided credentials (admin bind)", "return", "false", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "// could not bind with the provided credentials (regular user bind) or", "// something else went wrong", "return", "false", ";", "}" ]
Connects and binds to the LDAP server. An optional username and password can be supplied to override the default credentials. Returns whether the connection and binding was successful. @param string $username The override username to use @param string $password The override password to use @throws LdapExtensionNotLoadedException If the LDAP extension has not been installed and loaded @throws Exception If the LDAP connection fails @return boolean
[ "Connects", "and", "binds", "to", "the", "LDAP", "server", ".", "An", "optional", "username", "and", "password", "can", "be", "supplied", "to", "override", "the", "default", "credentials", ".", "Returns", "whether", "the", "connection", "and", "binding", "was", "successful", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L165-L267
13,396
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.connectByDN
public function connectByDN($dn, $password="") { // make sure the ldap extension has been loaded if(!extension_loaded('ldap')) { throw new LdapExtensionNotLoadedException(); } $params = array( 'hostname' => $this->host, 'base_dn' => $this->basedn, 'options' => [ ConnectionInterface::OPT_PROTOCOL_VERSION => $this->version, ], ); // if there is an overlay, use that as the base DN instead if(!empty($this->overlay_dn)) { $params['base_dn'] = $this->overlay_dn; } $this->ldap = new Manager($params, new Driver()); // connect to the server and bind with the credentials try { $this->ldap->connect(); // if we do not have a password specified, use the admin DN and // password for the connection operation if(empty($password)) { if($this->allowNoPass) { // yes so use the constructor-provided DN and password $dn = $this->dn; if(!empty($this->overlay_dn)) { $dn .= "," . $this->overlay_dn; } $password = $this->password; } } $this->bind($dn, $password); // if it hits this return then the connection was successful and // the binding was also successful return true; } catch(BindException $be) { // could not bind with the provided credentials return false; } catch(Exception $e) { throw $e; } // something else went wrong return false; }
php
public function connectByDN($dn, $password="") { // make sure the ldap extension has been loaded if(!extension_loaded('ldap')) { throw new LdapExtensionNotLoadedException(); } $params = array( 'hostname' => $this->host, 'base_dn' => $this->basedn, 'options' => [ ConnectionInterface::OPT_PROTOCOL_VERSION => $this->version, ], ); // if there is an overlay, use that as the base DN instead if(!empty($this->overlay_dn)) { $params['base_dn'] = $this->overlay_dn; } $this->ldap = new Manager($params, new Driver()); // connect to the server and bind with the credentials try { $this->ldap->connect(); // if we do not have a password specified, use the admin DN and // password for the connection operation if(empty($password)) { if($this->allowNoPass) { // yes so use the constructor-provided DN and password $dn = $this->dn; if(!empty($this->overlay_dn)) { $dn .= "," . $this->overlay_dn; } $password = $this->password; } } $this->bind($dn, $password); // if it hits this return then the connection was successful and // the binding was also successful return true; } catch(BindException $be) { // could not bind with the provided credentials return false; } catch(Exception $e) { throw $e; } // something else went wrong return false; }
[ "public", "function", "connectByDN", "(", "$", "dn", ",", "$", "password", "=", "\"\"", ")", "{", "// make sure the ldap extension has been loaded", "if", "(", "!", "extension_loaded", "(", "'ldap'", ")", ")", "{", "throw", "new", "LdapExtensionNotLoadedException", "(", ")", ";", "}", "$", "params", "=", "array", "(", "'hostname'", "=>", "$", "this", "->", "host", ",", "'base_dn'", "=>", "$", "this", "->", "basedn", ",", "'options'", "=>", "[", "ConnectionInterface", "::", "OPT_PROTOCOL_VERSION", "=>", "$", "this", "->", "version", ",", "]", ",", ")", ";", "// if there is an overlay, use that as the base DN instead", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "$", "params", "[", "'base_dn'", "]", "=", "$", "this", "->", "overlay_dn", ";", "}", "$", "this", "->", "ldap", "=", "new", "Manager", "(", "$", "params", ",", "new", "Driver", "(", ")", ")", ";", "// connect to the server and bind with the credentials", "try", "{", "$", "this", "->", "ldap", "->", "connect", "(", ")", ";", "// if we do not have a password specified, use the admin DN and", "// password for the connection operation", "if", "(", "empty", "(", "$", "password", ")", ")", "{", "if", "(", "$", "this", "->", "allowNoPass", ")", "{", "// yes so use the constructor-provided DN and password", "$", "dn", "=", "$", "this", "->", "dn", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "$", "dn", ".=", "\",\"", ".", "$", "this", "->", "overlay_dn", ";", "}", "$", "password", "=", "$", "this", "->", "password", ";", "}", "}", "$", "this", "->", "bind", "(", "$", "dn", ",", "$", "password", ")", ";", "// if it hits this return then the connection was successful and", "// the binding was also successful", "return", "true", ";", "}", "catch", "(", "BindException", "$", "be", ")", "{", "// could not bind with the provided credentials", "return", "false", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "throw", "$", "e", ";", "}", "// something else went wrong", "return", "false", ";", "}" ]
Connects and binds to the LDAP server based on the provided DN and an optional password. Returns whether the connection and binding were successful. @param string $dn The bind DN to use @param string $password An optional password to use @throws LdapExtensionNotLoadedException If the LDAP extension has not been installed and loaded @throws Exception If the LDAP connection fails @return boolean
[ "Connects", "and", "binds", "to", "the", "LDAP", "server", "based", "on", "the", "provided", "DN", "and", "an", "optional", "password", ".", "Returns", "whether", "the", "connection", "and", "binding", "were", "successful", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L282-L339
13,397
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.getAttributeFromResults
public function getAttributeFromResults($results, $attr_name) { foreach($results as $node) { if($attr_name == "dn") { return $node->getDn(); } foreach($node->getAttributes() as $attribute) { if (strtolower($attribute->getName()) == strtolower($attr_name)) { return $attribute->getValues()[0]; // attribute found } } } return null; }
php
public function getAttributeFromResults($results, $attr_name) { foreach($results as $node) { if($attr_name == "dn") { return $node->getDn(); } foreach($node->getAttributes() as $attribute) { if (strtolower($attribute->getName()) == strtolower($attr_name)) { return $attribute->getValues()[0]; // attribute found } } } return null; }
[ "public", "function", "getAttributeFromResults", "(", "$", "results", ",", "$", "attr_name", ")", "{", "foreach", "(", "$", "results", "as", "$", "node", ")", "{", "if", "(", "$", "attr_name", "==", "\"dn\"", ")", "{", "return", "$", "node", "->", "getDn", "(", ")", ";", "}", "foreach", "(", "$", "node", "->", "getAttributes", "(", ")", "as", "$", "attribute", ")", "{", "if", "(", "strtolower", "(", "$", "attribute", "->", "getName", "(", ")", ")", "==", "strtolower", "(", "$", "attr_name", ")", ")", "{", "return", "$", "attribute", "->", "getValues", "(", ")", "[", "0", "]", ";", "// attribute found", "}", "}", "}", "return", "null", ";", "}" ]
Returns the value of the specified attribute from the result set. Returns null if the attribute could not be found. @param Result-instance $results The result-set to search through @param string $attr_name The attribute name to look for @return string|integer|boolean|null
[ "Returns", "the", "value", "of", "the", "specified", "attribute", "from", "the", "result", "set", ".", "Returns", "null", "if", "the", "attribute", "could", "not", "be", "found", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L349-L362
13,398
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.searchByAuth
public function searchByAuth($value) { // figure out how many times the placeholder occurs, then fill an // array that number of times with the search value $numArgs = substr_count($this->search_auth_query, "%s"); $args = array_fill(0, $numArgs, $value); // format the string and then perform the search for each base DN $searchStr = vsprintf($this->search_auth_query, $args); // iterate over the array of base DNs and perform the searches; we will // return the first result set that matches our query $results = null; foreach($this->basedn_array as $basedn) { // add the overlay if it exists if(!empty($this->overlay_dn)) { // append the overlay if we do have a base DN or use the // overlay as the base DN if not if(!empty($basedn)) { $basedn .= ',' . $this->overlay_dn; } else { $basedn = $this->overlay_dn; } } $results = $this->ldap->search($basedn, $searchStr); if($this->isValidResult($results)) { return $results; } } // ensures that there is some result set that is returned based upon // one of the loop iterations even if we did not match our desired // condition return $results; }
php
public function searchByAuth($value) { // figure out how many times the placeholder occurs, then fill an // array that number of times with the search value $numArgs = substr_count($this->search_auth_query, "%s"); $args = array_fill(0, $numArgs, $value); // format the string and then perform the search for each base DN $searchStr = vsprintf($this->search_auth_query, $args); // iterate over the array of base DNs and perform the searches; we will // return the first result set that matches our query $results = null; foreach($this->basedn_array as $basedn) { // add the overlay if it exists if(!empty($this->overlay_dn)) { // append the overlay if we do have a base DN or use the // overlay as the base DN if not if(!empty($basedn)) { $basedn .= ',' . $this->overlay_dn; } else { $basedn = $this->overlay_dn; } } $results = $this->ldap->search($basedn, $searchStr); if($this->isValidResult($results)) { return $results; } } // ensures that there is some result set that is returned based upon // one of the loop iterations even if we did not match our desired // condition return $results; }
[ "public", "function", "searchByAuth", "(", "$", "value", ")", "{", "// figure out how many times the placeholder occurs, then fill an", "// array that number of times with the search value", "$", "numArgs", "=", "substr_count", "(", "$", "this", "->", "search_auth_query", ",", "\"%s\"", ")", ";", "$", "args", "=", "array_fill", "(", "0", ",", "$", "numArgs", ",", "$", "value", ")", ";", "// format the string and then perform the search for each base DN", "$", "searchStr", "=", "vsprintf", "(", "$", "this", "->", "search_auth_query", ",", "$", "args", ")", ";", "// iterate over the array of base DNs and perform the searches; we will", "// return the first result set that matches our query", "$", "results", "=", "null", ";", "foreach", "(", "$", "this", "->", "basedn_array", "as", "$", "basedn", ")", "{", "// add the overlay if it exists", "if", "(", "!", "empty", "(", "$", "this", "->", "overlay_dn", ")", ")", "{", "// append the overlay if we do have a base DN or use the", "// overlay as the base DN if not", "if", "(", "!", "empty", "(", "$", "basedn", ")", ")", "{", "$", "basedn", ".=", "','", ".", "$", "this", "->", "overlay_dn", ";", "}", "else", "{", "$", "basedn", "=", "$", "this", "->", "overlay_dn", ";", "}", "}", "$", "results", "=", "$", "this", "->", "ldap", "->", "search", "(", "$", "basedn", ",", "$", "searchStr", ")", ";", "if", "(", "$", "this", "->", "isValidResult", "(", "$", "results", ")", ")", "{", "return", "$", "results", ";", "}", "}", "// ensures that there is some result set that is returned based upon", "// one of the loop iterations even if we did not match our desired", "// condition", "return", "$", "results", ";", "}" ]
Queries LDAP for the record with the specified value for attributes matching what could commonly be used for authentication. For the purposes of this method, uid, mail and mailLocalAddress are searched by default unless their values have been overridden. @param string $value The value to use for searching @return Result-instance
[ "Queries", "LDAP", "for", "the", "record", "with", "the", "specified", "value", "for", "attributes", "matching", "what", "could", "commonly", "be", "used", "for", "authentication", ".", "For", "the", "purposes", "of", "this", "method", "uid", "mail", "and", "mailLocalAddress", "are", "searched", "by", "default", "unless", "their", "values", "have", "been", "overridden", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L383-L419
13,399
csun-metalab/laravel-directory-authentication
src/Authentication/Handlers/HandlerLDAP.php
HandlerLDAP.searchByEmail
public function searchByEmail($email) { $results = $this->ldap->search($this->basedn, $this->search_mail . '=' . $email); return $results; }
php
public function searchByEmail($email) { $results = $this->ldap->search($this->basedn, $this->search_mail . '=' . $email); return $results; }
[ "public", "function", "searchByEmail", "(", "$", "email", ")", "{", "$", "results", "=", "$", "this", "->", "ldap", "->", "search", "(", "$", "this", "->", "basedn", ",", "$", "this", "->", "search_mail", ".", "'='", ".", "$", "email", ")", ";", "return", "$", "results", ";", "}" ]
Queries LDAP for the record with the specified email. @param string $email The email to use for searching @return Result-instance
[ "Queries", "LDAP", "for", "the", "record", "with", "the", "specified", "email", "." ]
b8d4fa64dd646566e508cdf838d6a3d03b1d53ea
https://github.com/csun-metalab/laravel-directory-authentication/blob/b8d4fa64dd646566e508cdf838d6a3d03b1d53ea/src/Authentication/Handlers/HandlerLDAP.php#L427-L431