repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/storage/storage_set.php
ezcMailStorageSet.getNextLine
public function getNextLine() { if ( $this->hasMoreMailData === false ) { $this->nextMail(); $this->hasMoreMailData = true; } $line = $this->set->getNextLine(); fputs( $this->writer, $line ); return $line; }
php
public function getNextLine() { if ( $this->hasMoreMailData === false ) { $this->nextMail(); $this->hasMoreMailData = true; } $line = $this->set->getNextLine(); fputs( $this->writer, $line ); return $line; }
[ "public", "function", "getNextLine", "(", ")", "{", "if", "(", "$", "this", "->", "hasMoreMailData", "===", "false", ")", "{", "$", "this", "->", "nextMail", "(", ")", ";", "$", "this", "->", "hasMoreMailData", "=", "true", ";", "}", "$", "line", "=", "$", "this", "->", "set", "->", "getNextLine", "(", ")", ";", "fputs", "(", "$", "this", "->", "writer", ",", "$", "line", ")", ";", "return", "$", "line", ";", "}" ]
Returns one line of data from the current mail in the set. Null is returned if there is no current mail in the set or the end of the mail is reached, It also writes the line of data to the current file. If the line contains a Message-ID header then the value in the header will be used to rename the file. @return string
[ "Returns", "one", "line", "of", "data", "from", "the", "current", "mail", "in", "the", "set", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/storage/storage_set.php#L140-L151
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/storage/storage_set.php
ezcMailStorageSet.nextMail
public function nextMail() { if ( $this->writer !== null ) { fclose( $this->writer ); $this->files[] = $this->path . $this->file; $this->writer = null; } $mail = $this->set->nextMail(); if ( $mail === true || $this->hasMoreMailData === false ) { $this->counter++; // Temporary file name for the mail source $this->file = getmypid() . '-' . time() . '-' . $this->counter; $writer = fopen( $this->path . $this->file, 'w' ); if ( $writer !== false ) { $this->writer = $writer; } return $mail; } return false; }
php
public function nextMail() { if ( $this->writer !== null ) { fclose( $this->writer ); $this->files[] = $this->path . $this->file; $this->writer = null; } $mail = $this->set->nextMail(); if ( $mail === true || $this->hasMoreMailData === false ) { $this->counter++; // Temporary file name for the mail source $this->file = getmypid() . '-' . time() . '-' . $this->counter; $writer = fopen( $this->path . $this->file, 'w' ); if ( $writer !== false ) { $this->writer = $writer; } return $mail; } return false; }
[ "public", "function", "nextMail", "(", ")", "{", "if", "(", "$", "this", "->", "writer", "!==", "null", ")", "{", "fclose", "(", "$", "this", "->", "writer", ")", ";", "$", "this", "->", "files", "[", "]", "=", "$", "this", "->", "path", ".", "$", "this", "->", "file", ";", "$", "this", "->", "writer", "=", "null", ";", "}", "$", "mail", "=", "$", "this", "->", "set", "->", "nextMail", "(", ")", ";", "if", "(", "$", "mail", "===", "true", "||", "$", "this", "->", "hasMoreMailData", "===", "false", ")", "{", "$", "this", "->", "counter", "++", ";", "// Temporary file name for the mail source", "$", "this", "->", "file", "=", "getmypid", "(", ")", ".", "'-'", ".", "time", "(", ")", ".", "'-'", ".", "$", "this", "->", "counter", ";", "$", "writer", "=", "fopen", "(", "$", "this", "->", "path", ".", "$", "this", "->", "file", ",", "'w'", ")", ";", "if", "(", "$", "writer", "!==", "false", ")", "{", "$", "this", "->", "writer", "=", "$", "writer", ";", "}", "return", "$", "mail", ";", "}", "return", "false", ";", "}" ]
Moves the set to the next mail and returns true upon success. False is returned if there are no more mail in the set. @return bool
[ "Moves", "the", "set", "to", "the", "next", "mail", "and", "returns", "true", "upon", "success", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/transports/storage/storage_set.php#L160-L183
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.extractNumerics
static function extractNumerics($string, array $include = []) { // Make sure it's string $string = (string) $string; // Set numerics $numerics = ''; // Get length $len = strlen($string); // Loop through string for ($i = 0; $i < $len; $i++) { // If digit if (static::isDigit($string[$i])) { // Append to numerics $numerics .= $string[$i]; } // If decimal if ($include && in_array($string[$i], $include)) { // Append to numerics $numerics .= $string[$i]; } } // Return numerics return $numerics; }
php
static function extractNumerics($string, array $include = []) { // Make sure it's string $string = (string) $string; // Set numerics $numerics = ''; // Get length $len = strlen($string); // Loop through string for ($i = 0; $i < $len; $i++) { // If digit if (static::isDigit($string[$i])) { // Append to numerics $numerics .= $string[$i]; } // If decimal if ($include && in_array($string[$i], $include)) { // Append to numerics $numerics .= $string[$i]; } } // Return numerics return $numerics; }
[ "static", "function", "extractNumerics", "(", "$", "string", ",", "array", "$", "include", "=", "[", "]", ")", "{", "// Make sure it's string", "$", "string", "=", "(", "string", ")", "$", "string", ";", "// Set numerics", "$", "numerics", "=", "''", ";", "// Get length", "$", "len", "=", "strlen", "(", "$", "string", ")", ";", "// Loop through string", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "$", "i", "++", ")", "{", "// If digit", "if", "(", "static", "::", "isDigit", "(", "$", "string", "[", "$", "i", "]", ")", ")", "{", "// Append to numerics", "$", "numerics", ".=", "$", "string", "[", "$", "i", "]", ";", "}", "// If decimal", "if", "(", "$", "include", "&&", "in_array", "(", "$", "string", "[", "$", "i", "]", ",", "$", "include", ")", ")", "{", "// Append to numerics", "$", "numerics", ".=", "$", "string", "[", "$", "i", "]", ";", "}", "}", "// Return numerics", "return", "$", "numerics", ";", "}" ]
Extract numeric @return string The numeric string
[ "Extract", "numeric" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L25-L47
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.parseMobileNumber
static function parseMobileNumber($number) { // Extract numerics $numerics = static::extractNumerics($number); // Set country code $countryCode = ''; // Get last 10 digits $short = static::right($numerics, 10, $countryCode); // Set carrier code $carriercode = ''; // Get number $number = static::right($short, 7, $carrierCode); // Return return compact('countryCode', 'carrierCode', 'number'); }
php
static function parseMobileNumber($number) { // Extract numerics $numerics = static::extractNumerics($number); // Set country code $countryCode = ''; // Get last 10 digits $short = static::right($numerics, 10, $countryCode); // Set carrier code $carriercode = ''; // Get number $number = static::right($short, 7, $carrierCode); // Return return compact('countryCode', 'carrierCode', 'number'); }
[ "static", "function", "parseMobileNumber", "(", "$", "number", ")", "{", "// Extract numerics", "$", "numerics", "=", "static", "::", "extractNumerics", "(", "$", "number", ")", ";", "// Set country code", "$", "countryCode", "=", "''", ";", "// Get last 10 digits", "$", "short", "=", "static", "::", "right", "(", "$", "numerics", ",", "10", ",", "$", "countryCode", ")", ";", "// Set carrier code", "$", "carriercode", "=", "''", ";", "// Get number", "$", "number", "=", "static", "::", "right", "(", "$", "short", ",", "7", ",", "$", "carrierCode", ")", ";", "// Return", "return", "compact", "(", "'countryCode'", ",", "'carrierCode'", ",", "'number'", ")", ";", "}" ]
Parse mobile number
[ "Parse", "mobile", "number" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L52-L65
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.right
static function right($str, $len, &$left = null) { // Get length of string $strlen = strlen($str); // Get start $start = $strlen - $len; // If start is less than 0 if ($start < 0) { // Set to 0 $start = 0; } // Set left $left = substr($str, 0, $start); // Return return substr($str, $start); }
php
static function right($str, $len, &$left = null) { // Get length of string $strlen = strlen($str); // Get start $start = $strlen - $len; // If start is less than 0 if ($start < 0) { // Set to 0 $start = 0; } // Set left $left = substr($str, 0, $start); // Return return substr($str, $start); }
[ "static", "function", "right", "(", "$", "str", ",", "$", "len", ",", "&", "$", "left", "=", "null", ")", "{", "// Get length of string", "$", "strlen", "=", "strlen", "(", "$", "str", ")", ";", "// Get start", "$", "start", "=", "$", "strlen", "-", "$", "len", ";", "// If start is less than 0", "if", "(", "$", "start", "<", "0", ")", "{", "// Set to 0", "$", "start", "=", "0", ";", "}", "// Set left", "$", "left", "=", "substr", "(", "$", "str", ",", "0", ",", "$", "start", ")", ";", "// Return", "return", "substr", "(", "$", "str", ",", "$", "start", ")", ";", "}" ]
Get substr
[ "Get", "substr" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L70-L84
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.arrayExtract
static function arrayExtract(array $keys, array $array, array $callbacks = []) { // Set extracted $extracted = []; // Loop through keys foreach ($keys as $key) { // Add to extracted, only if it exists if (array_key_exists($key, $array)) { // Set item $item = $array[$key]; // If there's a callback if (isset($callbacks[$key]) && is_callable($callbacks[$key])) { // Call it $item = call_user_func_array($callbacks[$key], [$item]); } // Add to extracted $extracted[$key] = $item; } } // Return extracted return $extracted; }
php
static function arrayExtract(array $keys, array $array, array $callbacks = []) { // Set extracted $extracted = []; // Loop through keys foreach ($keys as $key) { // Add to extracted, only if it exists if (array_key_exists($key, $array)) { // Set item $item = $array[$key]; // If there's a callback if (isset($callbacks[$key]) && is_callable($callbacks[$key])) { // Call it $item = call_user_func_array($callbacks[$key], [$item]); } // Add to extracted $extracted[$key] = $item; } } // Return extracted return $extracted; }
[ "static", "function", "arrayExtract", "(", "array", "$", "keys", ",", "array", "$", "array", ",", "array", "$", "callbacks", "=", "[", "]", ")", "{", "// Set extracted", "$", "extracted", "=", "[", "]", ";", "// Loop through keys", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "// Add to extracted, only if it exists", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "array", ")", ")", "{", "// Set item", "$", "item", "=", "$", "array", "[", "$", "key", "]", ";", "// If there's a callback", "if", "(", "isset", "(", "$", "callbacks", "[", "$", "key", "]", ")", "&&", "is_callable", "(", "$", "callbacks", "[", "$", "key", "]", ")", ")", "{", "// Call it", "$", "item", "=", "call_user_func_array", "(", "$", "callbacks", "[", "$", "key", "]", ",", "[", "$", "item", "]", ")", ";", "}", "// Add to extracted", "$", "extracted", "[", "$", "key", "]", "=", "$", "item", ";", "}", "}", "// Return extracted", "return", "$", "extracted", ";", "}" ]
Extract array from array with keys
[ "Extract", "array", "from", "array", "with", "keys" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L105-L125
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.arrayExcept
static function arrayExcept(array $keys, array $array) { // Except $except = []; // Loop through array foreach ($array as $key=> $item) { // If key doesn't exist if ( ! in_array($key, $keys)) { // Add to except $except[$key] = $item; } } // Return return $except; }
php
static function arrayExcept(array $keys, array $array) { // Except $except = []; // Loop through array foreach ($array as $key=> $item) { // If key doesn't exist if ( ! in_array($key, $keys)) { // Add to except $except[$key] = $item; } } // Return return $except; }
[ "static", "function", "arrayExcept", "(", "array", "$", "keys", ",", "array", "$", "array", ")", "{", "// Except", "$", "except", "=", "[", "]", ";", "// Loop through array", "foreach", "(", "$", "array", "as", "$", "key", "=>", "$", "item", ")", "{", "// If key doesn't exist", "if", "(", "!", "in_array", "(", "$", "key", ",", "$", "keys", ")", ")", "{", "// Add to except", "$", "except", "[", "$", "key", "]", "=", "$", "item", ";", "}", "}", "// Return", "return", "$", "except", ";", "}" ]
Except
[ "Except" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L130-L143
ronaldborla/chikka
src/Borla/Chikka/Support/Utilities.php
Utilities.executeCallback
static function executeCallback($callback, array $params = array()) { // If callback has @ if (is_string($callback) && strpos($callback, '@') !== false) { // Split $arrCallback = explode('@', $callback); // Set object $object = class_exists($arrCallback[0]) ? (new $arrCallback[0]()) : null; // Set method $method = isset($arrCallback[0]) ? $arrCallback[0] : null; // Set callback $callback = array($object, $method); } // If not callable if ( ! is_callable($callback)) { // Throw error throw new InvalidCallback('Callback must be callable'); } // Execute and return return call_user_func_array($callback, $params); }
php
static function executeCallback($callback, array $params = array()) { // If callback has @ if (is_string($callback) && strpos($callback, '@') !== false) { // Split $arrCallback = explode('@', $callback); // Set object $object = class_exists($arrCallback[0]) ? (new $arrCallback[0]()) : null; // Set method $method = isset($arrCallback[0]) ? $arrCallback[0] : null; // Set callback $callback = array($object, $method); } // If not callable if ( ! is_callable($callback)) { // Throw error throw new InvalidCallback('Callback must be callable'); } // Execute and return return call_user_func_array($callback, $params); }
[ "static", "function", "executeCallback", "(", "$", "callback", ",", "array", "$", "params", "=", "array", "(", ")", ")", "{", "// If callback has @", "if", "(", "is_string", "(", "$", "callback", ")", "&&", "strpos", "(", "$", "callback", ",", "'@'", ")", "!==", "false", ")", "{", "// Split", "$", "arrCallback", "=", "explode", "(", "'@'", ",", "$", "callback", ")", ";", "// Set object", "$", "object", "=", "class_exists", "(", "$", "arrCallback", "[", "0", "]", ")", "?", "(", "new", "$", "arrCallback", "[", "0", "]", "(", ")", ")", ":", "null", ";", "// Set method", "$", "method", "=", "isset", "(", "$", "arrCallback", "[", "0", "]", ")", "?", "$", "arrCallback", "[", "0", "]", ":", "null", ";", "// Set callback", "$", "callback", "=", "array", "(", "$", "object", ",", "$", "method", ")", ";", "}", "// If not callable", "if", "(", "!", "is_callable", "(", "$", "callback", ")", ")", "{", "// Throw error", "throw", "new", "InvalidCallback", "(", "'Callback must be callable'", ")", ";", "}", "// Execute and return", "return", "call_user_func_array", "(", "$", "callback", ",", "$", "params", ")", ";", "}" ]
Execute callback
[ "Execute", "callback" ]
train
https://github.com/ronaldborla/chikka/blob/446987706f81d5a0efbc8bd6b7d3b259d0527719/src/Borla/Chikka/Support/Utilities.php#L148-L167
j-d/draggy
src/Draggy/Autocode/Templates/JavaEntityTemplate.php
JavaEntityTemplate.getFullPackage
public function getFullPackage($entity = null) { if (null === $entity) { $entity = $this->getEntity(); } return substr($entity->getProject()->getAutocodeConfiguration('package') . '.' . str_replace('/', '.', ($entity->getModule() != '' ? $entity->getModule() . '/' : '') . $this->getPath()), 0, -1); }
php
public function getFullPackage($entity = null) { if (null === $entity) { $entity = $this->getEntity(); } return substr($entity->getProject()->getAutocodeConfiguration('package') . '.' . str_replace('/', '.', ($entity->getModule() != '' ? $entity->getModule() . '/' : '') . $this->getPath()), 0, -1); }
[ "public", "function", "getFullPackage", "(", "$", "entity", "=", "null", ")", "{", "if", "(", "null", "===", "$", "entity", ")", "{", "$", "entity", "=", "$", "this", "->", "getEntity", "(", ")", ";", "}", "return", "substr", "(", "$", "entity", "->", "getProject", "(", ")", "->", "getAutocodeConfiguration", "(", "'package'", ")", ".", "'.'", ".", "str_replace", "(", "'/'", ",", "'.'", ",", "(", "$", "entity", "->", "getModule", "(", ")", "!=", "''", "?", "$", "entity", "->", "getModule", "(", ")", ".", "'/'", ":", "''", ")", ".", "$", "this", "->", "getPath", "(", ")", ")", ",", "0", ",", "-", "1", ")", ";", "}" ]
@param Entity $entity @return string
[ "@param", "Entity", "$entity" ]
train
https://github.com/j-d/draggy/blob/97ffc66e1aacb5f685d7aac5251c4abb8888d4bb/src/Draggy/Autocode/Templates/JavaEntityTemplate.php#L177-L184
mvccore/ext-router-module
src/MvcCore/Ext/Routers/Modules/Route/UrlBuilding.php
UrlBuilding.Url
public function Url (\MvcCore\IRequest & $request, array & $params = [], array & $defaultUrlParams = [], $queryStringParamsSepatator = '&', $splitUrl = FALSE) { // check reverse initialization if ($this->reverseParams === NULL) $this->initReverse(); // complete and filter all params to build reverse pattern if (count($this->reverseParams) === 0) { $allParamsClone = array_merge([], $params); } else {// complete params with necessary values to build reverse pattern (and than query string) $emptyReverseParams = array_fill_keys(array_keys($this->reverseParams), ''); $allMergedParams = array_merge($this->defaults, $defaultUrlParams, $params); // all params clone contains only keys necessary to build reverse // pattern for this route and all given `$params` keys, nothing more // from currently requested URL $allParamsClone = array_merge( $emptyReverseParams, array_intersect_key($allMergedParams, $emptyReverseParams), $params ); } // filter params list(,$filteredParams) = $this->Filter($allParamsClone, $defaultUrlParams, \MvcCore\IRoute::CONFIG_FILTER_OUT); // convert all domain param values to lower case $router = & $this->router; foreach ($filteredParams as $paramName => & $paramValue) { if ($paramName == $router::URL_PARAM_BASEPATH) continue; if (is_string($paramValue)) $paramValue = mb_strtolower($paramValue); } // split params into domain params array and into path and query params array $domainPercentageParams = $this->urlGetAndRemoveDomainPercentageParams($filteredParams); // build reverse pattern $result = $this->urlComposeByReverseSectionsAndParams( $this->reverse, $this->reverseSections, $this->reverseParams, $filteredParams, $this->defaults ); return $this->urlAbsPartAndSplit($request, $result, $domainPercentageParams, $splitUrl); }
php
public function Url (\MvcCore\IRequest & $request, array & $params = [], array & $defaultUrlParams = [], $queryStringParamsSepatator = '&', $splitUrl = FALSE) { // check reverse initialization if ($this->reverseParams === NULL) $this->initReverse(); // complete and filter all params to build reverse pattern if (count($this->reverseParams) === 0) { $allParamsClone = array_merge([], $params); } else {// complete params with necessary values to build reverse pattern (and than query string) $emptyReverseParams = array_fill_keys(array_keys($this->reverseParams), ''); $allMergedParams = array_merge($this->defaults, $defaultUrlParams, $params); // all params clone contains only keys necessary to build reverse // pattern for this route and all given `$params` keys, nothing more // from currently requested URL $allParamsClone = array_merge( $emptyReverseParams, array_intersect_key($allMergedParams, $emptyReverseParams), $params ); } // filter params list(,$filteredParams) = $this->Filter($allParamsClone, $defaultUrlParams, \MvcCore\IRoute::CONFIG_FILTER_OUT); // convert all domain param values to lower case $router = & $this->router; foreach ($filteredParams as $paramName => & $paramValue) { if ($paramName == $router::URL_PARAM_BASEPATH) continue; if (is_string($paramValue)) $paramValue = mb_strtolower($paramValue); } // split params into domain params array and into path and query params array $domainPercentageParams = $this->urlGetAndRemoveDomainPercentageParams($filteredParams); // build reverse pattern $result = $this->urlComposeByReverseSectionsAndParams( $this->reverse, $this->reverseSections, $this->reverseParams, $filteredParams, $this->defaults ); return $this->urlAbsPartAndSplit($request, $result, $domainPercentageParams, $splitUrl); }
[ "public", "function", "Url", "(", "\\", "MvcCore", "\\", "IRequest", "&", "$", "request", ",", "array", "&", "$", "params", "=", "[", "]", ",", "array", "&", "$", "defaultUrlParams", "=", "[", "]", ",", "$", "queryStringParamsSepatator", "=", "'&'", ",", "$", "splitUrl", "=", "FALSE", ")", "{", "// check reverse initialization", "if", "(", "$", "this", "->", "reverseParams", "===", "NULL", ")", "$", "this", "->", "initReverse", "(", ")", ";", "// complete and filter all params to build reverse pattern", "if", "(", "count", "(", "$", "this", "->", "reverseParams", ")", "===", "0", ")", "{", "$", "allParamsClone", "=", "array_merge", "(", "[", "]", ",", "$", "params", ")", ";", "}", "else", "{", "// complete params with necessary values to build reverse pattern (and than query string)", "$", "emptyReverseParams", "=", "array_fill_keys", "(", "array_keys", "(", "$", "this", "->", "reverseParams", ")", ",", "''", ")", ";", "$", "allMergedParams", "=", "array_merge", "(", "$", "this", "->", "defaults", ",", "$", "defaultUrlParams", ",", "$", "params", ")", ";", "// all params clone contains only keys necessary to build reverse ", "// pattern for this route and all given `$params` keys, nothing more ", "// from currently requested URL", "$", "allParamsClone", "=", "array_merge", "(", "$", "emptyReverseParams", ",", "array_intersect_key", "(", "$", "allMergedParams", ",", "$", "emptyReverseParams", ")", ",", "$", "params", ")", ";", "}", "// filter params", "list", "(", ",", "$", "filteredParams", ")", "=", "$", "this", "->", "Filter", "(", "$", "allParamsClone", ",", "$", "defaultUrlParams", ",", "\\", "MvcCore", "\\", "IRoute", "::", "CONFIG_FILTER_OUT", ")", ";", "// convert all domain param values to lower case", "$", "router", "=", "&", "$", "this", "->", "router", ";", "foreach", "(", "$", "filteredParams", "as", "$", "paramName", "=>", "&", "$", "paramValue", ")", "{", "if", "(", "$", "paramName", "==", "$", "router", "::", "URL_PARAM_BASEPATH", ")", "continue", ";", "if", "(", "is_string", "(", "$", "paramValue", ")", ")", "$", "paramValue", "=", "mb_strtolower", "(", "$", "paramValue", ")", ";", "}", "// split params into domain params array and into path and query params array", "$", "domainPercentageParams", "=", "$", "this", "->", "urlGetAndRemoveDomainPercentageParams", "(", "$", "filteredParams", ")", ";", "// build reverse pattern", "$", "result", "=", "$", "this", "->", "urlComposeByReverseSectionsAndParams", "(", "$", "this", "->", "reverse", ",", "$", "this", "->", "reverseSections", ",", "$", "this", "->", "reverseParams", ",", "$", "filteredParams", ",", "$", "this", "->", "defaults", ")", ";", "return", "$", "this", "->", "urlAbsPartAndSplit", "(", "$", "request", ",", "$", "result", ",", "$", "domainPercentageParams", ",", "$", "splitUrl", ")", ";", "}" ]
Complete route URL by given params array and route internal reverse replacements pattern string. If there are more given params in first argument than total count of replacement places in reverse pattern, then create URL with query string params after reverse pattern, containing that extra record(s) value(s). Returned is an array with two strings - result URL in two parts - first part as scheme, domain and base path and second as path and query string. Example: Input (`$params`): `[ "name" => "cool-product-name", "color" => "blue", "variants" => ["L", "XL"], ];` Input (`\MvcCore\Route::$reverse`): `"/products-list/<name>/<color*>"` Output: `[ "https://example.com/any/app/base/path", "/products-list/cool-product-name/blue?variant[]=L&amp;variant[]=XL" ]` @param \MvcCore\Request $request Currently requested request object. @param array $params URL params from application point completed by developer. @param array $defaultUrlParams Requested URL route params and query string params without escaped HTML special chars: `< > & " ' &`. @param string $queryStringParamsSepatator Query params separator, `&` by default. Always automatically completed by router instance. @param bool $splitUrl Boolean value about to split completed result URL into two parts or not. Default is FALSE to return a string array with only one record - the result URL. If `TRUE`, result url is split into two parts and function return array with two items. @return \string[] Result URL address in array. If last argument is `FALSE` by default, this function returns only single item array with result URL. If last argument is `TRUE`, function returns result URL in two parts - domain part with base path and path part with query string.
[ "Complete", "route", "URL", "by", "given", "params", "array", "and", "route", "internal", "reverse", "replacements", "pattern", "string", ".", "If", "there", "are", "more", "given", "params", "in", "first", "argument", "than", "total", "count", "of", "replacement", "places", "in", "reverse", "pattern", "then", "create", "URL", "with", "query", "string", "params", "after", "reverse", "pattern", "containing", "that", "extra", "record", "(", "s", ")", "value", "(", "s", ")", ".", "Returned", "is", "an", "array", "with", "two", "strings", "-", "result", "URL", "in", "two", "parts", "-", "first", "part", "as", "scheme", "domain", "and", "base", "path", "and", "second", "as", "path", "and", "query", "string", ".", "Example", ":", "Input", "(", "$params", ")", ":", "[", "name", "=", ">", "cool", "-", "product", "-", "name", "color", "=", ">", "blue", "variants", "=", ">", "[", "L", "XL", "]", "]", ";", "Input", "(", "\\", "MvcCore", "\\", "Route", "::", "$reverse", ")", ":", "/", "products", "-", "list", "/", "<name", ">", "/", "<color", "*", ">", "Output", ":", "[", "https", ":", "//", "example", ".", "com", "/", "any", "/", "app", "/", "base", "/", "path", "/", "products", "-", "list", "/", "cool", "-", "product", "-", "name", "/", "blue?variant", "[]", "=", "L&amp", ";", "variant", "[]", "=", "XL", "]" ]
train
https://github.com/mvccore/ext-router-module/blob/7695784a451db86cca6a43c98d076803cd0a50a7/src/MvcCore/Ext/Routers/Modules/Route/UrlBuilding.php#L65-L100
WellCommerce/AppBundle
EventListener/LayoutBoxSubscriber.php
LayoutBoxSubscriber.onLayoutBoxFormInit
public function onLayoutBoxFormInit(FormEvent $event) { $builder = $event->getFormBuilder(); $form = $event->getForm(); $configurators = $this->container->get('layout_box.configurator.collection')->all(); $resource = $event->getResource(); $boxSettings = $resource->getSettings(); foreach ($configurators as $configurator) { if ($configurator instanceof LayoutBoxConfiguratorInterface) { $defaults = []; if ($resource->getBoxType() == $configurator->getType()) { $defaults = $boxSettings; } $configurator->addFormFields($builder, $form, $defaults); } } }
php
public function onLayoutBoxFormInit(FormEvent $event) { $builder = $event->getFormBuilder(); $form = $event->getForm(); $configurators = $this->container->get('layout_box.configurator.collection')->all(); $resource = $event->getResource(); $boxSettings = $resource->getSettings(); foreach ($configurators as $configurator) { if ($configurator instanceof LayoutBoxConfiguratorInterface) { $defaults = []; if ($resource->getBoxType() == $configurator->getType()) { $defaults = $boxSettings; } $configurator->addFormFields($builder, $form, $defaults); } } }
[ "public", "function", "onLayoutBoxFormInit", "(", "FormEvent", "$", "event", ")", "{", "$", "builder", "=", "$", "event", "->", "getFormBuilder", "(", ")", ";", "$", "form", "=", "$", "event", "->", "getForm", "(", ")", ";", "$", "configurators", "=", "$", "this", "->", "container", "->", "get", "(", "'layout_box.configurator.collection'", ")", "->", "all", "(", ")", ";", "$", "resource", "=", "$", "event", "->", "getResource", "(", ")", ";", "$", "boxSettings", "=", "$", "resource", "->", "getSettings", "(", ")", ";", "foreach", "(", "$", "configurators", "as", "$", "configurator", ")", "{", "if", "(", "$", "configurator", "instanceof", "LayoutBoxConfiguratorInterface", ")", "{", "$", "defaults", "=", "[", "]", ";", "if", "(", "$", "resource", "->", "getBoxType", "(", ")", "==", "$", "configurator", "->", "getType", "(", ")", ")", "{", "$", "defaults", "=", "$", "boxSettings", ";", "}", "$", "configurator", "->", "addFormFields", "(", "$", "builder", ",", "$", "form", ",", "$", "defaults", ")", ";", "}", "}", "}" ]
Adds configurator fields to main layout box edit form. Loops through all configurators, renders the fieldset and sets default data @param FormEvent $event
[ "Adds", "configurator", "fields", "to", "main", "layout", "box", "edit", "form", ".", "Loops", "through", "all", "configurators", "renders", "the", "fieldset", "and", "sets", "default", "data" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/EventListener/LayoutBoxSubscriber.php#L43-L61
WellCommerce/AppBundle
EventListener/LayoutBoxSubscriber.php
LayoutBoxSubscriber.onLayoutBoxPreUpdate
public function onLayoutBoxPreUpdate(EntityEvent $event) { $resource = $event->getEntity(); if ($resource instanceof LayoutBox) { $request = $this->getRequestHelper()->getCurrentRequest(); $settings = $this->getBoxSettingsFromRequest($request); $settings = $this->mergeUnmodifiedSettings($resource->getSettings(), $settings); $resource->setSettings($settings); } }
php
public function onLayoutBoxPreUpdate(EntityEvent $event) { $resource = $event->getEntity(); if ($resource instanceof LayoutBox) { $request = $this->getRequestHelper()->getCurrentRequest(); $settings = $this->getBoxSettingsFromRequest($request); $settings = $this->mergeUnmodifiedSettings($resource->getSettings(), $settings); $resource->setSettings($settings); } }
[ "public", "function", "onLayoutBoxPreUpdate", "(", "EntityEvent", "$", "event", ")", "{", "$", "resource", "=", "$", "event", "->", "getEntity", "(", ")", ";", "if", "(", "$", "resource", "instanceof", "LayoutBox", ")", "{", "$", "request", "=", "$", "this", "->", "getRequestHelper", "(", ")", "->", "getCurrentRequest", "(", ")", ";", "$", "settings", "=", "$", "this", "->", "getBoxSettingsFromRequest", "(", "$", "request", ")", ";", "$", "settings", "=", "$", "this", "->", "mergeUnmodifiedSettings", "(", "$", "resource", "->", "getSettings", "(", ")", ",", "$", "settings", ")", ";", "$", "resource", "->", "setSettings", "(", "$", "settings", ")", ";", "}", "}" ]
Sets resource settings fetched from fieldset corresponding to selected box type @param EntityEvent $event
[ "Sets", "resource", "settings", "fetched", "from", "fieldset", "corresponding", "to", "selected", "box", "type" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/EventListener/LayoutBoxSubscriber.php#L68-L77
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.getFunctions
public function getFunctions() { $options = ['is_safe' => ['html']]; return [ new \Twig_SimpleFunction('lug_grid', [$this, 'render'], $options), new \Twig_SimpleFunction('lug_grid_filters', [$this, 'renderFilters'], $options), new \Twig_SimpleFunction('lug_grid_body', [$this, 'renderGrid'], $options), new \Twig_SimpleFunction('lug_grid_column', [$this, 'renderColumn'], $options), new \Twig_SimpleFunction('lug_grid_column_actions', [$this, 'renderColumnActions'], $options), new \Twig_SimpleFunction('lug_grid_column_action', [$this, 'renderColumnAction'], $options), new \Twig_SimpleFunction('lug_grid_column_sortings', [$this, 'renderColumnSortings'], $options), new \Twig_SimpleFunction('lug_grid_column_sorting', [$this, 'renderColumnSorting'], $options), new \Twig_SimpleFunction('lug_grid_global_actions', [$this, 'renderGlobalActions'], $options), new \Twig_SimpleFunction('lug_grid_global_action', [$this, 'renderGlobalAction'], $options), new \Twig_SimpleFunction('lug_grid_pager', [$this, 'renderPager'], $options), ]; }
php
public function getFunctions() { $options = ['is_safe' => ['html']]; return [ new \Twig_SimpleFunction('lug_grid', [$this, 'render'], $options), new \Twig_SimpleFunction('lug_grid_filters', [$this, 'renderFilters'], $options), new \Twig_SimpleFunction('lug_grid_body', [$this, 'renderGrid'], $options), new \Twig_SimpleFunction('lug_grid_column', [$this, 'renderColumn'], $options), new \Twig_SimpleFunction('lug_grid_column_actions', [$this, 'renderColumnActions'], $options), new \Twig_SimpleFunction('lug_grid_column_action', [$this, 'renderColumnAction'], $options), new \Twig_SimpleFunction('lug_grid_column_sortings', [$this, 'renderColumnSortings'], $options), new \Twig_SimpleFunction('lug_grid_column_sorting', [$this, 'renderColumnSorting'], $options), new \Twig_SimpleFunction('lug_grid_global_actions', [$this, 'renderGlobalActions'], $options), new \Twig_SimpleFunction('lug_grid_global_action', [$this, 'renderGlobalAction'], $options), new \Twig_SimpleFunction('lug_grid_pager', [$this, 'renderPager'], $options), ]; }
[ "public", "function", "getFunctions", "(", ")", "{", "$", "options", "=", "[", "'is_safe'", "=>", "[", "'html'", "]", "]", ";", "return", "[", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid'", ",", "[", "$", "this", ",", "'render'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_filters'", ",", "[", "$", "this", ",", "'renderFilters'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_body'", ",", "[", "$", "this", ",", "'renderGrid'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_column'", ",", "[", "$", "this", ",", "'renderColumn'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_column_actions'", ",", "[", "$", "this", ",", "'renderColumnActions'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_column_action'", ",", "[", "$", "this", ",", "'renderColumnAction'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_column_sortings'", ",", "[", "$", "this", ",", "'renderColumnSortings'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_column_sorting'", ",", "[", "$", "this", ",", "'renderColumnSorting'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_global_actions'", ",", "[", "$", "this", ",", "'renderGlobalActions'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_global_action'", ",", "[", "$", "this", ",", "'renderGlobalAction'", "]", ",", "$", "options", ")", ",", "new", "\\", "Twig_SimpleFunction", "(", "'lug_grid_pager'", ",", "[", "$", "this", ",", "'renderPager'", "]", ",", "$", "options", ")", ",", "]", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L49-L66
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderColumn
public function renderColumn(GridViewInterface $grid, ColumnInterface $column, $data) { return $this->renderer->renderColumn($grid, $column, $data); }
php
public function renderColumn(GridViewInterface $grid, ColumnInterface $column, $data) { return $this->renderer->renderColumn($grid, $column, $data); }
[ "public", "function", "renderColumn", "(", "GridViewInterface", "$", "grid", ",", "ColumnInterface", "$", "column", ",", "$", "data", ")", "{", "return", "$", "this", "->", "renderer", "->", "renderColumn", "(", "$", "grid", ",", "$", "column", ",", "$", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L95-L98
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderColumnSortings
public function renderColumnSortings(GridViewInterface $grid, ColumnInterface $column) { return $this->renderer->renderColumnSortings($grid, $column); }
php
public function renderColumnSortings(GridViewInterface $grid, ColumnInterface $column) { return $this->renderer->renderColumnSortings($grid, $column); }
[ "public", "function", "renderColumnSortings", "(", "GridViewInterface", "$", "grid", ",", "ColumnInterface", "$", "column", ")", "{", "return", "$", "this", "->", "renderer", "->", "renderColumnSortings", "(", "$", "grid", ",", "$", "column", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L103-L106
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderColumnSorting
public function renderColumnSorting(GridViewInterface $grid, ColumnInterface $column, $sorting) { return $this->renderer->renderColumnSorting($grid, $column, $sorting); }
php
public function renderColumnSorting(GridViewInterface $grid, ColumnInterface $column, $sorting) { return $this->renderer->renderColumnSorting($grid, $column, $sorting); }
[ "public", "function", "renderColumnSorting", "(", "GridViewInterface", "$", "grid", ",", "ColumnInterface", "$", "column", ",", "$", "sorting", ")", "{", "return", "$", "this", "->", "renderer", "->", "renderColumnSorting", "(", "$", "grid", ",", "$", "column", ",", "$", "sorting", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L111-L114
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderColumnAction
public function renderColumnAction(GridViewInterface $grid, ActionInterface $action, $data) { return $this->renderer->renderColumnAction($grid, $action, $data); }
php
public function renderColumnAction(GridViewInterface $grid, ActionInterface $action, $data) { return $this->renderer->renderColumnAction($grid, $action, $data); }
[ "public", "function", "renderColumnAction", "(", "GridViewInterface", "$", "grid", ",", "ActionInterface", "$", "action", ",", "$", "data", ")", "{", "return", "$", "this", "->", "renderer", "->", "renderColumnAction", "(", "$", "grid", ",", "$", "action", ",", "$", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L127-L130
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderGlobalAction
public function renderGlobalAction(GridViewInterface $grid, ActionInterface $action) { return $this->renderer->renderGlobalAction($grid, $action); }
php
public function renderGlobalAction(GridViewInterface $grid, ActionInterface $action) { return $this->renderer->renderGlobalAction($grid, $action); }
[ "public", "function", "renderGlobalAction", "(", "GridViewInterface", "$", "grid", ",", "ActionInterface", "$", "action", ")", "{", "return", "$", "this", "->", "renderer", "->", "renderGlobalAction", "(", "$", "grid", ",", "$", "action", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L143-L146
php-lug/lug
src/Bundle/GridBundle/Twig/GridExtension.php
GridExtension.renderPager
public function renderPager(Pagerfanta $pager, $name = null, array $options = []) { if (isset($options['routeParams']['grid']['reset'])) { unset($options['routeParams']['grid']); } return $this->pagerfantaExtension->renderPagerfanta($pager, $name, $options); }
php
public function renderPager(Pagerfanta $pager, $name = null, array $options = []) { if (isset($options['routeParams']['grid']['reset'])) { unset($options['routeParams']['grid']); } return $this->pagerfantaExtension->renderPagerfanta($pager, $name, $options); }
[ "public", "function", "renderPager", "(", "Pagerfanta", "$", "pager", ",", "$", "name", "=", "null", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "options", "[", "'routeParams'", "]", "[", "'grid'", "]", "[", "'reset'", "]", ")", ")", "{", "unset", "(", "$", "options", "[", "'routeParams'", "]", "[", "'grid'", "]", ")", ";", "}", "return", "$", "this", "->", "pagerfantaExtension", "->", "renderPagerfanta", "(", "$", "pager", ",", "$", "name", ",", "$", "options", ")", ";", "}" ]
@param Pagerfanta $pager @param string|null $name @param mixed[] $options @return string
[ "@param", "Pagerfanta", "$pager", "@param", "string|null", "$name", "@param", "mixed", "[]", "$options" ]
train
https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/GridBundle/Twig/GridExtension.php#L155-L162
technote-space/wordpress-plugin-base
src/classes/models/lib/minify.php
Minify.check_cache
private function check_cache( $src, $name ) { $name = $name . '_minify_cache'; $hash = sha1( $src ); $cache = $this->app->get_shared_object( $name, 'all' ); if ( $cache ) { if ( isset( $cache[ $hash ] ) ) { return true; } } else { $cache = []; } $cache[ $hash ] = true; $this->app->set_shared_object( $name, $cache, 'all' ); return false; }
php
private function check_cache( $src, $name ) { $name = $name . '_minify_cache'; $hash = sha1( $src ); $cache = $this->app->get_shared_object( $name, 'all' ); if ( $cache ) { if ( isset( $cache[ $hash ] ) ) { return true; } } else { $cache = []; } $cache[ $hash ] = true; $this->app->set_shared_object( $name, $cache, 'all' ); return false; }
[ "private", "function", "check_cache", "(", "$", "src", ",", "$", "name", ")", "{", "$", "name", "=", "$", "name", ".", "'_minify_cache'", ";", "$", "hash", "=", "sha1", "(", "$", "src", ")", ";", "$", "cache", "=", "$", "this", "->", "app", "->", "get_shared_object", "(", "$", "name", ",", "'all'", ")", ";", "if", "(", "$", "cache", ")", "{", "if", "(", "isset", "(", "$", "cache", "[", "$", "hash", "]", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "$", "cache", "=", "[", "]", ";", "}", "$", "cache", "[", "$", "hash", "]", "=", "true", ";", "$", "this", "->", "app", "->", "set_shared_object", "(", "$", "name", ",", "$", "cache", ",", "'all'", ")", ";", "return", "false", ";", "}" ]
@param string $src @param string $name @return bool
[ "@param", "string", "$src", "@param", "string", "$name" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/minify.php#L60-L75
technote-space/wordpress-plugin-base
src/classes/models/lib/minify.php
Minify.output_js
public function output_js( $clear_cache = false ) { if ( $clear_cache ) { $this->clear_cache( 'script' ); } if ( empty( $this->_script ) ) { return; } ksort( $this->_script ); $script = implode( "\n", array_map( function ( $s ) { return implode( "\n", $s ); }, $this->_script ) ); if ( $this->apply_filters( 'minify_js' ) ) { $minify = new \MatthiasMullie\Minify\JS(); $minify->add( $script ); echo '<script>' . $minify->minify() . '</script>'; } else { echo '<script>' . $script . '</script>'; } $this->_script = []; $this->_has_output_script = true; }
php
public function output_js( $clear_cache = false ) { if ( $clear_cache ) { $this->clear_cache( 'script' ); } if ( empty( $this->_script ) ) { return; } ksort( $this->_script ); $script = implode( "\n", array_map( function ( $s ) { return implode( "\n", $s ); }, $this->_script ) ); if ( $this->apply_filters( 'minify_js' ) ) { $minify = new \MatthiasMullie\Minify\JS(); $minify->add( $script ); echo '<script>' . $minify->minify() . '</script>'; } else { echo '<script>' . $script . '</script>'; } $this->_script = []; $this->_has_output_script = true; }
[ "public", "function", "output_js", "(", "$", "clear_cache", "=", "false", ")", "{", "if", "(", "$", "clear_cache", ")", "{", "$", "this", "->", "clear_cache", "(", "'script'", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "_script", ")", ")", "{", "return", ";", "}", "ksort", "(", "$", "this", "->", "_script", ")", ";", "$", "script", "=", "implode", "(", "\"\\n\"", ",", "array_map", "(", "function", "(", "$", "s", ")", "{", "return", "implode", "(", "\"\\n\"", ",", "$", "s", ")", ";", "}", ",", "$", "this", "->", "_script", ")", ")", ";", "if", "(", "$", "this", "->", "apply_filters", "(", "'minify_js'", ")", ")", "{", "$", "minify", "=", "new", "\\", "MatthiasMullie", "\\", "Minify", "\\", "JS", "(", ")", ";", "$", "minify", "->", "add", "(", "$", "script", ")", ";", "echo", "'<script>'", ".", "$", "minify", "->", "minify", "(", ")", ".", "'</script>'", ";", "}", "else", "{", "echo", "'<script>'", ".", "$", "script", ".", "'</script>'", ";", "}", "$", "this", "->", "_script", "=", "[", "]", ";", "$", "this", "->", "_has_output_script", "=", "true", ";", "}" ]
@since 2.9.0 Added: clear cache @param bool $clear_cache
[ "@since", "2", ".", "9", ".", "0", "Added", ":", "clear", "cache" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/minify.php#L128-L149
technote-space/wordpress-plugin-base
src/classes/models/lib/minify.php
Minify.output_css
public function output_css( $clear_cache = false ) { if ( $clear_cache ) { $this->clear_cache( 'style' ); } if ( empty( $this->_css ) ) { return; } ksort( $this->_css ); $css = implode( "\n", array_map( function ( $s ) { return implode( "\n", $s ); }, $this->_css ) ); if ( $this->apply_filters( 'minify_css' ) ) { $minify = new \MatthiasMullie\Minify\CSS(); $minify->add( $css ); echo '<style>' . $minify->minify() . '</style>'; } else { echo '<style>' . $css . '</style>'; } $this->_css = []; }
php
public function output_css( $clear_cache = false ) { if ( $clear_cache ) { $this->clear_cache( 'style' ); } if ( empty( $this->_css ) ) { return; } ksort( $this->_css ); $css = implode( "\n", array_map( function ( $s ) { return implode( "\n", $s ); }, $this->_css ) ); if ( $this->apply_filters( 'minify_css' ) ) { $minify = new \MatthiasMullie\Minify\CSS(); $minify->add( $css ); echo '<style>' . $minify->minify() . '</style>'; } else { echo '<style>' . $css . '</style>'; } $this->_css = []; }
[ "public", "function", "output_css", "(", "$", "clear_cache", "=", "false", ")", "{", "if", "(", "$", "clear_cache", ")", "{", "$", "this", "->", "clear_cache", "(", "'style'", ")", ";", "}", "if", "(", "empty", "(", "$", "this", "->", "_css", ")", ")", "{", "return", ";", "}", "ksort", "(", "$", "this", "->", "_css", ")", ";", "$", "css", "=", "implode", "(", "\"\\n\"", ",", "array_map", "(", "function", "(", "$", "s", ")", "{", "return", "implode", "(", "\"\\n\"", ",", "$", "s", ")", ";", "}", ",", "$", "this", "->", "_css", ")", ")", ";", "if", "(", "$", "this", "->", "apply_filters", "(", "'minify_css'", ")", ")", "{", "$", "minify", "=", "new", "\\", "MatthiasMullie", "\\", "Minify", "\\", "CSS", "(", ")", ";", "$", "minify", "->", "add", "(", "$", "css", ")", ";", "echo", "'<style>'", ".", "$", "minify", "->", "minify", "(", ")", ".", "'</style>'", ";", "}", "else", "{", "echo", "'<style>'", ".", "$", "css", ".", "'</style>'", ";", "}", "$", "this", "->", "_css", "=", "[", "]", ";", "}" ]
@since 2.9.0 Added: clear cache @param bool $clear_cache
[ "@since", "2", ".", "9", ".", "0", "Added", ":", "clear", "cache" ]
train
https://github.com/technote-space/wordpress-plugin-base/blob/02cfcba358432a2539af07a69d9db00ff7c14eac/src/classes/models/lib/minify.php#L192-L212
brick/di
src/UnresolvedValueException.php
UnresolvedValueException.unresolvedParameter
public static function unresolvedParameter(\ReflectionParameter $parameter) : UnresolvedValueException { $message = 'The parameter "%s" from function "%s" could not be resolved'; $message = sprintf($message, self::getParameterName($parameter), self::getFunctionName($parameter)); return new self($message); }
php
public static function unresolvedParameter(\ReflectionParameter $parameter) : UnresolvedValueException { $message = 'The parameter "%s" from function "%s" could not be resolved'; $message = sprintf($message, self::getParameterName($parameter), self::getFunctionName($parameter)); return new self($message); }
[ "public", "static", "function", "unresolvedParameter", "(", "\\", "ReflectionParameter", "$", "parameter", ")", ":", "UnresolvedValueException", "{", "$", "message", "=", "'The parameter \"%s\" from function \"%s\" could not be resolved'", ";", "$", "message", "=", "sprintf", "(", "$", "message", ",", "self", "::", "getParameterName", "(", "$", "parameter", ")", ",", "self", "::", "getFunctionName", "(", "$", "parameter", ")", ")", ";", "return", "new", "self", "(", "$", "message", ")", ";", "}" ]
@param \ReflectionParameter $parameter @return UnresolvedValueException
[ "@param", "\\", "ReflectionParameter", "$parameter" ]
train
https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/UnresolvedValueException.php#L17-L23
brick/di
src/UnresolvedValueException.php
UnresolvedValueException.unresolvedProperty
public static function unresolvedProperty(\ReflectionProperty $property) : UnresolvedValueException { $message = 'The property %s::$%s could not be resolved'; $message = sprintf($message, $property->getDeclaringClass()->getName(), $property->getName()); return new self($message); }
php
public static function unresolvedProperty(\ReflectionProperty $property) : UnresolvedValueException { $message = 'The property %s::$%s could not be resolved'; $message = sprintf($message, $property->getDeclaringClass()->getName(), $property->getName()); return new self($message); }
[ "public", "static", "function", "unresolvedProperty", "(", "\\", "ReflectionProperty", "$", "property", ")", ":", "UnresolvedValueException", "{", "$", "message", "=", "'The property %s::$%s could not be resolved'", ";", "$", "message", "=", "sprintf", "(", "$", "message", ",", "$", "property", "->", "getDeclaringClass", "(", ")", "->", "getName", "(", ")", ",", "$", "property", "->", "getName", "(", ")", ")", ";", "return", "new", "self", "(", "$", "message", ")", ";", "}" ]
@param \ReflectionProperty $property @return UnresolvedValueException
[ "@param", "\\", "ReflectionProperty", "$property" ]
train
https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/UnresolvedValueException.php#L30-L36
brick/di
src/UnresolvedValueException.php
UnresolvedValueException.getParameterName
private static function getParameterName(\ReflectionParameter $parameter) : string { $parameterType = ''; if (null !== $type = $parameter->getType()) { $parameterType = (string) $type . ' '; } return $parameterType . '$' . $parameter->getName(); }
php
private static function getParameterName(\ReflectionParameter $parameter) : string { $parameterType = ''; if (null !== $type = $parameter->getType()) { $parameterType = (string) $type . ' '; } return $parameterType . '$' . $parameter->getName(); }
[ "private", "static", "function", "getParameterName", "(", "\\", "ReflectionParameter", "$", "parameter", ")", ":", "string", "{", "$", "parameterType", "=", "''", ";", "if", "(", "null", "!==", "$", "type", "=", "$", "parameter", "->", "getType", "(", ")", ")", "{", "$", "parameterType", "=", "(", "string", ")", "$", "type", ".", "' '", ";", "}", "return", "$", "parameterType", ".", "'$'", ".", "$", "parameter", "->", "getName", "(", ")", ";", "}" ]
Returns the type (if any) + name of a function parameter. @param \ReflectionParameter $parameter @return string
[ "Returns", "the", "type", "(", "if", "any", ")", "+", "name", "of", "a", "function", "parameter", "." ]
train
https://github.com/brick/di/blob/6ced82ab3623b8f1470317d38cbd2de855e7aa3d/src/UnresolvedValueException.php#L45-L54
ekuiter/feature-php
FeaturePhp/Exporter/LocalExporter.php
LocalExporter.export
public function export($product) { $files = $product->generateFiles(); mkdir($this->target, 0777, true); foreach ($files as $file) if (!$file->getContent()->copy(fphp\Helper\Path::join($this->target, $file->getTarget()))) throw new LocalExporterException("could not copy file \"{$file->getTarget()}\""); }
php
public function export($product) { $files = $product->generateFiles(); mkdir($this->target, 0777, true); foreach ($files as $file) if (!$file->getContent()->copy(fphp\Helper\Path::join($this->target, $file->getTarget()))) throw new LocalExporterException("could not copy file \"{$file->getTarget()}\""); }
[ "public", "function", "export", "(", "$", "product", ")", "{", "$", "files", "=", "$", "product", "->", "generateFiles", "(", ")", ";", "mkdir", "(", "$", "this", "->", "target", ",", "0777", ",", "true", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "if", "(", "!", "$", "file", "->", "getContent", "(", ")", "->", "copy", "(", "fphp", "\\", "Helper", "\\", "Path", "::", "join", "(", "$", "this", "->", "target", ",", "$", "file", "->", "getTarget", "(", ")", ")", ")", ")", "throw", "new", "LocalExporterException", "(", "\"could not copy file \\\"{$file->getTarget()}\\\"\"", ")", ";", "}" ]
Exports a product in the local filesystem. Every generated file is copied to the filesystem at its target path. @param \FeaturePhp\ProductLine\Product $product
[ "Exports", "a", "product", "in", "the", "local", "filesystem", ".", "Every", "generated", "file", "is", "copied", "to", "the", "filesystem", "at", "its", "target", "path", "." ]
train
https://github.com/ekuiter/feature-php/blob/daf4a59098802fedcfd1f1a1d07847fcf2fea7bf/FeaturePhp/Exporter/LocalExporter.php#L44-L51
oroinc/OroLayoutComponent
Loader/Visitor/ElementDependentVisitor.php
ElementDependentVisitor.endVisit
public function endVisit(VisitContext $visitContext) { $writer = $visitContext->createWriter(); $writer->writeln(sprintf('return \'%s\';', $this->elementId)); $method = PhpMethod::create('getElement'); $method->setBody($writer->getContent()); $visitContext->getClass()->setMethod($method); }
php
public function endVisit(VisitContext $visitContext) { $writer = $visitContext->createWriter(); $writer->writeln(sprintf('return \'%s\';', $this->elementId)); $method = PhpMethod::create('getElement'); $method->setBody($writer->getContent()); $visitContext->getClass()->setMethod($method); }
[ "public", "function", "endVisit", "(", "VisitContext", "$", "visitContext", ")", "{", "$", "writer", "=", "$", "visitContext", "->", "createWriter", "(", ")", ";", "$", "writer", "->", "writeln", "(", "sprintf", "(", "'return \\'%s\\';'", ",", "$", "this", "->", "elementId", ")", ")", ";", "$", "method", "=", "PhpMethod", "::", "create", "(", "'getElement'", ")", ";", "$", "method", "->", "setBody", "(", "$", "writer", "->", "getContent", "(", ")", ")", ";", "$", "visitContext", "->", "getClass", "(", ")", "->", "setMethod", "(", "$", "method", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/oroinc/OroLayoutComponent/blob/682a96672393d81c63728e47c4a4c3618c515be0/Loader/Visitor/ElementDependentVisitor.php#L34-L43
DevGroup-ru/yii2-users-module
src/scenarios/BaseAuthorizationPair.php
BaseAuthorizationPair.findUserByField
protected function findUserByField(LoginForm &$loginForm, $field = 'username') { return [ $field, function ($attribute) use (&$loginForm) { $user = Yii::createObject(ModelMapHelper::User()); /** @var LazyCache $cache */ $cache = Yii::$app->cache; $value = $loginForm->$attribute; $loginForm->user = $cache->lazy(function () use ($user, $value, $attribute) { return $user::find() ->where( "$attribute=:param", [ ':param' => $value, ] )->one(); }, "User:by:$attribute:$value", 86400, new TagDependency(['tags'=>$user::commonTag()])); } ]; }
php
protected function findUserByField(LoginForm &$loginForm, $field = 'username') { return [ $field, function ($attribute) use (&$loginForm) { $user = Yii::createObject(ModelMapHelper::User()); /** @var LazyCache $cache */ $cache = Yii::$app->cache; $value = $loginForm->$attribute; $loginForm->user = $cache->lazy(function () use ($user, $value, $attribute) { return $user::find() ->where( "$attribute=:param", [ ':param' => $value, ] )->one(); }, "User:by:$attribute:$value", 86400, new TagDependency(['tags'=>$user::commonTag()])); } ]; }
[ "protected", "function", "findUserByField", "(", "LoginForm", "&", "$", "loginForm", ",", "$", "field", "=", "'username'", ")", "{", "return", "[", "$", "field", ",", "function", "(", "$", "attribute", ")", "use", "(", "&", "$", "loginForm", ")", "{", "$", "user", "=", "Yii", "::", "createObject", "(", "ModelMapHelper", "::", "User", "(", ")", ")", ";", "/** @var LazyCache $cache */", "$", "cache", "=", "Yii", "::", "$", "app", "->", "cache", ";", "$", "value", "=", "$", "loginForm", "->", "$", "attribute", ";", "$", "loginForm", "->", "user", "=", "$", "cache", "->", "lazy", "(", "function", "(", ")", "use", "(", "$", "user", ",", "$", "value", ",", "$", "attribute", ")", "{", "return", "$", "user", "::", "find", "(", ")", "->", "where", "(", "\"$attribute=:param\"", ",", "[", "':param'", "=>", "$", "value", ",", "]", ")", "->", "one", "(", ")", ";", "}", ",", "\"User:by:$attribute:$value\"", ",", "86400", ",", "new", "TagDependency", "(", "[", "'tags'", "=>", "$", "user", "::", "commonTag", "(", ")", "]", ")", ")", ";", "}", "]", ";", "}" ]
Finds user by specified field(username, email, phone) @param \DevGroup\Users\models\LoginForm $loginForm @param string $field @return array
[ "Finds", "user", "by", "specified", "field", "(", "username", "email", "phone", ")", "@param", "\\", "DevGroup", "\\", "Users", "\\", "models", "\\", "LoginForm", "$loginForm", "@param", "string", "$field" ]
train
https://github.com/DevGroup-ru/yii2-users-module/blob/ff0103dc55c3462627ccc704c33e70c96053f750/src/scenarios/BaseAuthorizationPair.php#L76-L96
DevGroup-ru/yii2-users-module
src/scenarios/BaseAuthorizationPair.php
BaseAuthorizationPair.validatePassword
protected function validatePassword(LoginForm &$loginForm) { return [ 'password', function ($attribute) use (&$loginForm) { if ($loginForm->user === null || !PasswordHelper::validate($loginForm->password, $loginForm->user->password_hash) ) { $loginForm->addError($attribute, Yii::t('users', 'Invalid login or password')); } } ]; }
php
protected function validatePassword(LoginForm &$loginForm) { return [ 'password', function ($attribute) use (&$loginForm) { if ($loginForm->user === null || !PasswordHelper::validate($loginForm->password, $loginForm->user->password_hash) ) { $loginForm->addError($attribute, Yii::t('users', 'Invalid login or password')); } } ]; }
[ "protected", "function", "validatePassword", "(", "LoginForm", "&", "$", "loginForm", ")", "{", "return", "[", "'password'", ",", "function", "(", "$", "attribute", ")", "use", "(", "&", "$", "loginForm", ")", "{", "if", "(", "$", "loginForm", "->", "user", "===", "null", "||", "!", "PasswordHelper", "::", "validate", "(", "$", "loginForm", "->", "password", ",", "$", "loginForm", "->", "user", "->", "password_hash", ")", ")", "{", "$", "loginForm", "->", "addError", "(", "$", "attribute", ",", "Yii", "::", "t", "(", "'users'", ",", "'Invalid login or password'", ")", ")", ";", "}", "}", "]", ";", "}" ]
Adds password validation rule for login scenario @param \DevGroup\Users\models\LoginForm $loginForm @return array
[ "Adds", "password", "validation", "rule", "for", "login", "scenario" ]
train
https://github.com/DevGroup-ru/yii2-users-module/blob/ff0103dc55c3462627ccc704c33e70c96053f750/src/scenarios/BaseAuthorizationPair.php#L105-L117
DevGroup-ru/yii2-users-module
src/scenarios/BaseAuthorizationPair.php
BaseAuthorizationPair.inactiveUsers
protected function inactiveUsers(LoginForm &$loginForm) { if (UsersModule::module()->allowLoginInactiveAccounts === false) { return []; } return [ 'username', function ($attribute) use (&$loginForm) { if ($loginForm->user !== null && $loginForm->user->is_active === false) { $loginForm->addError($attribute, Yii::t('users', 'You need to confirm your email address')); } } ]; }
php
protected function inactiveUsers(LoginForm &$loginForm) { if (UsersModule::module()->allowLoginInactiveAccounts === false) { return []; } return [ 'username', function ($attribute) use (&$loginForm) { if ($loginForm->user !== null && $loginForm->user->is_active === false) { $loginForm->addError($attribute, Yii::t('users', 'You need to confirm your email address')); } } ]; }
[ "protected", "function", "inactiveUsers", "(", "LoginForm", "&", "$", "loginForm", ")", "{", "if", "(", "UsersModule", "::", "module", "(", ")", "->", "allowLoginInactiveAccounts", "===", "false", ")", "{", "return", "[", "]", ";", "}", "return", "[", "'username'", ",", "function", "(", "$", "attribute", ")", "use", "(", "&", "$", "loginForm", ")", "{", "if", "(", "$", "loginForm", "->", "user", "!==", "null", "&&", "$", "loginForm", "->", "user", "->", "is_active", "===", "false", ")", "{", "$", "loginForm", "->", "addError", "(", "$", "attribute", ",", "Yii", "::", "t", "(", "'users'", ",", "'You need to confirm your email address'", ")", ")", ";", "}", "}", "]", ";", "}" ]
Adds validation rule to not accept inactive users if such feature is toggled on in module configuration. @param \DevGroup\Users\models\LoginForm $loginForm @return array
[ "Adds", "validation", "rule", "to", "not", "accept", "inactive", "users", "if", "such", "feature", "is", "toggled", "on", "in", "module", "configuration", "." ]
train
https://github.com/DevGroup-ru/yii2-users-module/blob/ff0103dc55c3462627ccc704c33e70c96053f750/src/scenarios/BaseAuthorizationPair.php#L126-L139
mikebarlow/html-helper
src/Html.php
Html.tag
public function tag($tag, $attr = null, $content = null, $close = false) { $tag = strtolower($tag); if (! empty($attr) && is_array($attr)) { $attr = $this->Attr->attr($attr); } if ($close) { return sprintf('<%s%s>%s</%1$s>', $tag, $attr, $content); } else { return sprintf('<%s%s>', $tag, $attr); } }
php
public function tag($tag, $attr = null, $content = null, $close = false) { $tag = strtolower($tag); if (! empty($attr) && is_array($attr)) { $attr = $this->Attr->attr($attr); } if ($close) { return sprintf('<%s%s>%s</%1$s>', $tag, $attr, $content); } else { return sprintf('<%s%s>', $tag, $attr); } }
[ "public", "function", "tag", "(", "$", "tag", ",", "$", "attr", "=", "null", ",", "$", "content", "=", "null", ",", "$", "close", "=", "false", ")", "{", "$", "tag", "=", "strtolower", "(", "$", "tag", ")", ";", "if", "(", "!", "empty", "(", "$", "attr", ")", "&&", "is_array", "(", "$", "attr", ")", ")", "{", "$", "attr", "=", "$", "this", "->", "Attr", "->", "attr", "(", "$", "attr", ")", ";", "}", "if", "(", "$", "close", ")", "{", "return", "sprintf", "(", "'<%s%s>%s</%1$s>'", ",", "$", "tag", ",", "$", "attr", ",", "$", "content", ")", ";", "}", "else", "{", "return", "sprintf", "(", "'<%s%s>'", ",", "$", "tag", ",", "$", "attr", ")", ";", "}", "}" ]
render a tag @param string tag to render @param array attributes for the tag @param string contents of tag when not self closing @param bool close the tag? @return string
[ "render", "a", "tag" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L50-L63
mikebarlow/html-helper
src/Html.php
Html.ul
public function ul($list, $attr = null) { $out = $this->tag('ul', $attr); if (! empty($list) && is_array($list)) { $out .= $this->processList($list); } $out .= $this->tag('/ul'); return $out; }
php
public function ul($list, $attr = null) { $out = $this->tag('ul', $attr); if (! empty($list) && is_array($list)) { $out .= $this->processList($list); } $out .= $this->tag('/ul'); return $out; }
[ "public", "function", "ul", "(", "$", "list", ",", "$", "attr", "=", "null", ")", "{", "$", "out", "=", "$", "this", "->", "tag", "(", "'ul'", ",", "$", "attr", ")", ";", "if", "(", "!", "empty", "(", "$", "list", ")", "&&", "is_array", "(", "$", "list", ")", ")", "{", "$", "out", ".=", "$", "this", "->", "processList", "(", "$", "list", ")", ";", "}", "$", "out", ".=", "$", "this", "->", "tag", "(", "'/ul'", ")", ";", "return", "$", "out", ";", "}" ]
unordered list @param array Array of items to list / attr @param array Array of attributes for the ul @return string
[ "unordered", "list" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L96-L107
mikebarlow/html-helper
src/Html.php
Html.processList
public function processList($list, $subListType = 'ul') { $out = ''; foreach ($list as $key => $value) { if (is_array($value) && (isset($value['list']) || isset($value['attr']))) { $attr = (isset($value['attr'])) ? $value['attr'] : null; $listAttr = (isset($value['listAttr'])) ? $value['listAttr'] : null; $subList = (isset($value['list'])) ? $this->{$subListType}($value['list'], $listAttr) : ''; $out .= $this->tag('li', $attr, $key . $subList, true); } elseif (is_array($value)) { $out .= $this->tag('li', null, $key . $this->{$subListType}($value), true); } else { $out .= $this->tag('li', null, $value, true); } } return $out; }
php
public function processList($list, $subListType = 'ul') { $out = ''; foreach ($list as $key => $value) { if (is_array($value) && (isset($value['list']) || isset($value['attr']))) { $attr = (isset($value['attr'])) ? $value['attr'] : null; $listAttr = (isset($value['listAttr'])) ? $value['listAttr'] : null; $subList = (isset($value['list'])) ? $this->{$subListType}($value['list'], $listAttr) : ''; $out .= $this->tag('li', $attr, $key . $subList, true); } elseif (is_array($value)) { $out .= $this->tag('li', null, $key . $this->{$subListType}($value), true); } else { $out .= $this->tag('li', null, $value, true); } } return $out; }
[ "public", "function", "processList", "(", "$", "list", ",", "$", "subListType", "=", "'ul'", ")", "{", "$", "out", "=", "''", ";", "foreach", "(", "$", "list", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "(", "isset", "(", "$", "value", "[", "'list'", "]", ")", "||", "isset", "(", "$", "value", "[", "'attr'", "]", ")", ")", ")", "{", "$", "attr", "=", "(", "isset", "(", "$", "value", "[", "'attr'", "]", ")", ")", "?", "$", "value", "[", "'attr'", "]", ":", "null", ";", "$", "listAttr", "=", "(", "isset", "(", "$", "value", "[", "'listAttr'", "]", ")", ")", "?", "$", "value", "[", "'listAttr'", "]", ":", "null", ";", "$", "subList", "=", "(", "isset", "(", "$", "value", "[", "'list'", "]", ")", ")", "?", "$", "this", "->", "{", "$", "subListType", "}", "(", "$", "value", "[", "'list'", "]", ",", "$", "listAttr", ")", ":", "''", ";", "$", "out", ".=", "$", "this", "->", "tag", "(", "'li'", ",", "$", "attr", ",", "$", "key", ".", "$", "subList", ",", "true", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "out", ".=", "$", "this", "->", "tag", "(", "'li'", ",", "null", ",", "$", "key", ".", "$", "this", "->", "{", "$", "subListType", "}", "(", "$", "value", ")", ",", "true", ")", ";", "}", "else", "{", "$", "out", ".=", "$", "this", "->", "tag", "(", "'li'", ",", "null", ",", "$", "value", ",", "true", ")", ";", "}", "}", "return", "$", "out", ";", "}" ]
process list items @todo add ability to define sublists from within the list @param array Array of list items to process @param string method to use for sub-lists @return string
[ "process", "list", "items" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L137-L156
mikebarlow/html-helper
src/Html.php
Html.link
public function link($text, $url = null, $attr = null) { $url = $this->Router->getUrl($url); $attr['href'] = $url; return $this->tag('a', $attr, $text, true); }
php
public function link($text, $url = null, $attr = null) { $url = $this->Router->getUrl($url); $attr['href'] = $url; return $this->tag('a', $attr, $text, true); }
[ "public", "function", "link", "(", "$", "text", ",", "$", "url", "=", "null", ",", "$", "attr", "=", "null", ")", "{", "$", "url", "=", "$", "this", "->", "Router", "->", "getUrl", "(", "$", "url", ")", ";", "$", "attr", "[", "'href'", "]", "=", "$", "url", ";", "return", "$", "this", "->", "tag", "(", "'a'", ",", "$", "attr", ",", "$", "text", ",", "true", ")", ";", "}" ]
create a link @param string Link text @param mixed url data. Will be passed to the router interface for processing @param array attributes to place on the link tag @return string
[ "create", "a", "link" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L166-L171
mikebarlow/html-helper
src/Html.php
Html.image
public function image($src, $attr = array()) { $src = $this->Assets->getImage($src); $attr['src'] = $src; return $this->tag('img', $attr); }
php
public function image($src, $attr = array()) { $src = $this->Assets->getImage($src); $attr['src'] = $src; return $this->tag('img', $attr); }
[ "public", "function", "image", "(", "$", "src", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "$", "src", "=", "$", "this", "->", "Assets", "->", "getImage", "(", "$", "src", ")", ";", "$", "attr", "[", "'src'", "]", "=", "$", "src", ";", "return", "$", "this", "->", "tag", "(", "'img'", ",", "$", "attr", ")", ";", "}" ]
create an image @param mixed image path data - will be passed to the assets interface for processing @param array attributes to be placed on the img tag @return string
[ "create", "an", "image" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L180-L185
mikebarlow/html-helper
src/Html.php
Html.style
public function style($src, $attr = array()) { $src = $this->Assets->getStyle($src); $attr['href'] = $src; $attr = array_merge( array( 'media' => 'screen', 'rel' => 'stylesheet', 'type' => 'text/css' ), $attr ); return $this->tag('link', $attr); }
php
public function style($src, $attr = array()) { $src = $this->Assets->getStyle($src); $attr['href'] = $src; $attr = array_merge( array( 'media' => 'screen', 'rel' => 'stylesheet', 'type' => 'text/css' ), $attr ); return $this->tag('link', $attr); }
[ "public", "function", "style", "(", "$", "src", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "$", "src", "=", "$", "this", "->", "Assets", "->", "getStyle", "(", "$", "src", ")", ";", "$", "attr", "[", "'href'", "]", "=", "$", "src", ";", "$", "attr", "=", "array_merge", "(", "array", "(", "'media'", "=>", "'screen'", ",", "'rel'", "=>", "'stylesheet'", ",", "'type'", "=>", "'text/css'", ")", ",", "$", "attr", ")", ";", "return", "$", "this", "->", "tag", "(", "'link'", ",", "$", "attr", ")", ";", "}" ]
create a style link @param mixed style path data - will be passed to the assets interface for processing @param array attributes to be placed on the link tag @return string
[ "create", "a", "style", "link" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L194-L209
mikebarlow/html-helper
src/Html.php
Html.script
public function script($src, $attr = array()) { $src = $this->Assets->getScript($src); $attr['src'] = $src; return $this->tag('script', $attr, '', true); }
php
public function script($src, $attr = array()) { $src = $this->Assets->getScript($src); $attr['src'] = $src; return $this->tag('script', $attr, '', true); }
[ "public", "function", "script", "(", "$", "src", ",", "$", "attr", "=", "array", "(", ")", ")", "{", "$", "src", "=", "$", "this", "->", "Assets", "->", "getScript", "(", "$", "src", ")", ";", "$", "attr", "[", "'src'", "]", "=", "$", "src", ";", "return", "$", "this", "->", "tag", "(", "'script'", ",", "$", "attr", ",", "''", ",", "true", ")", ";", "}" ]
create a script tag @param mixed script path data - will be passed to the assets interface for processing @param array attributes to be placed on the script tag @return string
[ "create", "a", "script", "tag" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L218-L223
mikebarlow/html-helper
src/Html.php
Html.setRouter
public function setRouter($Router) { if (! is_object($Router) || ! $Router instanceof Router) { throw new \InvalidArgumentException( 'The Router Interface must be a valid Router Object' ); } $this->Router = $Router; return true; }
php
public function setRouter($Router) { if (! is_object($Router) || ! $Router instanceof Router) { throw new \InvalidArgumentException( 'The Router Interface must be a valid Router Object' ); } $this->Router = $Router; return true; }
[ "public", "function", "setRouter", "(", "$", "Router", ")", "{", "if", "(", "!", "is_object", "(", "$", "Router", ")", "||", "!", "$", "Router", "instanceof", "Router", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The Router Interface must be a valid Router Object'", ")", ";", "}", "$", "this", "->", "Router", "=", "$", "Router", ";", "return", "true", ";", "}" ]
check and set the router interface @param Object Instance of an Router @return bool @throws \InvalidArgumentException
[ "check", "and", "set", "the", "router", "interface" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L232-L242
mikebarlow/html-helper
src/Html.php
Html.setAssets
public function setAssets($Assets) { if (! is_object($Assets) || ! $Assets instanceof Assets) { throw new \InvalidArgumentException( 'The Assets Interface must be a valid Assets Object' ); } $this->Assets = $Assets; return true; }
php
public function setAssets($Assets) { if (! is_object($Assets) || ! $Assets instanceof Assets) { throw new \InvalidArgumentException( 'The Assets Interface must be a valid Assets Object' ); } $this->Assets = $Assets; return true; }
[ "public", "function", "setAssets", "(", "$", "Assets", ")", "{", "if", "(", "!", "is_object", "(", "$", "Assets", ")", "||", "!", "$", "Assets", "instanceof", "Assets", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The Assets Interface must be a valid Assets Object'", ")", ";", "}", "$", "this", "->", "Assets", "=", "$", "Assets", ";", "return", "true", ";", "}" ]
check and set the Asset interface @param Object Instance of an Assets @return bool @throws \InvalidArgumentException
[ "check", "and", "set", "the", "Asset", "interface" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L251-L261
mikebarlow/html-helper
src/Html.php
Html.setForm
public function setForm($Form) { if (! is_object($Form) || ! $Form instanceof Helpers\Form) { throw new \InvalidArgumentException( 'The Form Object must be a valid Helpers\Form Object' ); } $this->Form = $Form; return true; }
php
public function setForm($Form) { if (! is_object($Form) || ! $Form instanceof Helpers\Form) { throw new \InvalidArgumentException( 'The Form Object must be a valid Helpers\Form Object' ); } $this->Form = $Form; return true; }
[ "public", "function", "setForm", "(", "$", "Form", ")", "{", "if", "(", "!", "is_object", "(", "$", "Form", ")", "||", "!", "$", "Form", "instanceof", "Helpers", "\\", "Form", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The Form Object must be a valid Helpers\\Form Object'", ")", ";", "}", "$", "this", "->", "Form", "=", "$", "Form", ";", "return", "true", ";", "}" ]
check and set the Form Object @param Object Instance of an Helpers\Form @return bool @throws \InvalidArgumentException
[ "check", "and", "set", "the", "Form", "Object" ]
train
https://github.com/mikebarlow/html-helper/blob/d9d9dc3e92ba3ecd75f3a2e5a5bc2d23f38b5f65/src/Html.php#L270-L280
gpupo/common-schema
src/ORM/Entity/Trading/Trading.php
Trading.removePayment
public function removePayment(\Gpupo\CommonSchema\ORM\Entity\Trading\Payment\Payment $payment) { return $this->payments->removeElement($payment); }
php
public function removePayment(\Gpupo\CommonSchema\ORM\Entity\Trading\Payment\Payment $payment) { return $this->payments->removeElement($payment); }
[ "public", "function", "removePayment", "(", "\\", "Gpupo", "\\", "CommonSchema", "\\", "ORM", "\\", "Entity", "\\", "Trading", "\\", "Payment", "\\", "Payment", "$", "payment", ")", "{", "return", "$", "this", "->", "payments", "->", "removeElement", "(", "$", "payment", ")", ";", "}" ]
Remove payment. @param \Gpupo\CommonSchema\ORM\Entity\Trading\Payment\Payment $payment @return bool TRUE if this collection contained the specified element, FALSE otherwise
[ "Remove", "payment", "." ]
train
https://github.com/gpupo/common-schema/blob/a762d2eb3063b7317c72c69cbb463b1f95b86b0a/src/ORM/Entity/Trading/Trading.php#L138-L141
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.endclip
public function endclip() { $name = $this->clipName; if (isset($this->clips[$name])) { $this->clips[$name] .= ob_get_clean(); } else { $this->clips[$name] = ob_get_clean(); } }
php
public function endclip() { $name = $this->clipName; if (isset($this->clips[$name])) { $this->clips[$name] .= ob_get_clean(); } else { $this->clips[$name] = ob_get_clean(); } }
[ "public", "function", "endclip", "(", ")", "{", "$", "name", "=", "$", "this", "->", "clipName", ";", "if", "(", "isset", "(", "$", "this", "->", "clips", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "clips", "[", "$", "name", "]", ".=", "ob_get_clean", "(", ")", ";", "}", "else", "{", "$", "this", "->", "clips", "[", "$", "name", "]", "=", "ob_get_clean", "(", ")", ";", "}", "}" ]
Ends clip
[ "Ends", "clip" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L40-L48
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.baseUrl
public function baseUrl() { if (!$this->baseUrl) { $this->baseUrl = $this->request->getScheme() . '://' . $this->request->getHttpHost(); } return $this->baseUrl; }
php
public function baseUrl() { if (!$this->baseUrl) { $this->baseUrl = $this->request->getScheme() . '://' . $this->request->getHttpHost(); } return $this->baseUrl; }
[ "public", "function", "baseUrl", "(", ")", "{", "if", "(", "!", "$", "this", "->", "baseUrl", ")", "{", "$", "this", "->", "baseUrl", "=", "$", "this", "->", "request", "->", "getScheme", "(", ")", ".", "'://'", ".", "$", "this", "->", "request", "->", "getHttpHost", "(", ")", ";", "}", "return", "$", "this", "->", "baseUrl", ";", "}" ]
Gets the base url @return string
[ "Gets", "the", "base", "url" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L66-L73
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.absoluteUrl
public function absoluteUrl($uri = null, $args = null) { if (isset($uri)) { $uri = '/'. ltrim($uri, "/"); return $this->baseUrl() . $this->url->get($uri, $args); } else { return $this->baseUrl() . $this->url->getBaseUri(); } }
php
public function absoluteUrl($uri = null, $args = null) { if (isset($uri)) { $uri = '/'. ltrim($uri, "/"); return $this->baseUrl() . $this->url->get($uri, $args); } else { return $this->baseUrl() . $this->url->getBaseUri(); } }
[ "public", "function", "absoluteUrl", "(", "$", "uri", "=", "null", ",", "$", "args", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "uri", ")", ")", "{", "$", "uri", "=", "'/'", ".", "ltrim", "(", "$", "uri", ",", "\"/\"", ")", ";", "return", "$", "this", "->", "baseUrl", "(", ")", ".", "$", "this", "->", "url", "->", "get", "(", "$", "uri", ",", "$", "args", ")", ";", "}", "else", "{", "return", "$", "this", "->", "baseUrl", "(", ")", ".", "$", "this", "->", "url", "->", "getBaseUri", "(", ")", ";", "}", "}" ]
Gets absolute url @return string
[ "Gets", "absolute", "url" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L80-L88
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.trim
public function trim($str, $charlist = null) { return isset($charlist) ? trim($str, $charlist) : trim($str); }
php
public function trim($str, $charlist = null) { return isset($charlist) ? trim($str, $charlist) : trim($str); }
[ "public", "function", "trim", "(", "$", "str", ",", "$", "charlist", "=", "null", ")", "{", "return", "isset", "(", "$", "charlist", ")", "?", "trim", "(", "$", "str", ",", "$", "charlist", ")", ":", "trim", "(", "$", "str", ")", ";", "}" ]
trim string @param string $str @param array $charlist @return string
[ "trim", "string" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L97-L100
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.ltrim
public function ltrim($str, $charlist = null) { return isset($charlist) ? ltrim($str, $charlist) : ltrim($str); }
php
public function ltrim($str, $charlist = null) { return isset($charlist) ? ltrim($str, $charlist) : ltrim($str); }
[ "public", "function", "ltrim", "(", "$", "str", ",", "$", "charlist", "=", "null", ")", "{", "return", "isset", "(", "$", "charlist", ")", "?", "ltrim", "(", "$", "str", ",", "$", "charlist", ")", ":", "ltrim", "(", "$", "str", ")", ";", "}" ]
left trim string @param string $str @param array $charlist @return string
[ "left", "trim", "string" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L109-L112
wenbinye/PhalconX
src/Mvc/ViewHelper.php
ViewHelper.rtrim
public function rtrim($str, $charlist = null) { return isset($charlist) ? rtrim($str, $charlist) : rtrim($str); }
php
public function rtrim($str, $charlist = null) { return isset($charlist) ? rtrim($str, $charlist) : rtrim($str); }
[ "public", "function", "rtrim", "(", "$", "str", ",", "$", "charlist", "=", "null", ")", "{", "return", "isset", "(", "$", "charlist", ")", "?", "rtrim", "(", "$", "str", ",", "$", "charlist", ")", ":", "rtrim", "(", "$", "str", ")", ";", "}" ]
right trim string @param string $str @param array $charlist @return string
[ "right", "trim", "string" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Mvc/ViewHelper.php#L121-L124
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zInit
private function zInit($flagCert = false) { //se as chaves foram passadas na forma de strings então verificar a validade if ($flagCert) { //já que o certificado existe, verificar seu prazo de validade //o certificado será removido se estiver vencido if (! $this->ignoreValidCert) { return $this->zValidCerts($this->pubKey); } } else { if (substr($this->pathCerts, -1) !== DIRECTORY_SEPARATOR) { $this->pathCerts .= DIRECTORY_SEPARATOR; } //monta o path completo com o nome da chave privada $this->priKeyFile = $this->pathCerts . $this->cnpj . '_priKEY.pem'; //monta o path completo com o nome da chave publica $this->pubKeyFile = $this->pathCerts . $this->cnpj . '_pubKEY.pem'; //monta o path completo com o nome do certificado (chave publica e privada) em formato pem $this->certKeyFile = $this->pathCerts . $this->cnpj . '_certKEY.pem'; //se as chaves não foram passadas em strings, verifica se os certificados existem if (is_file($this->priKeyFile) && is_file($this->pubKeyFile) && is_file($this->certKeyFile)) { //se as chaves existem deve ser verificado sua validade $this->pubKey = file_get_contents($this->pubKeyFile); $this->priKey = file_get_contents($this->priKeyFile); $this->certKey = file_get_contents($this->certKeyFile); //já que o certificado existe, verificar seu prazo de validade if (! $this->ignoreValidCert) { return $this->zValidCerts($this->pubKey); } } } return true; }
php
private function zInit($flagCert = false) { //se as chaves foram passadas na forma de strings então verificar a validade if ($flagCert) { //já que o certificado existe, verificar seu prazo de validade //o certificado será removido se estiver vencido if (! $this->ignoreValidCert) { return $this->zValidCerts($this->pubKey); } } else { if (substr($this->pathCerts, -1) !== DIRECTORY_SEPARATOR) { $this->pathCerts .= DIRECTORY_SEPARATOR; } //monta o path completo com o nome da chave privada $this->priKeyFile = $this->pathCerts . $this->cnpj . '_priKEY.pem'; //monta o path completo com o nome da chave publica $this->pubKeyFile = $this->pathCerts . $this->cnpj . '_pubKEY.pem'; //monta o path completo com o nome do certificado (chave publica e privada) em formato pem $this->certKeyFile = $this->pathCerts . $this->cnpj . '_certKEY.pem'; //se as chaves não foram passadas em strings, verifica se os certificados existem if (is_file($this->priKeyFile) && is_file($this->pubKeyFile) && is_file($this->certKeyFile)) { //se as chaves existem deve ser verificado sua validade $this->pubKey = file_get_contents($this->pubKeyFile); $this->priKey = file_get_contents($this->priKeyFile); $this->certKey = file_get_contents($this->certKeyFile); //já que o certificado existe, verificar seu prazo de validade if (! $this->ignoreValidCert) { return $this->zValidCerts($this->pubKey); } } } return true; }
[ "private", "function", "zInit", "(", "$", "flagCert", "=", "false", ")", "{", "//se as chaves foram passadas na forma de strings então verificar a validade", "if", "(", "$", "flagCert", ")", "{", "//já que o certificado existe, verificar seu prazo de validade", "//o certificado será removido se estiver vencido", "if", "(", "!", "$", "this", "->", "ignoreValidCert", ")", "{", "return", "$", "this", "->", "zValidCerts", "(", "$", "this", "->", "pubKey", ")", ";", "}", "}", "else", "{", "if", "(", "substr", "(", "$", "this", "->", "pathCerts", ",", "-", "1", ")", "!==", "DIRECTORY_SEPARATOR", ")", "{", "$", "this", "->", "pathCerts", ".=", "DIRECTORY_SEPARATOR", ";", "}", "//monta o path completo com o nome da chave privada", "$", "this", "->", "priKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_priKEY.pem'", ";", "//monta o path completo com o nome da chave publica", "$", "this", "->", "pubKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_pubKEY.pem'", ";", "//monta o path completo com o nome do certificado (chave publica e privada) em formato pem", "$", "this", "->", "certKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_certKEY.pem'", ";", "//se as chaves não foram passadas em strings, verifica se os certificados existem", "if", "(", "is_file", "(", "$", "this", "->", "priKeyFile", ")", "&&", "is_file", "(", "$", "this", "->", "pubKeyFile", ")", "&&", "is_file", "(", "$", "this", "->", "certKeyFile", ")", ")", "{", "//se as chaves existem deve ser verificado sua validade", "$", "this", "->", "pubKey", "=", "file_get_contents", "(", "$", "this", "->", "pubKeyFile", ")", ";", "$", "this", "->", "priKey", "=", "file_get_contents", "(", "$", "this", "->", "priKeyFile", ")", ";", "$", "this", "->", "certKey", "=", "file_get_contents", "(", "$", "this", "->", "certKeyFile", ")", ";", "//já que o certificado existe, verificar seu prazo de validade", "if", "(", "!", "$", "this", "->", "ignoreValidCert", ")", "{", "return", "$", "this", "->", "zValidCerts", "(", "$", "this", "->", "pubKey", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
zInit Método de inicialização da classe irá verificar os parâmetros, arquivos e validade dos mesmos Em caso de erro o motivo da falha será indicada na parâmetro error da classe, os outros parâmetros serão limpos e os arquivos inválidos serão removidos da pasta. @param bool $flagCert indica que as chaves já foram passas como strings @return bool
[ "zInit", "Método", "de", "inicialização", "da", "classe", "irá", "verificar", "os", "parâmetros", "arquivos", "e", "validade", "dos", "mesmos", "Em", "caso", "de", "erro", "o", "motivo", "da", "falha", "será", "indicada", "na", "parâmetro", "error", "da", "classe", "os", "outros", "parâmetros", "serão", "limpos", "e", "os", "arquivos", "inválidos", "serão", "removidos", "da", "pasta", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L149-L182
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.loadPfxFile
public function loadPfxFile( $pathPfx = '', $password = '', $createFiles = true, $ignoreValidity = false, $ignoreOwner = false ) { if (! is_file($pathPfx)) { throw new Exception( "O nome do arquivo PFX deve ser passado. Não foi localizado o arquivo [$pathPfx]." ); } $this->pfxCert = file_get_contents($pathPfx); return $this->loadPfx($this->pfxCert, $password, $createFiles, $ignoreValidity, $ignoreOwner); }
php
public function loadPfxFile( $pathPfx = '', $password = '', $createFiles = true, $ignoreValidity = false, $ignoreOwner = false ) { if (! is_file($pathPfx)) { throw new Exception( "O nome do arquivo PFX deve ser passado. Não foi localizado o arquivo [$pathPfx]." ); } $this->pfxCert = file_get_contents($pathPfx); return $this->loadPfx($this->pfxCert, $password, $createFiles, $ignoreValidity, $ignoreOwner); }
[ "public", "function", "loadPfxFile", "(", "$", "pathPfx", "=", "''", ",", "$", "password", "=", "''", ",", "$", "createFiles", "=", "true", ",", "$", "ignoreValidity", "=", "false", ",", "$", "ignoreOwner", "=", "false", ")", "{", "if", "(", "!", "is_file", "(", "$", "pathPfx", ")", ")", "{", "throw", "new", "Exception", "(", "\"O nome do arquivo PFX deve ser passado. Não foi localizado o arquivo [$pathPfx].\"", ")", ";", "}", "$", "this", "->", "pfxCert", "=", "file_get_contents", "(", "$", "pathPfx", ")", ";", "return", "$", "this", "->", "loadPfx", "(", "$", "this", "->", "pfxCert", ",", "$", "password", ",", "$", "createFiles", ",", "$", "ignoreValidity", ",", "$", "ignoreOwner", ")", ";", "}" ]
loadPfxFile. @param string $pathPfx caminho completo para o arquivo pfx @param string $password senha para abrir o certificado pfx @param bool $createFiles @param bool $ignoreValidity @param bool $ignoreOwner @return bool
[ "loadPfxFile", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L195-L210
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.loadPfx
public function loadPfx( $pfxContent = '', $password = '', $createFiles = true, $ignoreValidity = false, $ignoreOwner = false ) { if ($password == '') { throw new Exception( 'A senha de acesso para o certificado pfx não pode ser vazia.' ); } //carrega os certificados e chaves para um array denominado $x509certdata $x509certdata = []; if (! openssl_pkcs12_read($pfxContent, $x509certdata, $password)) { throw new Exception( 'O certificado não pode ser lido!! Senha errada ou arquivo corrompido ou formato inválido!!' ); } $this->pfxCert = $pfxContent; if (! $ignoreValidity) { //verifica sua data de validade if (! $this->zValidCerts($x509certdata['cert'])) { throw new Exception($this->error); } } if (! $ignoreOwner) { $cnpjCert = Asn::getCNPJCert($x509certdata['cert']); if (substr($this->cnpj, 0, 8) != substr($cnpjCert, 0, 8)) { throw new Exception( 'O Certificado fornecido pertence a outro CNPJ!!' ); } } //monta o path completo com o nome da chave privada $this->priKeyFile = $this->pathCerts . $this->cnpj . '_priKEY.pem'; //monta o path completo com o nome da chave publica $this->pubKeyFile = $this->pathCerts . $this->cnpj . '_pubKEY.pem'; //monta o path completo com o nome do certificado (chave publica e privada) em formato pem $this->certKeyFile = $this->pathCerts . $this->cnpj . '_certKEY.pem'; $this->zRemovePemFiles(); if ($createFiles) { $this->zSavePemFiles($x509certdata); } $this->pubKey = $x509certdata['cert']; $this->priKey = $x509certdata['pkey']; $this->certKey = $x509certdata['pkey'] . "\r\n" . $x509certdata['cert']; return true; }
php
public function loadPfx( $pfxContent = '', $password = '', $createFiles = true, $ignoreValidity = false, $ignoreOwner = false ) { if ($password == '') { throw new Exception( 'A senha de acesso para o certificado pfx não pode ser vazia.' ); } //carrega os certificados e chaves para um array denominado $x509certdata $x509certdata = []; if (! openssl_pkcs12_read($pfxContent, $x509certdata, $password)) { throw new Exception( 'O certificado não pode ser lido!! Senha errada ou arquivo corrompido ou formato inválido!!' ); } $this->pfxCert = $pfxContent; if (! $ignoreValidity) { //verifica sua data de validade if (! $this->zValidCerts($x509certdata['cert'])) { throw new Exception($this->error); } } if (! $ignoreOwner) { $cnpjCert = Asn::getCNPJCert($x509certdata['cert']); if (substr($this->cnpj, 0, 8) != substr($cnpjCert, 0, 8)) { throw new Exception( 'O Certificado fornecido pertence a outro CNPJ!!' ); } } //monta o path completo com o nome da chave privada $this->priKeyFile = $this->pathCerts . $this->cnpj . '_priKEY.pem'; //monta o path completo com o nome da chave publica $this->pubKeyFile = $this->pathCerts . $this->cnpj . '_pubKEY.pem'; //monta o path completo com o nome do certificado (chave publica e privada) em formato pem $this->certKeyFile = $this->pathCerts . $this->cnpj . '_certKEY.pem'; $this->zRemovePemFiles(); if ($createFiles) { $this->zSavePemFiles($x509certdata); } $this->pubKey = $x509certdata['cert']; $this->priKey = $x509certdata['pkey']; $this->certKey = $x509certdata['pkey'] . "\r\n" . $x509certdata['cert']; return true; }
[ "public", "function", "loadPfx", "(", "$", "pfxContent", "=", "''", ",", "$", "password", "=", "''", ",", "$", "createFiles", "=", "true", ",", "$", "ignoreValidity", "=", "false", ",", "$", "ignoreOwner", "=", "false", ")", "{", "if", "(", "$", "password", "==", "''", ")", "{", "throw", "new", "Exception", "(", "'A senha de acesso para o certificado pfx não pode ser vazia.'", ")", ";", "}", "//carrega os certificados e chaves para um array denominado $x509certdata", "$", "x509certdata", "=", "[", "]", ";", "if", "(", "!", "openssl_pkcs12_read", "(", "$", "pfxContent", ",", "$", "x509certdata", ",", "$", "password", ")", ")", "{", "throw", "new", "Exception", "(", "'O certificado não pode ser lido!! Senha errada ou arquivo corrompido ou formato inválido!!'", ")", ";", "}", "$", "this", "->", "pfxCert", "=", "$", "pfxContent", ";", "if", "(", "!", "$", "ignoreValidity", ")", "{", "//verifica sua data de validade", "if", "(", "!", "$", "this", "->", "zValidCerts", "(", "$", "x509certdata", "[", "'cert'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "$", "this", "->", "error", ")", ";", "}", "}", "if", "(", "!", "$", "ignoreOwner", ")", "{", "$", "cnpjCert", "=", "Asn", "::", "getCNPJCert", "(", "$", "x509certdata", "[", "'cert'", "]", ")", ";", "if", "(", "substr", "(", "$", "this", "->", "cnpj", ",", "0", ",", "8", ")", "!=", "substr", "(", "$", "cnpjCert", ",", "0", ",", "8", ")", ")", "{", "throw", "new", "Exception", "(", "'O Certificado fornecido pertence a outro CNPJ!!'", ")", ";", "}", "}", "//monta o path completo com o nome da chave privada", "$", "this", "->", "priKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_priKEY.pem'", ";", "//monta o path completo com o nome da chave publica", "$", "this", "->", "pubKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_pubKEY.pem'", ";", "//monta o path completo com o nome do certificado (chave publica e privada) em formato pem", "$", "this", "->", "certKeyFile", "=", "$", "this", "->", "pathCerts", ".", "$", "this", "->", "cnpj", ".", "'_certKEY.pem'", ";", "$", "this", "->", "zRemovePemFiles", "(", ")", ";", "if", "(", "$", "createFiles", ")", "{", "$", "this", "->", "zSavePemFiles", "(", "$", "x509certdata", ")", ";", "}", "$", "this", "->", "pubKey", "=", "$", "x509certdata", "[", "'cert'", "]", ";", "$", "this", "->", "priKey", "=", "$", "x509certdata", "[", "'pkey'", "]", ";", "$", "this", "->", "certKey", "=", "$", "x509certdata", "[", "'pkey'", "]", ".", "\"\\r\\n\"", ".", "$", "x509certdata", "[", "'cert'", "]", ";", "return", "true", ";", "}" ]
loadPfx Carrega um novo certificado no formato PFX Isso deverá ocorrer a cada atualização do certificado digital, ou seja, pelo menos uma vez por ano, uma vez que a validade do certificado é anual. Será verificado também se o certificado pertence realmente ao CNPJ Essa verificação checa apenas se o certificado pertence a matriz ou filial comparando apenas os primeiros 8 digitos do CNPJ, dessa forma ambas a matriz e as filiais poderão usar o mesmo certificado indicado na instanciação da classe, se não for um erro irá ocorrer e o certificado não será convertido para o formato PEM. Em caso de erros, será retornado false e o motivo será indicado no parâmetro error da classe. Os certificados serão armazenados como <CNPJ>-<tipo>.pem. @param string $pfxContent arquivo PFX @param string $password Senha de acesso ao certificado PFX @param bool $createFiles se true irá criar os arquivos pem das chaves digitais, caso contrario não @param bool $ignoreValidity @param bool $ignoreOwner @return bool
[ "loadPfx", "Carrega", "um", "novo", "certificado", "no", "formato", "PFX", "Isso", "deverá", "ocorrer", "a", "cada", "atualização", "do", "certificado", "digital", "ou", "seja", "pelo", "menos", "uma", "vez", "por", "ano", "uma", "vez", "que", "a", "validade", "do", "certificado", "é", "anual", ".", "Será", "verificado", "também", "se", "o", "certificado", "pertence", "realmente", "ao", "CNPJ", "Essa", "verificação", "checa", "apenas", "se", "o", "certificado", "pertence", "a", "matriz", "ou", "filial", "comparando", "apenas", "os", "primeiros", "8", "digitos", "do", "CNPJ", "dessa", "forma", "ambas", "a", "matriz", "e", "as", "filiais", "poderão", "usar", "o", "mesmo", "certificado", "indicado", "na", "instanciação", "da", "classe", "se", "não", "for", "um", "erro", "irá", "ocorrer", "e", "o", "certificado", "não", "será", "convertido", "para", "o", "formato", "PEM", ".", "Em", "caso", "de", "erros", "será", "retornado", "false", "e", "o", "motivo", "será", "indicado", "no", "parâmetro", "error", "da", "classe", ".", "Os", "certificados", "serão", "armazenados", "como", "<CNPJ", ">", "-", "<tipo", ">", ".", "pem", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L234-L283
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zSavePemFiles
private function zSavePemFiles($x509certdata) { if (empty($this->pathCerts)) { throw new Exception( 'Não está definido o diretório para armazenar os certificados.' ); } if (! is_dir($this->pathCerts)) { throw new Exception( 'Não existe o diretório para armazenar os certificados.' ); } //recriar os arquivos pem com o arquivo pfx if (! file_put_contents($this->priKeyFile, $x509certdata['pkey'])) { throw new Exception( 'Falha de permissão de escrita na pasta dos certificados!!' ); } file_put_contents($this->pubKeyFile, $x509certdata['cert']); file_put_contents($this->certKeyFile, $x509certdata['pkey'] . "\r\n" . $x509certdata['cert']); }
php
private function zSavePemFiles($x509certdata) { if (empty($this->pathCerts)) { throw new Exception( 'Não está definido o diretório para armazenar os certificados.' ); } if (! is_dir($this->pathCerts)) { throw new Exception( 'Não existe o diretório para armazenar os certificados.' ); } //recriar os arquivos pem com o arquivo pfx if (! file_put_contents($this->priKeyFile, $x509certdata['pkey'])) { throw new Exception( 'Falha de permissão de escrita na pasta dos certificados!!' ); } file_put_contents($this->pubKeyFile, $x509certdata['cert']); file_put_contents($this->certKeyFile, $x509certdata['pkey'] . "\r\n" . $x509certdata['cert']); }
[ "private", "function", "zSavePemFiles", "(", "$", "x509certdata", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "pathCerts", ")", ")", "{", "throw", "new", "Exception", "(", "'Não está definido o diretório para armazenar os certificados.'", ")", ";", "}", "if", "(", "!", "is_dir", "(", "$", "this", "->", "pathCerts", ")", ")", "{", "throw", "new", "Exception", "(", "'Não existe o diretório para armazenar os certificados.'", ")", ";", "}", "//recriar os arquivos pem com o arquivo pfx", "if", "(", "!", "file_put_contents", "(", "$", "this", "->", "priKeyFile", ",", "$", "x509certdata", "[", "'pkey'", "]", ")", ")", "{", "throw", "new", "Exception", "(", "'Falha de permissão de escrita na pasta dos certificados!!'", ")", ";", "}", "file_put_contents", "(", "$", "this", "->", "pubKeyFile", ",", "$", "x509certdata", "[", "'cert'", "]", ")", ";", "file_put_contents", "(", "$", "this", "->", "certKeyFile", ",", "$", "x509certdata", "[", "'pkey'", "]", ".", "\"\\r\\n\"", ".", "$", "x509certdata", "[", "'cert'", "]", ")", ";", "}" ]
zSavePemFiles. @param array $x509certdata @throws Exception @throws Exception
[ "zSavePemFiles", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L291-L311
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.aadChain
public function aadChain($aCerts = []) { $certificate = $this->certKey; foreach ($aCerts as $cert) { if (is_file($cert)) { $dados = file_get_contents($cert); $certificate .= "\r\n" . $dados; } else { $certificate .= "\r\n" . $cert; } } $this->certKey = $certificate; if (is_file($this->certKeyFile)) { file_put_contents($this->certKeyFile, $certificate); } }
php
public function aadChain($aCerts = []) { $certificate = $this->certKey; foreach ($aCerts as $cert) { if (is_file($cert)) { $dados = file_get_contents($cert); $certificate .= "\r\n" . $dados; } else { $certificate .= "\r\n" . $cert; } } $this->certKey = $certificate; if (is_file($this->certKeyFile)) { file_put_contents($this->certKeyFile, $certificate); } }
[ "public", "function", "aadChain", "(", "$", "aCerts", "=", "[", "]", ")", "{", "$", "certificate", "=", "$", "this", "->", "certKey", ";", "foreach", "(", "$", "aCerts", "as", "$", "cert", ")", "{", "if", "(", "is_file", "(", "$", "cert", ")", ")", "{", "$", "dados", "=", "file_get_contents", "(", "$", "cert", ")", ";", "$", "certificate", ".=", "\"\\r\\n\"", ".", "$", "dados", ";", "}", "else", "{", "$", "certificate", ".=", "\"\\r\\n\"", ".", "$", "cert", ";", "}", "}", "$", "this", "->", "certKey", "=", "$", "certificate", ";", "if", "(", "is_file", "(", "$", "this", "->", "certKeyFile", ")", ")", "{", "file_put_contents", "(", "$", "this", "->", "certKeyFile", ",", "$", "certificate", ")", ";", "}", "}" ]
aadChain. @param array $aCerts Array com os caminhos completos para cada certificado da cadeia ou um array com o conteúdo desses certificados @return void
[ "aadChain", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L319-L334
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.signXML
public function signXML($docxml, $tagid = '') { //caso não tenha as chaves cai fora if ($this->pubKey == '' || $this->priKey == '') { $msg = 'As chaves não estão disponíveis.'; throw new Exception($msg); } //caso não seja informada a tag a ser assinada cai fora if ($tagid == '') { $msg = 'A tag a ser assinada deve ser indicada.'; throw new Exception($msg); } //carrega a chave privada no openssl $objSSLPriKey = openssl_get_privatekey($this->priKey); if ($objSSLPriKey === false) { $msg = 'Houve erro no carregamento da chave privada.'; $this->zGetOpenSSLError($msg); } $xml = $docxml; if (is_file($docxml)) { $xml = file_get_contents($docxml); } //remove sujeiras do xml $order = ["\r\n", "\n", "\r", "\t"]; $xml = str_replace($order, '', $xml); $xmldoc = new Dom(); $xmldoc->loadXMLString($xml); //coloca o node raiz em uma variável $root = $xmldoc->documentElement; //extrair a tag com os dados a serem assinados $node = $xmldoc->getElementsByTagName($tagid)->item(0); if (! isset($node)) { throw new Exception( "A tag < $tagid > não existe no XML!!" ); } $this->docId = $node->getAttribute('Id'); $xmlResp = $xml; if (! $this->zSignatureExists($xmldoc)) { //executa a assinatura $xmlResp = $this->zSignXML($xmldoc, $root, $node, $objSSLPriKey); } //libera a chave privada openssl_free_key($objSSLPriKey); return $xmlResp; }
php
public function signXML($docxml, $tagid = '') { //caso não tenha as chaves cai fora if ($this->pubKey == '' || $this->priKey == '') { $msg = 'As chaves não estão disponíveis.'; throw new Exception($msg); } //caso não seja informada a tag a ser assinada cai fora if ($tagid == '') { $msg = 'A tag a ser assinada deve ser indicada.'; throw new Exception($msg); } //carrega a chave privada no openssl $objSSLPriKey = openssl_get_privatekey($this->priKey); if ($objSSLPriKey === false) { $msg = 'Houve erro no carregamento da chave privada.'; $this->zGetOpenSSLError($msg); } $xml = $docxml; if (is_file($docxml)) { $xml = file_get_contents($docxml); } //remove sujeiras do xml $order = ["\r\n", "\n", "\r", "\t"]; $xml = str_replace($order, '', $xml); $xmldoc = new Dom(); $xmldoc->loadXMLString($xml); //coloca o node raiz em uma variável $root = $xmldoc->documentElement; //extrair a tag com os dados a serem assinados $node = $xmldoc->getElementsByTagName($tagid)->item(0); if (! isset($node)) { throw new Exception( "A tag < $tagid > não existe no XML!!" ); } $this->docId = $node->getAttribute('Id'); $xmlResp = $xml; if (! $this->zSignatureExists($xmldoc)) { //executa a assinatura $xmlResp = $this->zSignXML($xmldoc, $root, $node, $objSSLPriKey); } //libera a chave privada openssl_free_key($objSSLPriKey); return $xmlResp; }
[ "public", "function", "signXML", "(", "$", "docxml", ",", "$", "tagid", "=", "''", ")", "{", "//caso não tenha as chaves cai fora", "if", "(", "$", "this", "->", "pubKey", "==", "''", "||", "$", "this", "->", "priKey", "==", "''", ")", "{", "$", "msg", "=", "'As chaves não estão disponíveis.';", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "//caso não seja informada a tag a ser assinada cai fora", "if", "(", "$", "tagid", "==", "''", ")", "{", "$", "msg", "=", "'A tag a ser assinada deve ser indicada.'", ";", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "//carrega a chave privada no openssl", "$", "objSSLPriKey", "=", "openssl_get_privatekey", "(", "$", "this", "->", "priKey", ")", ";", "if", "(", "$", "objSSLPriKey", "===", "false", ")", "{", "$", "msg", "=", "'Houve erro no carregamento da chave privada.'", ";", "$", "this", "->", "zGetOpenSSLError", "(", "$", "msg", ")", ";", "}", "$", "xml", "=", "$", "docxml", ";", "if", "(", "is_file", "(", "$", "docxml", ")", ")", "{", "$", "xml", "=", "file_get_contents", "(", "$", "docxml", ")", ";", "}", "//remove sujeiras do xml", "$", "order", "=", "[", "\"\\r\\n\"", ",", "\"\\n\"", ",", "\"\\r\"", ",", "\"\\t\"", "]", ";", "$", "xml", "=", "str_replace", "(", "$", "order", ",", "''", ",", "$", "xml", ")", ";", "$", "xmldoc", "=", "new", "Dom", "(", ")", ";", "$", "xmldoc", "->", "loadXMLString", "(", "$", "xml", ")", ";", "//coloca o node raiz em uma variável", "$", "root", "=", "$", "xmldoc", "->", "documentElement", ";", "//extrair a tag com os dados a serem assinados", "$", "node", "=", "$", "xmldoc", "->", "getElementsByTagName", "(", "$", "tagid", ")", "->", "item", "(", "0", ")", ";", "if", "(", "!", "isset", "(", "$", "node", ")", ")", "{", "throw", "new", "Exception", "(", "\"A tag < $tagid > não existe no XML!!\"", ")", ";", "}", "$", "this", "->", "docId", "=", "$", "node", "->", "getAttribute", "(", "'Id'", ")", ";", "$", "xmlResp", "=", "$", "xml", ";", "if", "(", "!", "$", "this", "->", "zSignatureExists", "(", "$", "xmldoc", ")", ")", "{", "//executa a assinatura", "$", "xmlResp", "=", "$", "this", "->", "zSignXML", "(", "$", "xmldoc", ",", "$", "root", ",", "$", "node", ",", "$", "objSSLPriKey", ")", ";", "}", "//libera a chave privada", "openssl_free_key", "(", "$", "objSSLPriKey", ")", ";", "return", "$", "xmlResp", ";", "}" ]
signXML. @param string $docxml @param string $tagid @return string xml assinado @throws Exception @throws Exception
[ "signXML", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L344-L390
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zSignXML
public function zSignXML($xmldoc, $root, $node, $objSSLPriKey) { $nsDSIG = 'http://www.w3.org/2000/09/xmldsig#'; $nsCannonMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'; $nsSignatureMethod = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; $nsTransformMethod1 = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature'; $nsTransformMethod2 = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'; $nsDigestMethod = 'http://www.w3.org/2000/09/xmldsig#sha1'; //pega o atributo id do node a ser assinado $idSigned = (trim($node->getAttribute('Id') == null) ? $node->getAttribute('id') : $node->getAttribute('Id')); //extrai os dados da tag para uma string na forma canonica $dados = $node->C14N(true, false, null, null); //calcular o hash dos dados $hashValue = hash('sha1', $dados, true); //converter o hash para base64 $digValue = base64_encode($hashValue); //cria o node <Signature> $signatureNode = $xmldoc->createElementNS($nsDSIG, 'Signature'); //adiciona a tag <Signature> ao node raiz $root->appendChild($signatureNode); //cria o node <SignedInfo> $signedInfoNode = $xmldoc->createElement('SignedInfo'); //adiciona o node <SignedInfo> ao <Signature> $signatureNode->appendChild($signedInfoNode); //cria no node com o método de canonização dos dados $canonicalNode = $xmldoc->createElement('CanonicalizationMethod'); //adiona o <CanonicalizationMethod> ao node <SignedInfo> $signedInfoNode->appendChild($canonicalNode); //seta o atributo ao node <CanonicalizationMethod> $canonicalNode->setAttribute('Algorithm', $nsCannonMethod); //cria o node <SignatureMethod> $signatureMethodNode = $xmldoc->createElement('SignatureMethod'); //adiciona o node <SignatureMethod> ao node <SignedInfo> $signedInfoNode->appendChild($signatureMethodNode); //seta o atributo Algorithm ao node <SignatureMethod> $signatureMethodNode->setAttribute('Algorithm', $nsSignatureMethod); //cria o node <Reference> $referenceNode = $xmldoc->createElement('Reference'); //adiciona o node <Reference> ao node <SignedInfo> $signedInfoNode->appendChild($referenceNode); //seta o atributo URI a node <Reference> $idSigned == null ? $referenceNode->setAttribute('URI', '' . $idSigned) : $referenceNode->setAttribute('URI', '#' . $idSigned); //cria o node <Transforms> $transformsNode = $xmldoc->createElement('Transforms'); //adiciona o node <Transforms> ao node <Reference> $referenceNode->appendChild($transformsNode); //cria o primeiro node <Transform> OBS: no singular $transfNode1 = $xmldoc->createElement('Transform'); //adiciona o primeiro node <Transform> ao node <Transforms> $transformsNode->appendChild($transfNode1); //set o atributo Algorithm ao primeiro node <Transform> $transfNode1->setAttribute('Algorithm', $nsTransformMethod1); //cria outro node <Transform> OBS: no singular $transfNode2 = $xmldoc->createElement('Transform'); //adiciona o segundo node <Transform> ao node <Transforms> $transformsNode->appendChild($transfNode2); //set o atributo Algorithm ao segundo node <Transform> $transfNode2->setAttribute('Algorithm', $nsTransformMethod2); //cria o node <DigestMethod> $digestMethodNode = $xmldoc->createElement('DigestMethod'); //adiciona o node <DigestMethod> ao node <Reference> $referenceNode->appendChild($digestMethodNode); //seta o atributo Algorithm ao node <DigestMethod> $digestMethodNode->setAttribute('Algorithm', $nsDigestMethod); //cria o node <DigestValue> $digestValueNode = $xmldoc->createElement('DigestValue', $digValue); //adiciona o node <DigestValue> ao node <Reference> $referenceNode->appendChild($digestValueNode); //extrai node <SignedInfo> para uma string na sua forma canonica $cnSignedInfoNode = $signedInfoNode->C14N(true, false, null, null); //cria uma variavel vazia que receberá a assinatura $signature = ''; //calcula a assinatura do node canonizado <SignedInfo> //usando a chave privada em formato PEM if (! openssl_sign($cnSignedInfoNode, $signature, $objSSLPriKey)) { $msg = "Houve erro durante a assinatura digital.\n"; $this->zGetOpenSSLError($msg); } //converte a assinatura em base64 $signatureValue = base64_encode($signature); //cria o node <SignatureValue> $signatureValueNode = $xmldoc->createElement('SignatureValue', $signatureValue); //adiciona o node <SignatureValue> ao node <Signature> $signatureNode->appendChild($signatureValueNode); //cria o node <KeyInfo> $keyInfoNode = $xmldoc->createElement('KeyInfo'); //adiciona o node <KeyInfo> ao node <Signature> $signatureNode->appendChild($keyInfoNode); //cria o node <X509Data> $x509DataNode = $xmldoc->createElement('X509Data'); //adiciona o node <X509Data> ao node <KeyInfo> $keyInfoNode->appendChild($x509DataNode); //remove linhas desnecessárias do certificado $pubKeyClean = $this->zCleanPubKey(); //cria o node <X509Certificate> $x509CertificateNode = $xmldoc->createElement('X509Certificate', $pubKeyClean); //adiciona o node <X509Certificate> ao node <X509Data> $x509DataNode->appendChild($x509CertificateNode); //salva o xml completo em uma string $xmlResp = $xmldoc->saveXML(); //retorna o documento assinado return $xmlResp; }
php
public function zSignXML($xmldoc, $root, $node, $objSSLPriKey) { $nsDSIG = 'http://www.w3.org/2000/09/xmldsig#'; $nsCannonMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'; $nsSignatureMethod = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'; $nsTransformMethod1 = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature'; $nsTransformMethod2 = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'; $nsDigestMethod = 'http://www.w3.org/2000/09/xmldsig#sha1'; //pega o atributo id do node a ser assinado $idSigned = (trim($node->getAttribute('Id') == null) ? $node->getAttribute('id') : $node->getAttribute('Id')); //extrai os dados da tag para uma string na forma canonica $dados = $node->C14N(true, false, null, null); //calcular o hash dos dados $hashValue = hash('sha1', $dados, true); //converter o hash para base64 $digValue = base64_encode($hashValue); //cria o node <Signature> $signatureNode = $xmldoc->createElementNS($nsDSIG, 'Signature'); //adiciona a tag <Signature> ao node raiz $root->appendChild($signatureNode); //cria o node <SignedInfo> $signedInfoNode = $xmldoc->createElement('SignedInfo'); //adiciona o node <SignedInfo> ao <Signature> $signatureNode->appendChild($signedInfoNode); //cria no node com o método de canonização dos dados $canonicalNode = $xmldoc->createElement('CanonicalizationMethod'); //adiona o <CanonicalizationMethod> ao node <SignedInfo> $signedInfoNode->appendChild($canonicalNode); //seta o atributo ao node <CanonicalizationMethod> $canonicalNode->setAttribute('Algorithm', $nsCannonMethod); //cria o node <SignatureMethod> $signatureMethodNode = $xmldoc->createElement('SignatureMethod'); //adiciona o node <SignatureMethod> ao node <SignedInfo> $signedInfoNode->appendChild($signatureMethodNode); //seta o atributo Algorithm ao node <SignatureMethod> $signatureMethodNode->setAttribute('Algorithm', $nsSignatureMethod); //cria o node <Reference> $referenceNode = $xmldoc->createElement('Reference'); //adiciona o node <Reference> ao node <SignedInfo> $signedInfoNode->appendChild($referenceNode); //seta o atributo URI a node <Reference> $idSigned == null ? $referenceNode->setAttribute('URI', '' . $idSigned) : $referenceNode->setAttribute('URI', '#' . $idSigned); //cria o node <Transforms> $transformsNode = $xmldoc->createElement('Transforms'); //adiciona o node <Transforms> ao node <Reference> $referenceNode->appendChild($transformsNode); //cria o primeiro node <Transform> OBS: no singular $transfNode1 = $xmldoc->createElement('Transform'); //adiciona o primeiro node <Transform> ao node <Transforms> $transformsNode->appendChild($transfNode1); //set o atributo Algorithm ao primeiro node <Transform> $transfNode1->setAttribute('Algorithm', $nsTransformMethod1); //cria outro node <Transform> OBS: no singular $transfNode2 = $xmldoc->createElement('Transform'); //adiciona o segundo node <Transform> ao node <Transforms> $transformsNode->appendChild($transfNode2); //set o atributo Algorithm ao segundo node <Transform> $transfNode2->setAttribute('Algorithm', $nsTransformMethod2); //cria o node <DigestMethod> $digestMethodNode = $xmldoc->createElement('DigestMethod'); //adiciona o node <DigestMethod> ao node <Reference> $referenceNode->appendChild($digestMethodNode); //seta o atributo Algorithm ao node <DigestMethod> $digestMethodNode->setAttribute('Algorithm', $nsDigestMethod); //cria o node <DigestValue> $digestValueNode = $xmldoc->createElement('DigestValue', $digValue); //adiciona o node <DigestValue> ao node <Reference> $referenceNode->appendChild($digestValueNode); //extrai node <SignedInfo> para uma string na sua forma canonica $cnSignedInfoNode = $signedInfoNode->C14N(true, false, null, null); //cria uma variavel vazia que receberá a assinatura $signature = ''; //calcula a assinatura do node canonizado <SignedInfo> //usando a chave privada em formato PEM if (! openssl_sign($cnSignedInfoNode, $signature, $objSSLPriKey)) { $msg = "Houve erro durante a assinatura digital.\n"; $this->zGetOpenSSLError($msg); } //converte a assinatura em base64 $signatureValue = base64_encode($signature); //cria o node <SignatureValue> $signatureValueNode = $xmldoc->createElement('SignatureValue', $signatureValue); //adiciona o node <SignatureValue> ao node <Signature> $signatureNode->appendChild($signatureValueNode); //cria o node <KeyInfo> $keyInfoNode = $xmldoc->createElement('KeyInfo'); //adiciona o node <KeyInfo> ao node <Signature> $signatureNode->appendChild($keyInfoNode); //cria o node <X509Data> $x509DataNode = $xmldoc->createElement('X509Data'); //adiciona o node <X509Data> ao node <KeyInfo> $keyInfoNode->appendChild($x509DataNode); //remove linhas desnecessárias do certificado $pubKeyClean = $this->zCleanPubKey(); //cria o node <X509Certificate> $x509CertificateNode = $xmldoc->createElement('X509Certificate', $pubKeyClean); //adiciona o node <X509Certificate> ao node <X509Data> $x509DataNode->appendChild($x509CertificateNode); //salva o xml completo em uma string $xmlResp = $xmldoc->saveXML(); //retorna o documento assinado return $xmlResp; }
[ "public", "function", "zSignXML", "(", "$", "xmldoc", ",", "$", "root", ",", "$", "node", ",", "$", "objSSLPriKey", ")", "{", "$", "nsDSIG", "=", "'http://www.w3.org/2000/09/xmldsig#'", ";", "$", "nsCannonMethod", "=", "'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'", ";", "$", "nsSignatureMethod", "=", "'http://www.w3.org/2000/09/xmldsig#rsa-sha1'", ";", "$", "nsTransformMethod1", "=", "'http://www.w3.org/2000/09/xmldsig#enveloped-signature'", ";", "$", "nsTransformMethod2", "=", "'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'", ";", "$", "nsDigestMethod", "=", "'http://www.w3.org/2000/09/xmldsig#sha1'", ";", "//pega o atributo id do node a ser assinado", "$", "idSigned", "=", "(", "trim", "(", "$", "node", "->", "getAttribute", "(", "'Id'", ")", "==", "null", ")", "?", "$", "node", "->", "getAttribute", "(", "'id'", ")", ":", "$", "node", "->", "getAttribute", "(", "'Id'", ")", ")", ";", "//extrai os dados da tag para uma string na forma canonica", "$", "dados", "=", "$", "node", "->", "C14N", "(", "true", ",", "false", ",", "null", ",", "null", ")", ";", "//calcular o hash dos dados", "$", "hashValue", "=", "hash", "(", "'sha1'", ",", "$", "dados", ",", "true", ")", ";", "//converter o hash para base64", "$", "digValue", "=", "base64_encode", "(", "$", "hashValue", ")", ";", "//cria o node <Signature>", "$", "signatureNode", "=", "$", "xmldoc", "->", "createElementNS", "(", "$", "nsDSIG", ",", "'Signature'", ")", ";", "//adiciona a tag <Signature> ao node raiz", "$", "root", "->", "appendChild", "(", "$", "signatureNode", ")", ";", "//cria o node <SignedInfo>", "$", "signedInfoNode", "=", "$", "xmldoc", "->", "createElement", "(", "'SignedInfo'", ")", ";", "//adiciona o node <SignedInfo> ao <Signature>", "$", "signatureNode", "->", "appendChild", "(", "$", "signedInfoNode", ")", ";", "//cria no node com o método de canonização dos dados", "$", "canonicalNode", "=", "$", "xmldoc", "->", "createElement", "(", "'CanonicalizationMethod'", ")", ";", "//adiona o <CanonicalizationMethod> ao node <SignedInfo>", "$", "signedInfoNode", "->", "appendChild", "(", "$", "canonicalNode", ")", ";", "//seta o atributo ao node <CanonicalizationMethod>", "$", "canonicalNode", "->", "setAttribute", "(", "'Algorithm'", ",", "$", "nsCannonMethod", ")", ";", "//cria o node <SignatureMethod>", "$", "signatureMethodNode", "=", "$", "xmldoc", "->", "createElement", "(", "'SignatureMethod'", ")", ";", "//adiciona o node <SignatureMethod> ao node <SignedInfo>", "$", "signedInfoNode", "->", "appendChild", "(", "$", "signatureMethodNode", ")", ";", "//seta o atributo Algorithm ao node <SignatureMethod>", "$", "signatureMethodNode", "->", "setAttribute", "(", "'Algorithm'", ",", "$", "nsSignatureMethod", ")", ";", "//cria o node <Reference>", "$", "referenceNode", "=", "$", "xmldoc", "->", "createElement", "(", "'Reference'", ")", ";", "//adiciona o node <Reference> ao node <SignedInfo>", "$", "signedInfoNode", "->", "appendChild", "(", "$", "referenceNode", ")", ";", "//seta o atributo URI a node <Reference>", "$", "idSigned", "==", "null", "?", "$", "referenceNode", "->", "setAttribute", "(", "'URI'", ",", "''", ".", "$", "idSigned", ")", ":", "$", "referenceNode", "->", "setAttribute", "(", "'URI'", ",", "'#'", ".", "$", "idSigned", ")", ";", "//cria o node <Transforms>", "$", "transformsNode", "=", "$", "xmldoc", "->", "createElement", "(", "'Transforms'", ")", ";", "//adiciona o node <Transforms> ao node <Reference>", "$", "referenceNode", "->", "appendChild", "(", "$", "transformsNode", ")", ";", "//cria o primeiro node <Transform> OBS: no singular", "$", "transfNode1", "=", "$", "xmldoc", "->", "createElement", "(", "'Transform'", ")", ";", "//adiciona o primeiro node <Transform> ao node <Transforms>", "$", "transformsNode", "->", "appendChild", "(", "$", "transfNode1", ")", ";", "//set o atributo Algorithm ao primeiro node <Transform>", "$", "transfNode1", "->", "setAttribute", "(", "'Algorithm'", ",", "$", "nsTransformMethod1", ")", ";", "//cria outro node <Transform> OBS: no singular", "$", "transfNode2", "=", "$", "xmldoc", "->", "createElement", "(", "'Transform'", ")", ";", "//adiciona o segundo node <Transform> ao node <Transforms>", "$", "transformsNode", "->", "appendChild", "(", "$", "transfNode2", ")", ";", "//set o atributo Algorithm ao segundo node <Transform>", "$", "transfNode2", "->", "setAttribute", "(", "'Algorithm'", ",", "$", "nsTransformMethod2", ")", ";", "//cria o node <DigestMethod>", "$", "digestMethodNode", "=", "$", "xmldoc", "->", "createElement", "(", "'DigestMethod'", ")", ";", "//adiciona o node <DigestMethod> ao node <Reference>", "$", "referenceNode", "->", "appendChild", "(", "$", "digestMethodNode", ")", ";", "//seta o atributo Algorithm ao node <DigestMethod>", "$", "digestMethodNode", "->", "setAttribute", "(", "'Algorithm'", ",", "$", "nsDigestMethod", ")", ";", "//cria o node <DigestValue>", "$", "digestValueNode", "=", "$", "xmldoc", "->", "createElement", "(", "'DigestValue'", ",", "$", "digValue", ")", ";", "//adiciona o node <DigestValue> ao node <Reference>", "$", "referenceNode", "->", "appendChild", "(", "$", "digestValueNode", ")", ";", "//extrai node <SignedInfo> para uma string na sua forma canonica", "$", "cnSignedInfoNode", "=", "$", "signedInfoNode", "->", "C14N", "(", "true", ",", "false", ",", "null", ",", "null", ")", ";", "//cria uma variavel vazia que receberá a assinatura", "$", "signature", "=", "''", ";", "//calcula a assinatura do node canonizado <SignedInfo>", "//usando a chave privada em formato PEM", "if", "(", "!", "openssl_sign", "(", "$", "cnSignedInfoNode", ",", "$", "signature", ",", "$", "objSSLPriKey", ")", ")", "{", "$", "msg", "=", "\"Houve erro durante a assinatura digital.\\n\"", ";", "$", "this", "->", "zGetOpenSSLError", "(", "$", "msg", ")", ";", "}", "//converte a assinatura em base64", "$", "signatureValue", "=", "base64_encode", "(", "$", "signature", ")", ";", "//cria o node <SignatureValue>", "$", "signatureValueNode", "=", "$", "xmldoc", "->", "createElement", "(", "'SignatureValue'", ",", "$", "signatureValue", ")", ";", "//adiciona o node <SignatureValue> ao node <Signature>", "$", "signatureNode", "->", "appendChild", "(", "$", "signatureValueNode", ")", ";", "//cria o node <KeyInfo>", "$", "keyInfoNode", "=", "$", "xmldoc", "->", "createElement", "(", "'KeyInfo'", ")", ";", "//adiciona o node <KeyInfo> ao node <Signature>", "$", "signatureNode", "->", "appendChild", "(", "$", "keyInfoNode", ")", ";", "//cria o node <X509Data>", "$", "x509DataNode", "=", "$", "xmldoc", "->", "createElement", "(", "'X509Data'", ")", ";", "//adiciona o node <X509Data> ao node <KeyInfo>", "$", "keyInfoNode", "->", "appendChild", "(", "$", "x509DataNode", ")", ";", "//remove linhas desnecessárias do certificado", "$", "pubKeyClean", "=", "$", "this", "->", "zCleanPubKey", "(", ")", ";", "//cria o node <X509Certificate>", "$", "x509CertificateNode", "=", "$", "xmldoc", "->", "createElement", "(", "'X509Certificate'", ",", "$", "pubKeyClean", ")", ";", "//adiciona o node <X509Certificate> ao node <X509Data>", "$", "x509DataNode", "->", "appendChild", "(", "$", "x509CertificateNode", ")", ";", "//salva o xml completo em uma string", "$", "xmlResp", "=", "$", "xmldoc", "->", "saveXML", "(", ")", ";", "//retorna o documento assinado", "return", "$", "xmlResp", ";", "}" ]
zSignXML Método que provê a assinatura do xml conforme padrão SEFAZ. @param resource $objSSLPriKey @return string xml assinado
[ "zSignXML", "Método", "que", "provê", "a", "assinatura", "do", "xml", "conforme", "padrão", "SEFAZ", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L398-L503
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zSignatureExists
private function zSignatureExists($dom) { $signature = $dom->getElementsByTagName('Signature')->item(0); if (! isset($signature)) { return false; } return true; }
php
private function zSignatureExists($dom) { $signature = $dom->getElementsByTagName('Signature')->item(0); if (! isset($signature)) { return false; } return true; }
[ "private", "function", "zSignatureExists", "(", "$", "dom", ")", "{", "$", "signature", "=", "$", "dom", "->", "getElementsByTagName", "(", "'Signature'", ")", "->", "item", "(", "0", ")", ";", "if", "(", "!", "isset", "(", "$", "signature", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
signatureExists Check se o xml possi a tag Signature. @param DOMDocument $dom @return bool
[ "signatureExists", "Check", "se", "o", "xml", "possi", "a", "tag", "Signature", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L511-L519
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.verifySignature
public function verifySignature($docxml = '', $tagid = '') { if ($docxml == '') { $msg = 'Não foi passado um xml para a verificação.'; throw new Exception($msg); } if ($tagid == '') { $msg = 'Não foi indicada a TAG a ser verificada.'; throw new Exception($msg); } $xml = $docxml; if (is_file($docxml)) { $xml = file_get_contents($docxml); } $dom = new Dom(); $dom->loadXMLString($xml); $flag = $this->zDigCheck($dom, $tagid); $flag = $this->zSignCheck($dom); return $flag; }
php
public function verifySignature($docxml = '', $tagid = '') { if ($docxml == '') { $msg = 'Não foi passado um xml para a verificação.'; throw new Exception($msg); } if ($tagid == '') { $msg = 'Não foi indicada a TAG a ser verificada.'; throw new Exception($msg); } $xml = $docxml; if (is_file($docxml)) { $xml = file_get_contents($docxml); } $dom = new Dom(); $dom->loadXMLString($xml); $flag = $this->zDigCheck($dom, $tagid); $flag = $this->zSignCheck($dom); return $flag; }
[ "public", "function", "verifySignature", "(", "$", "docxml", "=", "''", ",", "$", "tagid", "=", "''", ")", "{", "if", "(", "$", "docxml", "==", "''", ")", "{", "$", "msg", "=", "'Não foi passado um xml para a verificação.';", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "if", "(", "$", "tagid", "==", "''", ")", "{", "$", "msg", "=", "'Não foi indicada a TAG a ser verificada.';", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "$", "xml", "=", "$", "docxml", ";", "if", "(", "is_file", "(", "$", "docxml", ")", ")", "{", "$", "xml", "=", "file_get_contents", "(", "$", "docxml", ")", ";", "}", "$", "dom", "=", "new", "Dom", "(", ")", ";", "$", "dom", "->", "loadXMLString", "(", "$", "xml", ")", ";", "$", "flag", "=", "$", "this", "->", "zDigCheck", "(", "$", "dom", ",", "$", "tagid", ")", ";", "$", "flag", "=", "$", "this", "->", "zSignCheck", "(", "$", "dom", ")", ";", "return", "$", "flag", ";", "}" ]
verifySignature Verifica a validade da assinatura digital contida no xml. @param string $docxml conteudo do xml a ser verificado ou o path completo @param string $tagid tag que foi assinada no documento xml @return bool @throws Exception @throws Exception
[ "verifySignature", "Verifica", "a", "validade", "da", "assinatura", "digital", "contida", "no", "xml", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L530-L550
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zSignCheck
private function zSignCheck($dom) { // Obter e remontar a chave publica do xml $x509Certificate = $dom->getNodeValue('X509Certificate'); $x509Certificate = "-----BEGIN CERTIFICATE-----\n" . $this->zSplitLines($x509Certificate) . "\n-----END CERTIFICATE-----\n"; //carregar a chave publica remontada $objSSLPubKey = openssl_pkey_get_public($x509Certificate); if ($objSSLPubKey === false) { $msg = 'Ocorreram problemas ao carregar a chave pública. Certificado incorreto ou corrompido!!'; $this->zGetOpenSSLError($msg); //while ($erro = openssl_error_string()) { // $msg .= $erro . "\n"; //} //throw new Exception($msg); } //remontando conteudo que foi assinado $signContent = $dom->getElementsByTagName('SignedInfo')->item(0)->C14N(true, false, null, null); // validando assinatura do conteudo $signatureValueXML = $dom->getElementsByTagName('SignatureValue')->item(0)->nodeValue; $decodedSignature = base64_decode(str_replace(["\r", "\n"], '', $signatureValueXML)); $resp = openssl_verify($signContent, $decodedSignature, $objSSLPubKey); if ($resp != 1) { $msg = "Problema ({$resp}) ao verificar a assinatura do digital!!"; $this->zGetOpenSSLError($msg); } return true; }
php
private function zSignCheck($dom) { // Obter e remontar a chave publica do xml $x509Certificate = $dom->getNodeValue('X509Certificate'); $x509Certificate = "-----BEGIN CERTIFICATE-----\n" . $this->zSplitLines($x509Certificate) . "\n-----END CERTIFICATE-----\n"; //carregar a chave publica remontada $objSSLPubKey = openssl_pkey_get_public($x509Certificate); if ($objSSLPubKey === false) { $msg = 'Ocorreram problemas ao carregar a chave pública. Certificado incorreto ou corrompido!!'; $this->zGetOpenSSLError($msg); //while ($erro = openssl_error_string()) { // $msg .= $erro . "\n"; //} //throw new Exception($msg); } //remontando conteudo que foi assinado $signContent = $dom->getElementsByTagName('SignedInfo')->item(0)->C14N(true, false, null, null); // validando assinatura do conteudo $signatureValueXML = $dom->getElementsByTagName('SignatureValue')->item(0)->nodeValue; $decodedSignature = base64_decode(str_replace(["\r", "\n"], '', $signatureValueXML)); $resp = openssl_verify($signContent, $decodedSignature, $objSSLPubKey); if ($resp != 1) { $msg = "Problema ({$resp}) ao verificar a assinatura do digital!!"; $this->zGetOpenSSLError($msg); } return true; }
[ "private", "function", "zSignCheck", "(", "$", "dom", ")", "{", "// Obter e remontar a chave publica do xml", "$", "x509Certificate", "=", "$", "dom", "->", "getNodeValue", "(", "'X509Certificate'", ")", ";", "$", "x509Certificate", "=", "\"-----BEGIN CERTIFICATE-----\\n\"", ".", "$", "this", "->", "zSplitLines", "(", "$", "x509Certificate", ")", ".", "\"\\n-----END CERTIFICATE-----\\n\"", ";", "//carregar a chave publica remontada", "$", "objSSLPubKey", "=", "openssl_pkey_get_public", "(", "$", "x509Certificate", ")", ";", "if", "(", "$", "objSSLPubKey", "===", "false", ")", "{", "$", "msg", "=", "'Ocorreram problemas ao carregar a chave pública. Certificado incorreto ou corrompido!!';", "", "$", "this", "->", "zGetOpenSSLError", "(", "$", "msg", ")", ";", "//while ($erro = openssl_error_string()) {", "// $msg .= $erro . \"\\n\";", "//}", "//throw new Exception($msg);", "}", "//remontando conteudo que foi assinado", "$", "signContent", "=", "$", "dom", "->", "getElementsByTagName", "(", "'SignedInfo'", ")", "->", "item", "(", "0", ")", "->", "C14N", "(", "true", ",", "false", ",", "null", ",", "null", ")", ";", "// validando assinatura do conteudo", "$", "signatureValueXML", "=", "$", "dom", "->", "getElementsByTagName", "(", "'SignatureValue'", ")", "->", "item", "(", "0", ")", "->", "nodeValue", ";", "$", "decodedSignature", "=", "base64_decode", "(", "str_replace", "(", "[", "\"\\r\"", ",", "\"\\n\"", "]", ",", "''", ",", "$", "signatureValueXML", ")", ")", ";", "$", "resp", "=", "openssl_verify", "(", "$", "signContent", ",", "$", "decodedSignature", ",", "$", "objSSLPubKey", ")", ";", "if", "(", "$", "resp", "!=", "1", ")", "{", "$", "msg", "=", "\"Problema ({$resp}) ao verificar a assinatura do digital!!\"", ";", "$", "this", "->", "zGetOpenSSLError", "(", "$", "msg", ")", ";", "}", "return", "true", ";", "}" ]
zSignCheck. @param DOMDocument $dom @return bool @throws Exception
[ "zSignCheck", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L558-L587
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zDigCheck
private function zDigCheck($dom, $tagid = '') { $node = $dom->getNode($tagid, 0); if (empty($node)) { throw new Exception( "A tag < $tagid > não existe no XML!!" ); } if (! $this->zSignatureExists($dom)) { $msg = 'O xml não contêm nenhuma assinatura para ser verificada.'; throw new Exception($msg); } //carregar o node em sua forma canonica $tagInf = $node->C14N(true, false, null, null); //calcular o hash sha1 $hashValue = hash('sha1', $tagInf, true); //converter o hash para base64 para obter o digest do node $digestCalculado = base64_encode($hashValue); //pegar o digest informado no xml $digestInformado = $dom->getNodeValue('DigestValue'); //compara os digests calculados e informados if ($digestCalculado != $digestInformado) { $msg = "O conteúdo do XML não confere com o Digest Value.\n Digest calculado [{$digestCalculado}], digest informado no XML [{$digestInformado}].\n O arquivo pode estar corrompido ou ter sido adulterado."; throw new Exception($msg); } return true; }
php
private function zDigCheck($dom, $tagid = '') { $node = $dom->getNode($tagid, 0); if (empty($node)) { throw new Exception( "A tag < $tagid > não existe no XML!!" ); } if (! $this->zSignatureExists($dom)) { $msg = 'O xml não contêm nenhuma assinatura para ser verificada.'; throw new Exception($msg); } //carregar o node em sua forma canonica $tagInf = $node->C14N(true, false, null, null); //calcular o hash sha1 $hashValue = hash('sha1', $tagInf, true); //converter o hash para base64 para obter o digest do node $digestCalculado = base64_encode($hashValue); //pegar o digest informado no xml $digestInformado = $dom->getNodeValue('DigestValue'); //compara os digests calculados e informados if ($digestCalculado != $digestInformado) { $msg = "O conteúdo do XML não confere com o Digest Value.\n Digest calculado [{$digestCalculado}], digest informado no XML [{$digestInformado}].\n O arquivo pode estar corrompido ou ter sido adulterado."; throw new Exception($msg); } return true; }
[ "private", "function", "zDigCheck", "(", "$", "dom", ",", "$", "tagid", "=", "''", ")", "{", "$", "node", "=", "$", "dom", "->", "getNode", "(", "$", "tagid", ",", "0", ")", ";", "if", "(", "empty", "(", "$", "node", ")", ")", "{", "throw", "new", "Exception", "(", "\"A tag < $tagid > não existe no XML!!\"", ")", ";", "}", "if", "(", "!", "$", "this", "->", "zSignatureExists", "(", "$", "dom", ")", ")", "{", "$", "msg", "=", "'O xml não contêm nenhuma assinatura para ser verificada.';", "", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "//carregar o node em sua forma canonica", "$", "tagInf", "=", "$", "node", "->", "C14N", "(", "true", ",", "false", ",", "null", ",", "null", ")", ";", "//calcular o hash sha1", "$", "hashValue", "=", "hash", "(", "'sha1'", ",", "$", "tagInf", ",", "true", ")", ";", "//converter o hash para base64 para obter o digest do node", "$", "digestCalculado", "=", "base64_encode", "(", "$", "hashValue", ")", ";", "//pegar o digest informado no xml", "$", "digestInformado", "=", "$", "dom", "->", "getNodeValue", "(", "'DigestValue'", ")", ";", "//compara os digests calculados e informados", "if", "(", "$", "digestCalculado", "!=", "$", "digestInformado", ")", "{", "$", "msg", "=", "\"O conteúdo do XML não confere com o Digest Value.\\n\n Digest calculado [{$digestCalculado}], digest informado no XML [{$digestInformado}].\\n\n O arquivo pode estar corrompido ou ter sido adulterado.\"", ";", "throw", "new", "Exception", "(", "$", "msg", ")", ";", "}", "return", "true", ";", "}" ]
zDigCheck. @param DOMDocument $dom @param string $tagid @return bool @throws Exception
[ "zDigCheck", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L596-L625
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zValidCerts
protected function zValidCerts($pubKey) { if (! $data = openssl_x509_read($pubKey)) { //o dado não é uma chave válida $this->zRemovePemFiles(); $this->zLeaveParam(); $this->error = 'A chave passada está corrompida ou não é uma chave. Obtenha s chaves corretas!!'; return false; } $certData = openssl_x509_parse($data); // reformata a data de validade; $ano = substr($certData['validTo'], 0, 2); $mes = substr($certData['validTo'], 2, 2); $dia = substr($certData['validTo'], 4, 2); //obtem o timestamp da data de validade do certificado $dValid = gmmktime(0, 0, 0, $mes, $dia, $ano); // obtem o timestamp da data de hoje $dHoje = gmmktime(0, 0, 0, date('m'), date('d'), date('Y')); // compara a data de validade com a data atual $this->expireTimestamp = $dValid; if ($dHoje > $dValid) { $this->zRemovePemFiles(); $this->zLeaveParam(); $msg = "Data de validade vencida! [Valido até $dia/$mes/$ano]"; $this->error = $msg; return false; } return true; }
php
protected function zValidCerts($pubKey) { if (! $data = openssl_x509_read($pubKey)) { //o dado não é uma chave válida $this->zRemovePemFiles(); $this->zLeaveParam(); $this->error = 'A chave passada está corrompida ou não é uma chave. Obtenha s chaves corretas!!'; return false; } $certData = openssl_x509_parse($data); // reformata a data de validade; $ano = substr($certData['validTo'], 0, 2); $mes = substr($certData['validTo'], 2, 2); $dia = substr($certData['validTo'], 4, 2); //obtem o timestamp da data de validade do certificado $dValid = gmmktime(0, 0, 0, $mes, $dia, $ano); // obtem o timestamp da data de hoje $dHoje = gmmktime(0, 0, 0, date('m'), date('d'), date('Y')); // compara a data de validade com a data atual $this->expireTimestamp = $dValid; if ($dHoje > $dValid) { $this->zRemovePemFiles(); $this->zLeaveParam(); $msg = "Data de validade vencida! [Valido até $dia/$mes/$ano]"; $this->error = $msg; return false; } return true; }
[ "protected", "function", "zValidCerts", "(", "$", "pubKey", ")", "{", "if", "(", "!", "$", "data", "=", "openssl_x509_read", "(", "$", "pubKey", ")", ")", "{", "//o dado não é uma chave válida", "$", "this", "->", "zRemovePemFiles", "(", ")", ";", "$", "this", "->", "zLeaveParam", "(", ")", ";", "$", "this", "->", "error", "=", "'A chave passada está corrompida ou não é uma chave. Obtenha s chaves corretas!!';", "", "return", "false", ";", "}", "$", "certData", "=", "openssl_x509_parse", "(", "$", "data", ")", ";", "// reformata a data de validade;", "$", "ano", "=", "substr", "(", "$", "certData", "[", "'validTo'", "]", ",", "0", ",", "2", ")", ";", "$", "mes", "=", "substr", "(", "$", "certData", "[", "'validTo'", "]", ",", "2", ",", "2", ")", ";", "$", "dia", "=", "substr", "(", "$", "certData", "[", "'validTo'", "]", ",", "4", ",", "2", ")", ";", "//obtem o timestamp da data de validade do certificado", "$", "dValid", "=", "gmmktime", "(", "0", ",", "0", ",", "0", ",", "$", "mes", ",", "$", "dia", ",", "$", "ano", ")", ";", "// obtem o timestamp da data de hoje", "$", "dHoje", "=", "gmmktime", "(", "0", ",", "0", ",", "0", ",", "date", "(", "'m'", ")", ",", "date", "(", "'d'", ")", ",", "date", "(", "'Y'", ")", ")", ";", "// compara a data de validade com a data atual", "$", "this", "->", "expireTimestamp", "=", "$", "dValid", ";", "if", "(", "$", "dHoje", ">", "$", "dValid", ")", "{", "$", "this", "->", "zRemovePemFiles", "(", ")", ";", "$", "this", "->", "zLeaveParam", "(", ")", ";", "$", "msg", "=", "\"Data de validade vencida! [Valido até $dia/$mes/$ano]\";", "", "$", "this", "->", "error", "=", "$", "msg", ";", "return", "false", ";", "}", "return", "true", ";", "}" ]
zValidCerts Verifica a data de validade do certificado digital e compara com a data de hoje. Caso o certificado tenha expirado o mesmo será removido das pastas e o método irá retornar false. @param string $pubKey chave publica @return bool
[ "zValidCerts", "Verifica", "a", "data", "de", "validade", "do", "certificado", "digital", "e", "compara", "com", "a", "data", "de", "hoje", ".", "Caso", "o", "certificado", "tenha", "expirado", "o", "mesmo", "será", "removido", "das", "pastas", "e", "o", "método", "irá", "retornar", "false", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L636-L667
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zCleanPubKey
protected function zCleanPubKey() { //inicializa variavel $data = ''; //carregar a chave publica $pubKey = $this->pubKey; //carrega o certificado em um array usando o LF como referencia $arCert = explode("\n", $pubKey); foreach ($arCert as $curData) { //remove a tag de inicio e fim do certificado if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) != 0 && strncmp($curData, '-----END CERTIFICATE', 20) != 0) { //carrega o resultado numa string $data .= trim($curData); } } return $data; }
php
protected function zCleanPubKey() { //inicializa variavel $data = ''; //carregar a chave publica $pubKey = $this->pubKey; //carrega o certificado em um array usando o LF como referencia $arCert = explode("\n", $pubKey); foreach ($arCert as $curData) { //remove a tag de inicio e fim do certificado if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) != 0 && strncmp($curData, '-----END CERTIFICATE', 20) != 0) { //carrega o resultado numa string $data .= trim($curData); } } return $data; }
[ "protected", "function", "zCleanPubKey", "(", ")", "{", "//inicializa variavel", "$", "data", "=", "''", ";", "//carregar a chave publica", "$", "pubKey", "=", "$", "this", "->", "pubKey", ";", "//carrega o certificado em um array usando o LF como referencia", "$", "arCert", "=", "explode", "(", "\"\\n\"", ",", "$", "pubKey", ")", ";", "foreach", "(", "$", "arCert", "as", "$", "curData", ")", "{", "//remove a tag de inicio e fim do certificado", "if", "(", "strncmp", "(", "$", "curData", ",", "'-----BEGIN CERTIFICATE'", ",", "22", ")", "!=", "0", "&&", "strncmp", "(", "$", "curData", ",", "'-----END CERTIFICATE'", ",", "20", ")", "!=", "0", ")", "{", "//carrega o resultado numa string", "$", "data", ".=", "trim", "(", "$", "curData", ")", ";", "}", "}", "return", "$", "data", ";", "}" ]
zCleanPubKey Remove a informação de inicio e fim do certificado contido no formato PEM, deixando o certificado (chave publica) pronta para ser anexada ao xml da NFe. @return string contendo o certificado limpo
[ "zCleanPubKey", "Remove", "a", "informação", "de", "inicio", "e", "fim", "do", "certificado", "contido", "no", "formato", "PEM", "deixando", "o", "certificado", "(", "chave", "publica", ")", "pronta", "para", "ser", "anexada", "ao", "xml", "da", "NFe", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L676-L694
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zSplitLines
protected function zSplitLines($cntIn = '') { if ($cntIn != '') { $cnt = rtrim(chunk_split(str_replace(["\r", "\n"], '', $cntIn), 76, "\n")); } else { $cnt = $cntIn; } return $cnt; }
php
protected function zSplitLines($cntIn = '') { if ($cntIn != '') { $cnt = rtrim(chunk_split(str_replace(["\r", "\n"], '', $cntIn), 76, "\n")); } else { $cnt = $cntIn; } return $cnt; }
[ "protected", "function", "zSplitLines", "(", "$", "cntIn", "=", "''", ")", "{", "if", "(", "$", "cntIn", "!=", "''", ")", "{", "$", "cnt", "=", "rtrim", "(", "chunk_split", "(", "str_replace", "(", "[", "\"\\r\"", ",", "\"\\n\"", "]", ",", "''", ",", "$", "cntIn", ")", ",", "76", ",", "\"\\n\"", ")", ")", ";", "}", "else", "{", "$", "cnt", "=", "$", "cntIn", ";", "}", "return", "$", "cnt", ";", "}" ]
zSplitLines Divide a string do certificado publico em linhas com 76 caracteres (padrão original). @param string $cntIn certificado @return string certificado reformatado
[ "zSplitLines", "Divide", "a", "string", "do", "certificado", "publico", "em", "linhas", "com", "76", "caracteres", "(", "padrão", "original", ")", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L703-L712
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zRemovePemFiles
private function zRemovePemFiles() { if (is_file($this->pubKeyFile)) { unlink($this->pubKeyFile); } if (is_file($this->priKeyFile)) { unlink($this->priKeyFile); } if (is_file($this->certKeyFile)) { unlink($this->certKeyFile); } }
php
private function zRemovePemFiles() { if (is_file($this->pubKeyFile)) { unlink($this->pubKeyFile); } if (is_file($this->priKeyFile)) { unlink($this->priKeyFile); } if (is_file($this->certKeyFile)) { unlink($this->certKeyFile); } }
[ "private", "function", "zRemovePemFiles", "(", ")", "{", "if", "(", "is_file", "(", "$", "this", "->", "pubKeyFile", ")", ")", "{", "unlink", "(", "$", "this", "->", "pubKeyFile", ")", ";", "}", "if", "(", "is_file", "(", "$", "this", "->", "priKeyFile", ")", ")", "{", "unlink", "(", "$", "this", "->", "priKeyFile", ")", ";", "}", "if", "(", "is_file", "(", "$", "this", "->", "certKeyFile", ")", ")", "{", "unlink", "(", "$", "this", "->", "certKeyFile", ")", ";", "}", "}" ]
zRemovePemFiles Apaga os arquivos PEM do diretório Isso deve ser feito quando um novo certificado é carregado ou quando a validade do certificado expirou.
[ "zRemovePemFiles", "Apaga", "os", "arquivos", "PEM", "do", "diretório", "Isso", "deve", "ser", "feito", "quando", "um", "novo", "certificado", "é", "carregado", "ou", "quando", "a", "validade", "do", "certificado", "expirou", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L720-L731
phpnfe/tools
src/Certificado/Pkcs12.php
Pkcs12.zLeaveParam
private function zLeaveParam() { $this->pfxCert = ''; $this->pubKey = ''; $this->priKey = ''; $this->certKey = ''; $this->pubKeyFile = ''; $this->priKeyFile = ''; $this->certKeyFile = ''; $this->expireTimestamp = ''; }
php
private function zLeaveParam() { $this->pfxCert = ''; $this->pubKey = ''; $this->priKey = ''; $this->certKey = ''; $this->pubKeyFile = ''; $this->priKeyFile = ''; $this->certKeyFile = ''; $this->expireTimestamp = ''; }
[ "private", "function", "zLeaveParam", "(", ")", "{", "$", "this", "->", "pfxCert", "=", "''", ";", "$", "this", "->", "pubKey", "=", "''", ";", "$", "this", "->", "priKey", "=", "''", ";", "$", "this", "->", "certKey", "=", "''", ";", "$", "this", "->", "pubKeyFile", "=", "''", ";", "$", "this", "->", "priKeyFile", "=", "''", ";", "$", "this", "->", "certKeyFile", "=", "''", ";", "$", "this", "->", "expireTimestamp", "=", "''", ";", "}" ]
zLeaveParam Limpa os parametros da classe.
[ "zLeaveParam", "Limpa", "os", "parametros", "da", "classe", "." ]
train
https://github.com/phpnfe/tools/blob/303ca311989e0b345071f61b71d2b3bf7ee80454/src/Certificado/Pkcs12.php#L737-L747
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/DescriptorAbstract.php
DescriptorAbstract.getSummary
public function getSummary() { if ($this->summary && strtolower(trim($this->summary)) != '{@inheritdoc}') { return $this->summary; } $parent = $this->getInheritedElement(); if ($parent instanceof DescriptorAbstract) { return $parent->getSummary(); } return $this->summary; }
php
public function getSummary() { if ($this->summary && strtolower(trim($this->summary)) != '{@inheritdoc}') { return $this->summary; } $parent = $this->getInheritedElement(); if ($parent instanceof DescriptorAbstract) { return $parent->getSummary(); } return $this->summary; }
[ "public", "function", "getSummary", "(", ")", "{", "if", "(", "$", "this", "->", "summary", "&&", "strtolower", "(", "trim", "(", "$", "this", "->", "summary", ")", ")", "!=", "'{@inheritdoc}'", ")", "{", "return", "$", "this", "->", "summary", ";", "}", "$", "parent", "=", "$", "this", "->", "getInheritedElement", "(", ")", ";", "if", "(", "$", "parent", "instanceof", "DescriptorAbstract", ")", "{", "return", "$", "parent", "->", "getSummary", "(", ")", ";", "}", "return", "$", "this", "->", "summary", ";", "}" ]
Returns the summary which describes this element. This method will automatically attempt to inherit the parent's summary if this one has none. @return string
[ "Returns", "the", "summary", "which", "describes", "this", "element", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L148-L160
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/DescriptorAbstract.php
DescriptorAbstract.getDescription
public function getDescription() { if ($this->description && strpos(strtolower($this->description), '{@inheritdoc}') === false) { return $this->description; } $parentElement = $this->getInheritedElement(); if ($parentElement instanceof DescriptorAbstract) { $parentDescription = $parentElement->getDescription(); return $this->description ? str_ireplace('{@inheritdoc}', $parentDescription, $this->description) : $parentDescription; } return $this->description; }
php
public function getDescription() { if ($this->description && strpos(strtolower($this->description), '{@inheritdoc}') === false) { return $this->description; } $parentElement = $this->getInheritedElement(); if ($parentElement instanceof DescriptorAbstract) { $parentDescription = $parentElement->getDescription(); return $this->description ? str_ireplace('{@inheritdoc}', $parentDescription, $this->description) : $parentDescription; } return $this->description; }
[ "public", "function", "getDescription", "(", ")", "{", "if", "(", "$", "this", "->", "description", "&&", "strpos", "(", "strtolower", "(", "$", "this", "->", "description", ")", ",", "'{@inheritdoc}'", ")", "===", "false", ")", "{", "return", "$", "this", "->", "description", ";", "}", "$", "parentElement", "=", "$", "this", "->", "getInheritedElement", "(", ")", ";", "if", "(", "$", "parentElement", "instanceof", "DescriptorAbstract", ")", "{", "$", "parentDescription", "=", "$", "parentElement", "->", "getDescription", "(", ")", ";", "return", "$", "this", "->", "description", "?", "str_ireplace", "(", "'{@inheritdoc}'", ",", "$", "parentDescription", ",", "$", "this", "->", "description", ")", ":", "$", "parentDescription", ";", "}", "return", "$", "this", "->", "description", ";", "}" ]
Returns the description for this element. This method will automatically attempt to inherit the parent's description if this one has none. @return string
[ "Returns", "the", "description", "for", "this", "element", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L181-L197
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/DescriptorAbstract.php
DescriptorAbstract.getPackage
public function getPackage() { $inheritedElement = $this->getInheritedElement(); if ($this->package instanceof PackageDescriptor && ! ($this->package->getName() === '\\' && $inheritedElement)) { return $this->package; } if ($inheritedElement instanceof DescriptorAbstract) { return $inheritedElement->getPackage(); } return null; }
php
public function getPackage() { $inheritedElement = $this->getInheritedElement(); if ($this->package instanceof PackageDescriptor && ! ($this->package->getName() === '\\' && $inheritedElement)) { return $this->package; } if ($inheritedElement instanceof DescriptorAbstract) { return $inheritedElement->getPackage(); } return null; }
[ "public", "function", "getPackage", "(", ")", "{", "$", "inheritedElement", "=", "$", "this", "->", "getInheritedElement", "(", ")", ";", "if", "(", "$", "this", "->", "package", "instanceof", "PackageDescriptor", "&&", "!", "(", "$", "this", "->", "package", "->", "getName", "(", ")", "===", "'\\\\'", "&&", "$", "inheritedElement", ")", ")", "{", "return", "$", "this", "->", "package", ";", "}", "if", "(", "$", "inheritedElement", "instanceof", "DescriptorAbstract", ")", "{", "return", "$", "inheritedElement", "->", "getPackage", "(", ")", ";", "}", "return", "null", ";", "}" ]
Returns the package name for this element. @return PackageDescriptor
[ "Returns", "the", "package", "name", "for", "this", "element", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/DescriptorAbstract.php#L306-L319
wenbinye/PhalconX
src/Php/NodeVisitor.php
NodeVisitor.buildMethods
protected function buildMethods() { $refl = new \ReflectionClass($this); $enterMethods = []; $leaveMethods = []; foreach ($refl->getMethods() as $method) { $name = $method->getName(); if (preg_match('/^(enter|leave).+/', $name) && !preg_match('/^(enter|leave)Node$/', $name)) { $params = $method->getParameters(); if ($params && $params[0]->getClass()) { $nodeType = $params[0]->getClass()->getName(); if (Text::startsWith($name, 'enter')) { $enterMethods[$nodeType][] = $name; } else { $leaveMethods[$nodeType][] = $name; } } } } self::$enterMethods[get_class($this)] = $enterMethods; self::$leaveMethods[get_class($this)] = $leaveMethods; }
php
protected function buildMethods() { $refl = new \ReflectionClass($this); $enterMethods = []; $leaveMethods = []; foreach ($refl->getMethods() as $method) { $name = $method->getName(); if (preg_match('/^(enter|leave).+/', $name) && !preg_match('/^(enter|leave)Node$/', $name)) { $params = $method->getParameters(); if ($params && $params[0]->getClass()) { $nodeType = $params[0]->getClass()->getName(); if (Text::startsWith($name, 'enter')) { $enterMethods[$nodeType][] = $name; } else { $leaveMethods[$nodeType][] = $name; } } } } self::$enterMethods[get_class($this)] = $enterMethods; self::$leaveMethods[get_class($this)] = $leaveMethods; }
[ "protected", "function", "buildMethods", "(", ")", "{", "$", "refl", "=", "new", "\\", "ReflectionClass", "(", "$", "this", ")", ";", "$", "enterMethods", "=", "[", "]", ";", "$", "leaveMethods", "=", "[", "]", ";", "foreach", "(", "$", "refl", "->", "getMethods", "(", ")", "as", "$", "method", ")", "{", "$", "name", "=", "$", "method", "->", "getName", "(", ")", ";", "if", "(", "preg_match", "(", "'/^(enter|leave).+/'", ",", "$", "name", ")", "&&", "!", "preg_match", "(", "'/^(enter|leave)Node$/'", ",", "$", "name", ")", ")", "{", "$", "params", "=", "$", "method", "->", "getParameters", "(", ")", ";", "if", "(", "$", "params", "&&", "$", "params", "[", "0", "]", "->", "getClass", "(", ")", ")", "{", "$", "nodeType", "=", "$", "params", "[", "0", "]", "->", "getClass", "(", ")", "->", "getName", "(", ")", ";", "if", "(", "Text", "::", "startsWith", "(", "$", "name", ",", "'enter'", ")", ")", "{", "$", "enterMethods", "[", "$", "nodeType", "]", "[", "]", "=", "$", "name", ";", "}", "else", "{", "$", "leaveMethods", "[", "$", "nodeType", "]", "[", "]", "=", "$", "name", ";", "}", "}", "}", "}", "self", "::", "$", "enterMethods", "[", "get_class", "(", "$", "this", ")", "]", "=", "$", "enterMethods", ";", "self", "::", "$", "leaveMethods", "[", "get_class", "(", "$", "this", ")", "]", "=", "$", "leaveMethods", ";", "}" ]
collect all rule method according to node type of parameter
[ "collect", "all", "rule", "method", "according", "to", "node", "type", "of", "parameter" ]
train
https://github.com/wenbinye/PhalconX/blob/0d2e1480e722dde56ccd23b2e8a5c8ac6ac2f8e1/src/Php/NodeVisitor.php#L57-L79
dave-redfern/somnambulist-value-objects
src/AbstractValueObject.php
AbstractValueObject.equals
public function equals($object): bool { if (get_class($this) === get_class($object)) { $props = Collection::collect((new \ReflectionObject($this))->getProperties()); return $props ->filter(function ($prop) use ($object) { /** @var \ReflectionProperty $prop */ $prop->setAccessible(true); return (string)$prop->getValue($object) === (string)$prop->getValue($this); }) ->count() === $props->count() ; } return false; }
php
public function equals($object): bool { if (get_class($this) === get_class($object)) { $props = Collection::collect((new \ReflectionObject($this))->getProperties()); return $props ->filter(function ($prop) use ($object) { /** @var \ReflectionProperty $prop */ $prop->setAccessible(true); return (string)$prop->getValue($object) === (string)$prop->getValue($this); }) ->count() === $props->count() ; } return false; }
[ "public", "function", "equals", "(", "$", "object", ")", ":", "bool", "{", "if", "(", "get_class", "(", "$", "this", ")", "===", "get_class", "(", "$", "object", ")", ")", "{", "$", "props", "=", "Collection", "::", "collect", "(", "(", "new", "\\", "ReflectionObject", "(", "$", "this", ")", ")", "->", "getProperties", "(", ")", ")", ";", "return", "$", "props", "->", "filter", "(", "function", "(", "$", "prop", ")", "use", "(", "$", "object", ")", "{", "/** @var \\ReflectionProperty $prop */", "$", "prop", "->", "setAccessible", "(", "true", ")", ";", "return", "(", "string", ")", "$", "prop", "->", "getValue", "(", "$", "object", ")", "===", "(", "string", ")", "$", "prop", "->", "getValue", "(", "$", "this", ")", ";", "}", ")", "->", "count", "(", ")", "===", "$", "props", "->", "count", "(", ")", ";", "}", "return", "false", ";", "}" ]
@param AbstractValueObject $object @return bool
[ "@param", "AbstractValueObject", "$object" ]
train
https://github.com/dave-redfern/somnambulist-value-objects/blob/dbae7fea7140b36e105ed3f5e21a42316ea3061f/src/AbstractValueObject.php#L55-L72
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/FunctionDescriptor.php
FunctionDescriptor.getResponse
public function getResponse() { /** @var Collection|null $returnTags */ $returnTags = $this->getTags()->get('return'); return $returnTags instanceof Collection ? current($returnTags->getAll()) : null; }
php
public function getResponse() { /** @var Collection|null $returnTags */ $returnTags = $this->getTags()->get('return'); return $returnTags instanceof Collection ? current($returnTags->getAll()) : null; }
[ "public", "function", "getResponse", "(", ")", "{", "/** @var Collection|null $returnTags */", "$", "returnTags", "=", "$", "this", "->", "getTags", "(", ")", "->", "get", "(", "'return'", ")", ";", "return", "$", "returnTags", "instanceof", "Collection", "?", "current", "(", "$", "returnTags", "->", "getAll", "(", ")", ")", ":", "null", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/FunctionDescriptor.php#L51-L57
trunda/SmfMenu
src/Smf/Menu/Renderer/BootstrapNavRenderer.php
BootstrapNavRenderer.setDefaults
protected function setDefaults(array $defaultOptions = array()) { $defaultOptions = array_merge(array( 'depth' => null, 'ancestorCurrencyDepth' => null, 'currentClass' => 'active', 'ancestorClass' => 'active', 'firstClass' => null, 'lastClass' => null ), $defaultOptions); parent::setDefaults($defaultOptions); }
php
protected function setDefaults(array $defaultOptions = array()) { $defaultOptions = array_merge(array( 'depth' => null, 'ancestorCurrencyDepth' => null, 'currentClass' => 'active', 'ancestorClass' => 'active', 'firstClass' => null, 'lastClass' => null ), $defaultOptions); parent::setDefaults($defaultOptions); }
[ "protected", "function", "setDefaults", "(", "array", "$", "defaultOptions", "=", "array", "(", ")", ")", "{", "$", "defaultOptions", "=", "array_merge", "(", "array", "(", "'depth'", "=>", "null", ",", "'ancestorCurrencyDepth'", "=>", "null", ",", "'currentClass'", "=>", "'active'", ",", "'ancestorClass'", "=>", "'active'", ",", "'firstClass'", "=>", "null", ",", "'lastClass'", "=>", "null", ")", ",", "$", "defaultOptions", ")", ";", "parent", "::", "setDefaults", "(", "$", "defaultOptions", ")", ";", "}" ]
Overwriting some options - classes, etc. @param array $defaultOptions
[ "Overwriting", "some", "options", "-", "classes", "etc", "." ]
train
https://github.com/trunda/SmfMenu/blob/739e74fb664c1f018b4a74142bd28d20c004bac6/src/Smf/Menu/Renderer/BootstrapNavRenderer.php#L19-L31
dragonmantank/fillet
src/Fillet/Writer/PostWriter.php
PostWriter.write
public function write($data) { $post_date_string = $data['post_date']->format('Y-m-d H:i:s'); $slug = $this->generateSlug($data['title']); $filename = $data['post_date']->format('Y-m-d') . '-' . $slug; $headerData = [ 'title' => $data['title'], 'date' => $post_date_string, 'layout' => 'post', 'slug' => $slug, 'categories' => $data['categories'], 'tags' => $data['tags'], ]; $dumper = new YamlDumper(); $header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL; $filename = $this->destinationFolder . $filename; if ($this->isMarkdownEnabled()) { $filename .= '.md'; $data['content'] = $this->toMarkdown($data['content']); } else { $filename .= '.html'; } file_put_contents($filename, $header . PHP_EOL . $data['content']); }
php
public function write($data) { $post_date_string = $data['post_date']->format('Y-m-d H:i:s'); $slug = $this->generateSlug($data['title']); $filename = $data['post_date']->format('Y-m-d') . '-' . $slug; $headerData = [ 'title' => $data['title'], 'date' => $post_date_string, 'layout' => 'post', 'slug' => $slug, 'categories' => $data['categories'], 'tags' => $data['tags'], ]; $dumper = new YamlDumper(); $header = '---' . PHP_EOL . $dumper->dump($headerData, 2) . '---' . PHP_EOL; $filename = $this->destinationFolder . $filename; if ($this->isMarkdownEnabled()) { $filename .= '.md'; $data['content'] = $this->toMarkdown($data['content']); } else { $filename .= '.html'; } file_put_contents($filename, $header . PHP_EOL . $data['content']); }
[ "public", "function", "write", "(", "$", "data", ")", "{", "$", "post_date_string", "=", "$", "data", "[", "'post_date'", "]", "->", "format", "(", "'Y-m-d H:i:s'", ")", ";", "$", "slug", "=", "$", "this", "->", "generateSlug", "(", "$", "data", "[", "'title'", "]", ")", ";", "$", "filename", "=", "$", "data", "[", "'post_date'", "]", "->", "format", "(", "'Y-m-d'", ")", ".", "'-'", ".", "$", "slug", ";", "$", "headerData", "=", "[", "'title'", "=>", "$", "data", "[", "'title'", "]", ",", "'date'", "=>", "$", "post_date_string", ",", "'layout'", "=>", "'post'", ",", "'slug'", "=>", "$", "slug", ",", "'categories'", "=>", "$", "data", "[", "'categories'", "]", ",", "'tags'", "=>", "$", "data", "[", "'tags'", "]", ",", "]", ";", "$", "dumper", "=", "new", "YamlDumper", "(", ")", ";", "$", "header", "=", "'---'", ".", "PHP_EOL", ".", "$", "dumper", "->", "dump", "(", "$", "headerData", ",", "2", ")", ".", "'---'", ".", "PHP_EOL", ";", "$", "filename", "=", "$", "this", "->", "destinationFolder", ".", "$", "filename", ";", "if", "(", "$", "this", "->", "isMarkdownEnabled", "(", ")", ")", "{", "$", "filename", ".=", "'.md'", ";", "$", "data", "[", "'content'", "]", "=", "$", "this", "->", "toMarkdown", "(", "$", "data", "[", "'content'", "]", ")", ";", "}", "else", "{", "$", "filename", ".=", "'.html'", ";", "}", "file_put_contents", "(", "$", "filename", ",", "$", "header", ".", "PHP_EOL", ".", "$", "data", "[", "'content'", "]", ")", ";", "}" ]
Write out a set of data into a file @param array $data Data to use for constructing the page
[ "Write", "out", "a", "set", "of", "data", "into", "a", "file" ]
train
https://github.com/dragonmantank/fillet/blob/b197947608c05ac2318e8f6b296345494004d9c6/src/Fillet/Writer/PostWriter.php#L19-L45
kuria/url
src/Url.php
Url.parse
static function parse(string $url, ?int $preferredFormat = self::ABSOLUTE) { $components = parse_url($url); if ($components === false) { throw new InvalidUrlException(sprintf('The given URL "%s" is invalid', $url)); } $query = []; if (isset($components['query'])) { parse_str($components['query'], $query); } return new static( $components['scheme'] ?? null, $components['host'] ?? null, $components['port'] ?? null, $components['path'] ?? '', $query, $components['fragment'] ?? null, $preferredFormat ); }
php
static function parse(string $url, ?int $preferredFormat = self::ABSOLUTE) { $components = parse_url($url); if ($components === false) { throw new InvalidUrlException(sprintf('The given URL "%s" is invalid', $url)); } $query = []; if (isset($components['query'])) { parse_str($components['query'], $query); } return new static( $components['scheme'] ?? null, $components['host'] ?? null, $components['port'] ?? null, $components['path'] ?? '', $query, $components['fragment'] ?? null, $preferredFormat ); }
[ "static", "function", "parse", "(", "string", "$", "url", ",", "?", "int", "$", "preferredFormat", "=", "self", "::", "ABSOLUTE", ")", "{", "$", "components", "=", "parse_url", "(", "$", "url", ")", ";", "if", "(", "$", "components", "===", "false", ")", "{", "throw", "new", "InvalidUrlException", "(", "sprintf", "(", "'The given URL \"%s\" is invalid'", ",", "$", "url", ")", ")", ";", "}", "$", "query", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "components", "[", "'query'", "]", ")", ")", "{", "parse_str", "(", "$", "components", "[", "'query'", "]", ",", "$", "query", ")", ";", "}", "return", "new", "static", "(", "$", "components", "[", "'scheme'", "]", "??", "null", ",", "$", "components", "[", "'host'", "]", "??", "null", ",", "$", "components", "[", "'port'", "]", "??", "null", ",", "$", "components", "[", "'path'", "]", "??", "''", ",", "$", "query", ",", "$", "components", "[", "'fragment'", "]", "??", "null", ",", "$", "preferredFormat", ")", ";", "}" ]
Parse an URL @throws InvalidUrlException if the URL is invalid @return static
[ "Parse", "an", "URL" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L63-L86
kuria/url
src/Url.php
Url.getFullHost
function getFullHost(): ?string { if ($this->host === null) { return null; } $fullHost = $this->host; if ($this->port !== null) { $fullHost .= ':' . $this->port; } return $fullHost; }
php
function getFullHost(): ?string { if ($this->host === null) { return null; } $fullHost = $this->host; if ($this->port !== null) { $fullHost .= ':' . $this->port; } return $fullHost; }
[ "function", "getFullHost", "(", ")", ":", "?", "string", "{", "if", "(", "$", "this", "->", "host", "===", "null", ")", "{", "return", "null", ";", "}", "$", "fullHost", "=", "$", "this", "->", "host", ";", "if", "(", "$", "this", "->", "port", "!==", "null", ")", "{", "$", "fullHost", ".=", "':'", ".", "$", "this", "->", "port", ";", "}", "return", "$", "fullHost", ";", "}" ]
Get host name, including the port, if defined E.g. example.com:8080
[ "Get", "host", "name", "including", "the", "port", "if", "defined" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L113-L126
kuria/url
src/Url.php
Url.add
function add(array $parameters): void { foreach ($parameters as $parameter => $value) { $this->query[$parameter] = $value; } }
php
function add(array $parameters): void { foreach ($parameters as $parameter => $value) { $this->query[$parameter] = $value; } }
[ "function", "add", "(", "array", "$", "parameters", ")", ":", "void", "{", "foreach", "(", "$", "parameters", "as", "$", "parameter", "=>", "$", "value", ")", "{", "$", "this", "->", "query", "[", "$", "parameter", "]", "=", "$", "value", ";", "}", "}" ]
Add multiple query parameters Already defined parameters with the same key will be overriden.
[ "Add", "multiple", "query", "parameters" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L258-L263
kuria/url
src/Url.php
Url.build
function build(): string { if ($this->host !== null && $this->preferredFormat === static::ABSOLUTE) { return $this->buildAbsolute(); } else { return $this->buildRelative(); } }
php
function build(): string { if ($this->host !== null && $this->preferredFormat === static::ABSOLUTE) { return $this->buildAbsolute(); } else { return $this->buildRelative(); } }
[ "function", "build", "(", ")", ":", "string", "{", "if", "(", "$", "this", "->", "host", "!==", "null", "&&", "$", "this", "->", "preferredFormat", "===", "static", "::", "ABSOLUTE", ")", "{", "return", "$", "this", "->", "buildAbsolute", "(", ")", ";", "}", "else", "{", "return", "$", "this", "->", "buildRelative", "(", ")", ";", "}", "}" ]
Build an absolute or relative URL - if no host is specified, a relative URL will be returned - if the host is specified, an absolute URL will be returned (unless the preferred format option is set to relative) @see Url::setPreferredFormat()
[ "Build", "an", "absolute", "or", "relative", "URL" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L292-L299
kuria/url
src/Url.php
Url.buildAbsolute
function buildAbsolute(): string { $output = ''; if ($this->host === null) { throw new IncompleteUrlException('No host specified'); } // scheme if ($this->scheme !== null) { $output .= $this->scheme; $output .= '://'; } else { // protocol-relative $output .= '//'; } // host, port $output .= $this->getFullHost(); // ensure a forward slash between host and a non-empty path if ($this->path !== '' && $this->path[0] !== '/') { $output .= '/'; } // path, query, fragment $output .= $this->buildRelative(); return $output; }
php
function buildAbsolute(): string { $output = ''; if ($this->host === null) { throw new IncompleteUrlException('No host specified'); } // scheme if ($this->scheme !== null) { $output .= $this->scheme; $output .= '://'; } else { // protocol-relative $output .= '//'; } // host, port $output .= $this->getFullHost(); // ensure a forward slash between host and a non-empty path if ($this->path !== '' && $this->path[0] !== '/') { $output .= '/'; } // path, query, fragment $output .= $this->buildRelative(); return $output; }
[ "function", "buildAbsolute", "(", ")", ":", "string", "{", "$", "output", "=", "''", ";", "if", "(", "$", "this", "->", "host", "===", "null", ")", "{", "throw", "new", "IncompleteUrlException", "(", "'No host specified'", ")", ";", "}", "// scheme", "if", "(", "$", "this", "->", "scheme", "!==", "null", ")", "{", "$", "output", ".=", "$", "this", "->", "scheme", ";", "$", "output", ".=", "'://'", ";", "}", "else", "{", "// protocol-relative", "$", "output", ".=", "'//'", ";", "}", "// host, port", "$", "output", ".=", "$", "this", "->", "getFullHost", "(", ")", ";", "// ensure a forward slash between host and a non-empty path", "if", "(", "$", "this", "->", "path", "!==", "''", "&&", "$", "this", "->", "path", "[", "0", "]", "!==", "'/'", ")", "{", "$", "output", ".=", "'/'", ";", "}", "// path, query, fragment", "$", "output", ".=", "$", "this", "->", "buildRelative", "(", ")", ";", "return", "$", "output", ";", "}" ]
Build an absolute URL @throws IncompleteUrlException if no host is specified
[ "Build", "an", "absolute", "URL" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L306-L335
kuria/url
src/Url.php
Url.buildRelative
function buildRelative(): string { $output = ''; // path $output .= $this->path; // query if ($this->query) { $output .= '?'; $output .= $this->getQueryString(); } // fragment if ($this->fragment !== null) { $output .= '#'; $output .= $this->fragment; } return $output; }
php
function buildRelative(): string { $output = ''; // path $output .= $this->path; // query if ($this->query) { $output .= '?'; $output .= $this->getQueryString(); } // fragment if ($this->fragment !== null) { $output .= '#'; $output .= $this->fragment; } return $output; }
[ "function", "buildRelative", "(", ")", ":", "string", "{", "$", "output", "=", "''", ";", "// path", "$", "output", ".=", "$", "this", "->", "path", ";", "// query", "if", "(", "$", "this", "->", "query", ")", "{", "$", "output", ".=", "'?'", ";", "$", "output", ".=", "$", "this", "->", "getQueryString", "(", ")", ";", "}", "// fragment", "if", "(", "$", "this", "->", "fragment", "!==", "null", ")", "{", "$", "output", ".=", "'#'", ";", "$", "output", ".=", "$", "this", "->", "fragment", ";", "}", "return", "$", "output", ";", "}" ]
Build a relative URL
[ "Build", "a", "relative", "URL" ]
train
https://github.com/kuria/url/blob/5f405abb9bd4b722a907363b3d7c43207365c411/src/Url.php#L340-L360
mmanos/laravel-casset
src/Mmanos/Casset/Casset.php
Casset.container
public function container($container = 'default') { if (!isset($this->containers[$container])) { $this->containers[$container] = new Container($container); } return $this->containers[$container]; }
php
public function container($container = 'default') { if (!isset($this->containers[$container])) { $this->containers[$container] = new Container($container); } return $this->containers[$container]; }
[ "public", "function", "container", "(", "$", "container", "=", "'default'", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "containers", "[", "$", "container", "]", ")", ")", "{", "$", "this", "->", "containers", "[", "$", "container", "]", "=", "new", "Container", "(", "$", "container", ")", ";", "}", "return", "$", "this", "->", "containers", "[", "$", "container", "]", ";", "}" ]
Retrieve the requested asset container object. @param string $container Name of container. @return Container
[ "Retrieve", "the", "requested", "asset", "container", "object", "." ]
train
https://github.com/mmanos/laravel-casset/blob/0f7db71211c1daa99bde30afa41da2692a39b81c/src/Mmanos/Casset/Casset.php#L19-L26
ezsystems/ezcomments-ls-extension
classes/ezcomutility.php
ezcomUtility.validateURLString
public static function validateURLString( $value ) { if( preg_match( "/^(java|vb)script:.*/i" , $value ) ) { return ezpI18n::tr( 'ezcomments/comment/add', 'Javascript code in url is not allowed.' ); } if( preg_match( "/^mailto:(.*)/i" , $value ) ) { return ezpI18n::tr( 'ezcomments/comment/add', "Email link in url is not allowed." ); } return true; }
php
public static function validateURLString( $value ) { if( preg_match( "/^(java|vb)script:.*/i" , $value ) ) { return ezpI18n::tr( 'ezcomments/comment/add', 'Javascript code in url is not allowed.' ); } if( preg_match( "/^mailto:(.*)/i" , $value ) ) { return ezpI18n::tr( 'ezcomments/comment/add', "Email link in url is not allowed." ); } return true; }
[ "public", "static", "function", "validateURLString", "(", "$", "value", ")", "{", "if", "(", "preg_match", "(", "\"/^(java|vb)script:.*/i\"", ",", "$", "value", ")", ")", "{", "return", "ezpI18n", "::", "tr", "(", "'ezcomments/comment/add'", ",", "'Javascript code in url is not allowed.'", ")", ";", "}", "if", "(", "preg_match", "(", "\"/^mailto:(.*)/i\"", ",", "$", "value", ")", ")", "{", "return", "ezpI18n", "::", "tr", "(", "'ezcomments/comment/add'", ",", "\"Email link in url is not allowed.\"", ")", ";", "}", "return", "true", ";", "}" ]
validate url string. URL can not start with javascript/vbscript/mailto
[ "validate", "url", "string", ".", "URL", "can", "not", "start", "with", "javascript", "/", "vbscript", "/", "mailto" ]
train
https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomutility.php#L19-L30
xiewulong/yii2-fileupload
oss/libs/guzzle/http/Guzzle/Http/Client.php
Client.preparePharCacert
public function preparePharCacert($md5Check = true) { $from = __DIR__ . '/Resources/cacert.pem'; $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem'; if (!file_exists($certFile) && !copy($from, $certFile)) { throw new RuntimeException("Could not copy {$from} to {$certFile}: " . var_export(error_get_last(), true)); } elseif ($md5Check) { $actualMd5 = md5_file($certFile); $expectedMd5 = trim(file_get_contents("{$from}.md5")); if ($actualMd5 != $expectedMd5) { throw new RuntimeException("{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}"); } } return $certFile; }
php
public function preparePharCacert($md5Check = true) { $from = __DIR__ . '/Resources/cacert.pem'; $certFile = sys_get_temp_dir() . '/guzzle-cacert.pem'; if (!file_exists($certFile) && !copy($from, $certFile)) { throw new RuntimeException("Could not copy {$from} to {$certFile}: " . var_export(error_get_last(), true)); } elseif ($md5Check) { $actualMd5 = md5_file($certFile); $expectedMd5 = trim(file_get_contents("{$from}.md5")); if ($actualMd5 != $expectedMd5) { throw new RuntimeException("{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}"); } } return $certFile; }
[ "public", "function", "preparePharCacert", "(", "$", "md5Check", "=", "true", ")", "{", "$", "from", "=", "__DIR__", ".", "'/Resources/cacert.pem'", ";", "$", "certFile", "=", "sys_get_temp_dir", "(", ")", ".", "'/guzzle-cacert.pem'", ";", "if", "(", "!", "file_exists", "(", "$", "certFile", ")", "&&", "!", "copy", "(", "$", "from", ",", "$", "certFile", ")", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not copy {$from} to {$certFile}: \"", ".", "var_export", "(", "error_get_last", "(", ")", ",", "true", ")", ")", ";", "}", "elseif", "(", "$", "md5Check", ")", "{", "$", "actualMd5", "=", "md5_file", "(", "$", "certFile", ")", ";", "$", "expectedMd5", "=", "trim", "(", "file_get_contents", "(", "\"{$from}.md5\"", ")", ")", ";", "if", "(", "$", "actualMd5", "!=", "$", "expectedMd5", ")", "{", "throw", "new", "RuntimeException", "(", "\"{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}\"", ")", ";", "}", "}", "return", "$", "certFile", ";", "}" ]
Copy the cacert.pem file from the phar if it is not in the temp folder and validate the MD5 checksum @param bool $md5Check Set to false to not perform the MD5 validation @return string Returns the path to the extracted cacert @throws RuntimeException if the file cannot be copied or there is a MD5 mismatch
[ "Copy", "the", "cacert", ".", "pem", "file", "from", "the", "phar", "if", "it", "is", "not", "in", "the", "temp", "folder", "and", "validate", "the", "MD5", "checksum" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/guzzle/http/Guzzle/Http/Client.php#L344-L359
xiewulong/yii2-fileupload
oss/libs/guzzle/http/Guzzle/Http/Client.php
Client.initSsl
protected function initSsl() { if ('system' == ($authority = $this->config[self::SSL_CERT_AUTHORITY])) { return; } if ($authority === null) { $authority = true; } if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') { $authority = $this->preparePharCacert(); $that = $this; $this->getEventDispatcher()->addListener('request.before_send', function ($event) use ($authority, $that) { if ($authority == $event['request']->getCurlOptions()->get(CURLOPT_CAINFO)) { $that->preparePharCacert(false); } }); } $this->setSslVerification($authority); }
php
protected function initSsl() { if ('system' == ($authority = $this->config[self::SSL_CERT_AUTHORITY])) { return; } if ($authority === null) { $authority = true; } if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') { $authority = $this->preparePharCacert(); $that = $this; $this->getEventDispatcher()->addListener('request.before_send', function ($event) use ($authority, $that) { if ($authority == $event['request']->getCurlOptions()->get(CURLOPT_CAINFO)) { $that->preparePharCacert(false); } }); } $this->setSslVerification($authority); }
[ "protected", "function", "initSsl", "(", ")", "{", "if", "(", "'system'", "==", "(", "$", "authority", "=", "$", "this", "->", "config", "[", "self", "::", "SSL_CERT_AUTHORITY", "]", ")", ")", "{", "return", ";", "}", "if", "(", "$", "authority", "===", "null", ")", "{", "$", "authority", "=", "true", ";", "}", "if", "(", "$", "authority", "===", "true", "&&", "substr", "(", "__FILE__", ",", "0", ",", "7", ")", "==", "'phar://'", ")", "{", "$", "authority", "=", "$", "this", "->", "preparePharCacert", "(", ")", ";", "$", "that", "=", "$", "this", ";", "$", "this", "->", "getEventDispatcher", "(", ")", "->", "addListener", "(", "'request.before_send'", ",", "function", "(", "$", "event", ")", "use", "(", "$", "authority", ",", "$", "that", ")", "{", "if", "(", "$", "authority", "==", "$", "event", "[", "'request'", "]", "->", "getCurlOptions", "(", ")", "->", "get", "(", "CURLOPT_CAINFO", ")", ")", "{", "$", "that", "->", "preparePharCacert", "(", "false", ")", ";", "}", "}", ")", ";", "}", "$", "this", "->", "setSslVerification", "(", "$", "authority", ")", ";", "}" ]
Initializes SSL settings
[ "Initializes", "SSL", "settings" ]
train
https://github.com/xiewulong/yii2-fileupload/blob/3e75b17a4a18dd8466e3f57c63136de03470ca82/oss/libs/guzzle/http/Guzzle/Http/Client.php#L458-L479
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.findRecursiveCallback
static protected function findRecursiveCallback( ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo ) { // ignore if we have a directory if ( $fileInfo['mode'] & 0x4000 ) { return; } // update the statistics $context->elements[] = $sourceDir . DIRECTORY_SEPARATOR . $fileName; $context->count++; $context->size += $fileInfo['size']; }
php
static protected function findRecursiveCallback( ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo ) { // ignore if we have a directory if ( $fileInfo['mode'] & 0x4000 ) { return; } // update the statistics $context->elements[] = $sourceDir . DIRECTORY_SEPARATOR . $fileName; $context->count++; $context->size += $fileInfo['size']; }
[ "static", "protected", "function", "findRecursiveCallback", "(", "ezcBaseFileFindContext", "$", "context", ",", "$", "sourceDir", ",", "$", "fileName", ",", "$", "fileInfo", ")", "{", "// ignore if we have a directory", "if", "(", "$", "fileInfo", "[", "'mode'", "]", "&", "0x4000", ")", "{", "return", ";", "}", "// update the statistics", "$", "context", "->", "elements", "[", "]", "=", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "fileName", ";", "$", "context", "->", "count", "++", ";", "$", "context", "->", "size", "+=", "$", "fileInfo", "[", "'size'", "]", ";", "}" ]
This is the callback used by findRecursive to collect data. This callback method works together with walkRecursive() and is called for every file/and or directory. The $context is a callback specific container in which data can be stored and shared between the different calls to the callback function. The walkRecursive() function also passes in the full absolute directory in $sourceDir, the filename in $fileName and file information (such as size, modes, types) as an array as returned by PHP's stat() in the $fileInfo parameter. @param ezcBaseFileFindContext $context @param string $sourceDir @param string $fileName @param array(stat) $fileInfo
[ "This", "is", "the", "callback", "used", "by", "findRecursive", "to", "collect", "data", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L58-L70
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.walkRecursive
static public function walkRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), $callback, &$callbackContext ) { if ( !is_dir( $sourceDir ) ) { throw new ezcBaseFileNotFoundException( $sourceDir, 'directory' ); } $elements = array(); $d = @dir( $sourceDir ); if ( !$d ) { throw new ezcBaseFilePermissionException( $sourceDir, ezcBaseFileException::READ ); } while ( ( $entry = $d->read() ) !== false ) { if ( $entry == '.' || $entry == '..' ) { continue; } $fileInfo = @stat( $sourceDir . DIRECTORY_SEPARATOR . $entry ); if ( !$fileInfo ) { $fileInfo = array( 'size' => 0, 'mode' => 0 ); } if ( $fileInfo['mode'] & 0x4000 ) { // We need to ignore the Permission exceptions here as it can // be normal that a directory can not be accessed. We only need // the exception if the top directory could not be read. try { call_user_func_array( $callback, array( $callbackContext, $sourceDir, $entry, $fileInfo ) ); $subList = self::walkRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry, $includeFilters, $excludeFilters, $callback, $callbackContext ); $elements = array_merge( $elements, $subList ); } catch ( ezcBaseFilePermissionException $e ) { } } else { // By default a file is included in the return list $ok = true; // Iterate over the $includeFilters and prohibit the file from // being returned when atleast one of them does not match foreach ( $includeFilters as $filter ) { if ( !preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { $ok = false; break; } } // Iterate over the $excludeFilters and prohibit the file from // being returns when atleast one of them matches foreach ( $excludeFilters as $filter ) { if ( preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { $ok = false; break; } } // If everything's allright, call the callback and add the // entry to the elements array if ( $ok ) { call_user_func( $callback, $callbackContext, $sourceDir, $entry, $fileInfo ); $elements[] = $sourceDir . DIRECTORY_SEPARATOR . $entry; } } } sort( $elements ); return $elements; }
php
static public function walkRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), $callback, &$callbackContext ) { if ( !is_dir( $sourceDir ) ) { throw new ezcBaseFileNotFoundException( $sourceDir, 'directory' ); } $elements = array(); $d = @dir( $sourceDir ); if ( !$d ) { throw new ezcBaseFilePermissionException( $sourceDir, ezcBaseFileException::READ ); } while ( ( $entry = $d->read() ) !== false ) { if ( $entry == '.' || $entry == '..' ) { continue; } $fileInfo = @stat( $sourceDir . DIRECTORY_SEPARATOR . $entry ); if ( !$fileInfo ) { $fileInfo = array( 'size' => 0, 'mode' => 0 ); } if ( $fileInfo['mode'] & 0x4000 ) { // We need to ignore the Permission exceptions here as it can // be normal that a directory can not be accessed. We only need // the exception if the top directory could not be read. try { call_user_func_array( $callback, array( $callbackContext, $sourceDir, $entry, $fileInfo ) ); $subList = self::walkRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry, $includeFilters, $excludeFilters, $callback, $callbackContext ); $elements = array_merge( $elements, $subList ); } catch ( ezcBaseFilePermissionException $e ) { } } else { // By default a file is included in the return list $ok = true; // Iterate over the $includeFilters and prohibit the file from // being returned when atleast one of them does not match foreach ( $includeFilters as $filter ) { if ( !preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { $ok = false; break; } } // Iterate over the $excludeFilters and prohibit the file from // being returns when atleast one of them matches foreach ( $excludeFilters as $filter ) { if ( preg_match( $filter, $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { $ok = false; break; } } // If everything's allright, call the callback and add the // entry to the elements array if ( $ok ) { call_user_func( $callback, $callbackContext, $sourceDir, $entry, $fileInfo ); $elements[] = $sourceDir . DIRECTORY_SEPARATOR . $entry; } } } sort( $elements ); return $elements; }
[ "static", "public", "function", "walkRecursive", "(", "$", "sourceDir", ",", "array", "$", "includeFilters", "=", "array", "(", ")", ",", "array", "$", "excludeFilters", "=", "array", "(", ")", ",", "$", "callback", ",", "&", "$", "callbackContext", ")", "{", "if", "(", "!", "is_dir", "(", "$", "sourceDir", ")", ")", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "sourceDir", ",", "'directory'", ")", ";", "}", "$", "elements", "=", "array", "(", ")", ";", "$", "d", "=", "@", "dir", "(", "$", "sourceDir", ")", ";", "if", "(", "!", "$", "d", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "sourceDir", ",", "ezcBaseFileException", "::", "READ", ")", ";", "}", "while", "(", "(", "$", "entry", "=", "$", "d", "->", "read", "(", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "entry", "==", "'.'", "||", "$", "entry", "==", "'..'", ")", "{", "continue", ";", "}", "$", "fileInfo", "=", "@", "stat", "(", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", ";", "if", "(", "!", "$", "fileInfo", ")", "{", "$", "fileInfo", "=", "array", "(", "'size'", "=>", "0", ",", "'mode'", "=>", "0", ")", ";", "}", "if", "(", "$", "fileInfo", "[", "'mode'", "]", "&", "0x4000", ")", "{", "// We need to ignore the Permission exceptions here as it can", "// be normal that a directory can not be accessed. We only need", "// the exception if the top directory could not be read.", "try", "{", "call_user_func_array", "(", "$", "callback", ",", "array", "(", "$", "callbackContext", ",", "$", "sourceDir", ",", "$", "entry", ",", "$", "fileInfo", ")", ")", ";", "$", "subList", "=", "self", "::", "walkRecursive", "(", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ",", "$", "includeFilters", ",", "$", "excludeFilters", ",", "$", "callback", ",", "$", "callbackContext", ")", ";", "$", "elements", "=", "array_merge", "(", "$", "elements", ",", "$", "subList", ")", ";", "}", "catch", "(", "ezcBaseFilePermissionException", "$", "e", ")", "{", "}", "}", "else", "{", "// By default a file is included in the return list", "$", "ok", "=", "true", ";", "// Iterate over the $includeFilters and prohibit the file from", "// being returned when atleast one of them does not match", "foreach", "(", "$", "includeFilters", "as", "$", "filter", ")", "{", "if", "(", "!", "preg_match", "(", "$", "filter", ",", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", ")", "{", "$", "ok", "=", "false", ";", "break", ";", "}", "}", "// Iterate over the $excludeFilters and prohibit the file from", "// being returns when atleast one of them matches", "foreach", "(", "$", "excludeFilters", "as", "$", "filter", ")", "{", "if", "(", "preg_match", "(", "$", "filter", ",", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", ")", "{", "$", "ok", "=", "false", ";", "break", ";", "}", "}", "// If everything's allright, call the callback and add the", "// entry to the elements array", "if", "(", "$", "ok", ")", "{", "call_user_func", "(", "$", "callback", ",", "$", "callbackContext", ",", "$", "sourceDir", ",", "$", "entry", ",", "$", "fileInfo", ")", ";", "$", "elements", "[", "]", "=", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ";", "}", "}", "}", "sort", "(", "$", "elements", ")", ";", "return", "$", "elements", ";", "}" ]
Walks files and directories recursively on a file system This method walks over a directory and calls a callback from every file and directory it finds. You can use $includeFilters to include only specific files, and $excludeFilters to exclude certain files from being returned. The function will always go into subdirectories even if the entry would not have passed the filters. The callback is passed in the $callback parameter, and the $callbackContext will be send to the callback function/method as parameter so that you can store data in there that persists with all the calls and recursive calls to this method. It's up to the callback method to do something useful with this. The callback function's parameters are in order: <ul> <li>ezcBaseFileFindContext $context</li> <li>string $sourceDir</li> <li>string $fileName</li> <li>array(stat) $fileInfo</li> </ul> See {@see findRecursiveCallback()} for an example of a callback function. Filters are regular expressions and are therefore required to have starting and ending delimiters. The Perl Compatible syntax is used as regular expression language. @param string $sourceDir @param array(string) $includeFilters @param array(string) $excludeFilters @param callback $callback @param mixed $callbackContext @throws ezcBaseFileNotFoundException if the $sourceDir directory is not a directory or does not exist. @throws ezcBaseFilePermissionException if the $sourceDir directory could not be opened for reading. @return array
[ "Walks", "files", "and", "directories", "recursively", "on", "a", "file", "system" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L113-L190
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.findRecursive
static public function findRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), &$statistics = null ) { // init statistics array if ( !is_array( $statistics ) || !array_key_exists( 'size', $statistics ) || !array_key_exists( 'count', $statistics ) ) { $statistics['size'] = 0; $statistics['count'] = 0; } // create the context, and then start walking over the array $context = new ezcBaseFileFindContext; self::walkRecursive( $sourceDir, $includeFilters, $excludeFilters, array( 'ezcBaseFile', 'findRecursiveCallback' ), $context ); // collect the statistics $statistics['size'] = $context->size; $statistics['count'] = $context->count; // return the found and pattern-matched files sort( $context->elements ); return $context->elements; }
php
static public function findRecursive( $sourceDir, array $includeFilters = array(), array $excludeFilters = array(), &$statistics = null ) { // init statistics array if ( !is_array( $statistics ) || !array_key_exists( 'size', $statistics ) || !array_key_exists( 'count', $statistics ) ) { $statistics['size'] = 0; $statistics['count'] = 0; } // create the context, and then start walking over the array $context = new ezcBaseFileFindContext; self::walkRecursive( $sourceDir, $includeFilters, $excludeFilters, array( 'ezcBaseFile', 'findRecursiveCallback' ), $context ); // collect the statistics $statistics['size'] = $context->size; $statistics['count'] = $context->count; // return the found and pattern-matched files sort( $context->elements ); return $context->elements; }
[ "static", "public", "function", "findRecursive", "(", "$", "sourceDir", ",", "array", "$", "includeFilters", "=", "array", "(", ")", ",", "array", "$", "excludeFilters", "=", "array", "(", ")", ",", "&", "$", "statistics", "=", "null", ")", "{", "// init statistics array", "if", "(", "!", "is_array", "(", "$", "statistics", ")", "||", "!", "array_key_exists", "(", "'size'", ",", "$", "statistics", ")", "||", "!", "array_key_exists", "(", "'count'", ",", "$", "statistics", ")", ")", "{", "$", "statistics", "[", "'size'", "]", "=", "0", ";", "$", "statistics", "[", "'count'", "]", "=", "0", ";", "}", "// create the context, and then start walking over the array", "$", "context", "=", "new", "ezcBaseFileFindContext", ";", "self", "::", "walkRecursive", "(", "$", "sourceDir", ",", "$", "includeFilters", ",", "$", "excludeFilters", ",", "array", "(", "'ezcBaseFile'", ",", "'findRecursiveCallback'", ")", ",", "$", "context", ")", ";", "// collect the statistics", "$", "statistics", "[", "'size'", "]", "=", "$", "context", "->", "size", ";", "$", "statistics", "[", "'count'", "]", "=", "$", "context", "->", "count", ";", "// return the found and pattern-matched files", "sort", "(", "$", "context", "->", "elements", ")", ";", "return", "$", "context", "->", "elements", ";", "}" ]
Finds files recursively on a file system With this method you can scan the file system for files. You can use $includeFilters to include only specific files, and $excludeFilters to exclude certain files from being returned. The function will always go into subdirectories even if the entry would not have passed the filters. It uses the {@see walkRecursive()} method to do the actually recursion. Filters are regular expressions and are therefore required to have starting and ending delimiters. The Perl Compatible syntax is used as regular expression language. If you pass an empty array to the $statistics argument, the function will in details about the number of files found into the 'count' array element, and the total filesize in the 'size' array element. Because this argument is passed by reference, you *have* to pass a variable and you can not pass a constant value such as "array()". @param string $sourceDir @param array(string) $includeFilters @param array(string) $excludeFilters @param array() $statistics @throws ezcBaseFileNotFoundException if the $sourceDir directory is not a directory or does not exist. @throws ezcBaseFilePermissionException if the $sourceDir directory could not be opened for reading. @return array
[ "Finds", "files", "recursively", "on", "a", "file", "system" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L222-L242
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.removeRecursive
static public function removeRecursive( $directory ) { $sourceDir = realpath( $directory ); if ( !$sourceDir ) { throw new ezcBaseFileNotFoundException( $directory, 'directory' ); } $d = @dir( $sourceDir ); if ( !$d ) { throw new ezcBaseFilePermissionException( $directory, ezcBaseFileException::READ ); } // check if we can remove the dir $parentDir = realpath( $directory . DIRECTORY_SEPARATOR . '..' ); if ( !is_writable( $parentDir ) ) { throw new ezcBaseFilePermissionException( $parentDir, ezcBaseFileException::WRITE ); } // loop over contents while ( ( $entry = $d->read() ) !== false ) { if ( $entry == '.' || $entry == '..' ) { continue; } if ( is_dir( $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { self::removeRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry ); } else { if ( @unlink( $sourceDir . DIRECTORY_SEPARATOR . $entry ) === false ) { throw new ezcBaseFilePermissionException( $directory . DIRECTORY_SEPARATOR . $entry, ezcBaseFileException::REMOVE ); } } } $d->close(); rmdir( $sourceDir ); }
php
static public function removeRecursive( $directory ) { $sourceDir = realpath( $directory ); if ( !$sourceDir ) { throw new ezcBaseFileNotFoundException( $directory, 'directory' ); } $d = @dir( $sourceDir ); if ( !$d ) { throw new ezcBaseFilePermissionException( $directory, ezcBaseFileException::READ ); } // check if we can remove the dir $parentDir = realpath( $directory . DIRECTORY_SEPARATOR . '..' ); if ( !is_writable( $parentDir ) ) { throw new ezcBaseFilePermissionException( $parentDir, ezcBaseFileException::WRITE ); } // loop over contents while ( ( $entry = $d->read() ) !== false ) { if ( $entry == '.' || $entry == '..' ) { continue; } if ( is_dir( $sourceDir . DIRECTORY_SEPARATOR . $entry ) ) { self::removeRecursive( $sourceDir . DIRECTORY_SEPARATOR . $entry ); } else { if ( @unlink( $sourceDir . DIRECTORY_SEPARATOR . $entry ) === false ) { throw new ezcBaseFilePermissionException( $directory . DIRECTORY_SEPARATOR . $entry, ezcBaseFileException::REMOVE ); } } } $d->close(); rmdir( $sourceDir ); }
[ "static", "public", "function", "removeRecursive", "(", "$", "directory", ")", "{", "$", "sourceDir", "=", "realpath", "(", "$", "directory", ")", ";", "if", "(", "!", "$", "sourceDir", ")", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "directory", ",", "'directory'", ")", ";", "}", "$", "d", "=", "@", "dir", "(", "$", "sourceDir", ")", ";", "if", "(", "!", "$", "d", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "directory", ",", "ezcBaseFileException", "::", "READ", ")", ";", "}", "// check if we can remove the dir", "$", "parentDir", "=", "realpath", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "'..'", ")", ";", "if", "(", "!", "is_writable", "(", "$", "parentDir", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "parentDir", ",", "ezcBaseFileException", "::", "WRITE", ")", ";", "}", "// loop over contents", "while", "(", "(", "$", "entry", "=", "$", "d", "->", "read", "(", ")", ")", "!==", "false", ")", "{", "if", "(", "$", "entry", "==", "'.'", "||", "$", "entry", "==", "'..'", ")", "{", "continue", ";", "}", "if", "(", "is_dir", "(", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", ")", "{", "self", "::", "removeRecursive", "(", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", ";", "}", "else", "{", "if", "(", "@", "unlink", "(", "$", "sourceDir", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ")", "===", "false", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "entry", ",", "ezcBaseFileException", "::", "REMOVE", ")", ";", "}", "}", "}", "$", "d", "->", "close", "(", ")", ";", "rmdir", "(", "$", "sourceDir", ")", ";", "}" ]
Removes files and directories recursively from a file system This method recursively removes the $directory and all its contents. You should be <b>extremely</b> careful with this method as it has the potential to erase everything that the current user has access to. @param string $directory
[ "Removes", "files", "and", "directories", "recursively", "from", "a", "file", "system" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L254-L294
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.copyRecursive
static public function copyRecursive( $source, $destination, $depth = -1, $dirMode = 0775, $fileMode = 0664 ) { // Check if source file exists at all. if ( !is_file( $source ) && !is_dir( $source ) ) { throw new ezcBaseFileNotFoundException( $source ); } // Destination file should NOT exist if ( is_file( $destination ) || is_dir( $destination ) ) { throw new ezcBaseFilePermissionException( $destination, ezcBaseFileException::WRITE ); } // Skip non readable files in source directory if ( !is_readable( $source ) ) { return; } // Copy if ( is_dir( $source ) ) { mkdir( $destination ); // To ignore umask, umask() should not be changed with // multithreaded servers... chmod( $destination, $dirMode ); } elseif ( is_file( $source ) ) { copy( $source, $destination ); chmod( $destination, $fileMode ); } if ( ( $depth === 0 ) || ( !is_dir( $source ) ) ) { // Do not recurse (any more) return; } // Recurse $dh = opendir( $source ); while ( ( $file = readdir( $dh ) ) !== false ) { if ( ( $file === '.' ) || ( $file === '..' ) ) { continue; } self::copyRecursive( $source . '/' . $file, $destination . '/' . $file, $depth - 1, $dirMode, $fileMode ); } }
php
static public function copyRecursive( $source, $destination, $depth = -1, $dirMode = 0775, $fileMode = 0664 ) { // Check if source file exists at all. if ( !is_file( $source ) && !is_dir( $source ) ) { throw new ezcBaseFileNotFoundException( $source ); } // Destination file should NOT exist if ( is_file( $destination ) || is_dir( $destination ) ) { throw new ezcBaseFilePermissionException( $destination, ezcBaseFileException::WRITE ); } // Skip non readable files in source directory if ( !is_readable( $source ) ) { return; } // Copy if ( is_dir( $source ) ) { mkdir( $destination ); // To ignore umask, umask() should not be changed with // multithreaded servers... chmod( $destination, $dirMode ); } elseif ( is_file( $source ) ) { copy( $source, $destination ); chmod( $destination, $fileMode ); } if ( ( $depth === 0 ) || ( !is_dir( $source ) ) ) { // Do not recurse (any more) return; } // Recurse $dh = opendir( $source ); while ( ( $file = readdir( $dh ) ) !== false ) { if ( ( $file === '.' ) || ( $file === '..' ) ) { continue; } self::copyRecursive( $source . '/' . $file, $destination . '/' . $file, $depth - 1, $dirMode, $fileMode ); } }
[ "static", "public", "function", "copyRecursive", "(", "$", "source", ",", "$", "destination", ",", "$", "depth", "=", "-", "1", ",", "$", "dirMode", "=", "0775", ",", "$", "fileMode", "=", "0664", ")", "{", "// Check if source file exists at all.", "if", "(", "!", "is_file", "(", "$", "source", ")", "&&", "!", "is_dir", "(", "$", "source", ")", ")", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "source", ")", ";", "}", "// Destination file should NOT exist", "if", "(", "is_file", "(", "$", "destination", ")", "||", "is_dir", "(", "$", "destination", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "destination", ",", "ezcBaseFileException", "::", "WRITE", ")", ";", "}", "// Skip non readable files in source directory", "if", "(", "!", "is_readable", "(", "$", "source", ")", ")", "{", "return", ";", "}", "// Copy", "if", "(", "is_dir", "(", "$", "source", ")", ")", "{", "mkdir", "(", "$", "destination", ")", ";", "// To ignore umask, umask() should not be changed with", "// multithreaded servers...", "chmod", "(", "$", "destination", ",", "$", "dirMode", ")", ";", "}", "elseif", "(", "is_file", "(", "$", "source", ")", ")", "{", "copy", "(", "$", "source", ",", "$", "destination", ")", ";", "chmod", "(", "$", "destination", ",", "$", "fileMode", ")", ";", "}", "if", "(", "(", "$", "depth", "===", "0", ")", "||", "(", "!", "is_dir", "(", "$", "source", ")", ")", ")", "{", "// Do not recurse (any more)", "return", ";", "}", "// Recurse", "$", "dh", "=", "opendir", "(", "$", "source", ")", ";", "while", "(", "(", "$", "file", "=", "readdir", "(", "$", "dh", ")", ")", "!==", "false", ")", "{", "if", "(", "(", "$", "file", "===", "'.'", ")", "||", "(", "$", "file", "===", "'..'", ")", ")", "{", "continue", ";", "}", "self", "::", "copyRecursive", "(", "$", "source", ".", "'/'", ".", "$", "file", ",", "$", "destination", ".", "'/'", ".", "$", "file", ",", "$", "depth", "-", "1", ",", "$", "dirMode", ",", "$", "fileMode", ")", ";", "}", "}" ]
Recursively copy a file or directory. Recursively copy a file or directory in $source to the given destination. If a depth is given, the operation will stop, if the given recursion depth is reached. A depth of -1 means no limit, while a depth of 0 means, that only the current file or directory will be copied, without any recursion. You may optionally define modes used to create files and directories. @throws ezcBaseFileNotFoundException If the $sourceDir directory is not a directory or does not exist. @throws ezcBaseFilePermissionException If the $sourceDir directory could not be opened for reading, or the destination is not writeable. @param string $source @param string $destination @param int $depth @param int $dirMode @param int $fileMode @return void
[ "Recursively", "copy", "a", "file", "or", "directory", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L320-L377
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.calculateRelativePath
static public function calculateRelativePath( $path, $base ) { // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR ); $base = strtr( $base, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR ); $base = explode( DIRECTORY_SEPARATOR, $base ); $path = explode( DIRECTORY_SEPARATOR, $path ); // If the paths are the same we return if ( $base === $path ) { return '.'; } $result = ''; $pathPart = array_shift( $path ); $basePart = array_shift( $base ); while ( $pathPart == $basePart ) { $pathPart = array_shift( $path ); $basePart = array_shift( $base ); } if ( $pathPart != null ) { array_unshift( $path, $pathPart ); } if ( $basePart != null ) { array_unshift( $base, $basePart ); } $result = str_repeat( '..' . DIRECTORY_SEPARATOR, count( $base ) ); // prevent a trailing DIRECTORY_SEPARATOR in case there is only a .. if ( count( $path ) == 0 ) { $result = substr( $result, 0, -strlen( DIRECTORY_SEPARATOR ) ); } $result .= join( DIRECTORY_SEPARATOR, $path ); return $result; }
php
static public function calculateRelativePath( $path, $base ) { // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR ); $base = strtr( $base, '\\/', DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR ); $base = explode( DIRECTORY_SEPARATOR, $base ); $path = explode( DIRECTORY_SEPARATOR, $path ); // If the paths are the same we return if ( $base === $path ) { return '.'; } $result = ''; $pathPart = array_shift( $path ); $basePart = array_shift( $base ); while ( $pathPart == $basePart ) { $pathPart = array_shift( $path ); $basePart = array_shift( $base ); } if ( $pathPart != null ) { array_unshift( $path, $pathPart ); } if ( $basePart != null ) { array_unshift( $base, $basePart ); } $result = str_repeat( '..' . DIRECTORY_SEPARATOR, count( $base ) ); // prevent a trailing DIRECTORY_SEPARATOR in case there is only a .. if ( count( $path ) == 0 ) { $result = substr( $result, 0, -strlen( DIRECTORY_SEPARATOR ) ); } $result .= join( DIRECTORY_SEPARATOR, $path ); return $result; }
[ "static", "public", "function", "calculateRelativePath", "(", "$", "path", ",", "$", "base", ")", "{", "// Sanitize the paths to use the correct directory separator for the platform", "$", "path", "=", "strtr", "(", "$", "path", ",", "'\\\\/'", ",", "DIRECTORY_SEPARATOR", ".", "DIRECTORY_SEPARATOR", ")", ";", "$", "base", "=", "strtr", "(", "$", "base", ",", "'\\\\/'", ",", "DIRECTORY_SEPARATOR", ".", "DIRECTORY_SEPARATOR", ")", ";", "$", "base", "=", "explode", "(", "DIRECTORY_SEPARATOR", ",", "$", "base", ")", ";", "$", "path", "=", "explode", "(", "DIRECTORY_SEPARATOR", ",", "$", "path", ")", ";", "// If the paths are the same we return", "if", "(", "$", "base", "===", "$", "path", ")", "{", "return", "'.'", ";", "}", "$", "result", "=", "''", ";", "$", "pathPart", "=", "array_shift", "(", "$", "path", ")", ";", "$", "basePart", "=", "array_shift", "(", "$", "base", ")", ";", "while", "(", "$", "pathPart", "==", "$", "basePart", ")", "{", "$", "pathPart", "=", "array_shift", "(", "$", "path", ")", ";", "$", "basePart", "=", "array_shift", "(", "$", "base", ")", ";", "}", "if", "(", "$", "pathPart", "!=", "null", ")", "{", "array_unshift", "(", "$", "path", ",", "$", "pathPart", ")", ";", "}", "if", "(", "$", "basePart", "!=", "null", ")", "{", "array_unshift", "(", "$", "base", ",", "$", "basePart", ")", ";", "}", "$", "result", "=", "str_repeat", "(", "'..'", ".", "DIRECTORY_SEPARATOR", ",", "count", "(", "$", "base", ")", ")", ";", "// prevent a trailing DIRECTORY_SEPARATOR in case there is only a ..", "if", "(", "count", "(", "$", "path", ")", "==", "0", ")", "{", "$", "result", "=", "substr", "(", "$", "result", ",", "0", ",", "-", "strlen", "(", "DIRECTORY_SEPARATOR", ")", ")", ";", "}", "$", "result", ".=", "join", "(", "DIRECTORY_SEPARATOR", ",", "$", "path", ")", ";", "return", "$", "result", ";", "}" ]
Calculates the relative path of the file/directory '$path' to a given $base path. $path and $base should be fully absolute paths. This function returns the answer of "How do I go from $base to $path". If the $path and $base are the same path, the function returns '.'. This method does not touch the filesystem. @param string $path @param string $base @return string
[ "Calculates", "the", "relative", "path", "of", "the", "file", "/", "directory", "$path", "to", "a", "given", "$base", "path", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L392-L435
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php
ezcBaseFile.isAbsolutePath
public static function isAbsolutePath( $path, $os = null ) { if ( $os === null ) { $os = ezcBaseFeatures::os(); } // Stream wrapper like phar can also be considered absolute paths if ( preg_match( '(^[a-z]{3,}://)S', $path ) ) { return true; } switch ( $os ) { case 'Windows': // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', '\\\\' ); // Absolute paths with drive letter: X:\ if ( preg_match( '@^[A-Z]:\\\\@i', $path ) ) { return true; } // Absolute paths with network paths: \\server\share\ if ( preg_match( '@^\\\\\\\\[A-Z]+\\\\[^\\\\]@i', $path ) ) { return true; } break; case 'Mac': case 'Linux': case 'FreeBSD': default: // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', '//' ); if ( $path[0] == '/' ) { return true; } } return false; }
php
public static function isAbsolutePath( $path, $os = null ) { if ( $os === null ) { $os = ezcBaseFeatures::os(); } // Stream wrapper like phar can also be considered absolute paths if ( preg_match( '(^[a-z]{3,}://)S', $path ) ) { return true; } switch ( $os ) { case 'Windows': // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', '\\\\' ); // Absolute paths with drive letter: X:\ if ( preg_match( '@^[A-Z]:\\\\@i', $path ) ) { return true; } // Absolute paths with network paths: \\server\share\ if ( preg_match( '@^\\\\\\\\[A-Z]+\\\\[^\\\\]@i', $path ) ) { return true; } break; case 'Mac': case 'Linux': case 'FreeBSD': default: // Sanitize the paths to use the correct directory separator for the platform $path = strtr( $path, '\\/', '//' ); if ( $path[0] == '/' ) { return true; } } return false; }
[ "public", "static", "function", "isAbsolutePath", "(", "$", "path", ",", "$", "os", "=", "null", ")", "{", "if", "(", "$", "os", "===", "null", ")", "{", "$", "os", "=", "ezcBaseFeatures", "::", "os", "(", ")", ";", "}", "// Stream wrapper like phar can also be considered absolute paths", "if", "(", "preg_match", "(", "'(^[a-z]{3,}://)S'", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "switch", "(", "$", "os", ")", "{", "case", "'Windows'", ":", "// Sanitize the paths to use the correct directory separator for the platform", "$", "path", "=", "strtr", "(", "$", "path", ",", "'\\\\/'", ",", "'\\\\\\\\'", ")", ";", "// Absolute paths with drive letter: X:\\", "if", "(", "preg_match", "(", "'@^[A-Z]:\\\\\\\\@i'", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "// Absolute paths with network paths: \\\\server\\share\\", "if", "(", "preg_match", "(", "'@^\\\\\\\\\\\\\\\\[A-Z]+\\\\\\\\[^\\\\\\\\]@i'", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "break", ";", "case", "'Mac'", ":", "case", "'Linux'", ":", "case", "'FreeBSD'", ":", "default", ":", "// Sanitize the paths to use the correct directory separator for the platform", "$", "path", "=", "strtr", "(", "$", "path", ",", "'\\\\/'", ",", "'//'", ")", ";", "if", "(", "$", "path", "[", "0", "]", "==", "'/'", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns whether the passed $path is an absolute path, giving the current $os. With the $os parameter you can tell this function to use the semantics for a different operating system to determine whether a path is absolute. The $os argument defaults to the OS that the script is running on. @param string $path @param string $os @return bool
[ "Returns", "whether", "the", "passed", "$path", "is", "an", "absolute", "path", "giving", "the", "current", "$os", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Base/src/file.php#L449-L493
shipmile/shipmile-api-php
lib/Shipmile/HttpClient/HttpClient.php
HttpClient.request
public function request($path, $body = null, $httpMethod = 'GET', array $options = array()) { $headers = array(); $options = array_merge($this->options, $options); if (isset($options['headers'])) { $headers = $options['headers']; unset($options['headers']); } $headers = array_merge($this->headers, array_change_key_case($headers)); unset($options['body']); unset($options['base']); unset($options['user_agent']); $request = $this->createRequest($httpMethod, $path, null, $headers, $options); if ($httpMethod != 'GET') { $request = $this->setBody($request, $body, $options); } try { $response = $this->client->send($request); } catch (\LogicException $e) { throw new \ErrorException($e->getMessage()); } catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage()); } return new Response($this->getBody($response), $response->getStatusCode(), $response->getHeaders()); }
php
public function request($path, $body = null, $httpMethod = 'GET', array $options = array()) { $headers = array(); $options = array_merge($this->options, $options); if (isset($options['headers'])) { $headers = $options['headers']; unset($options['headers']); } $headers = array_merge($this->headers, array_change_key_case($headers)); unset($options['body']); unset($options['base']); unset($options['user_agent']); $request = $this->createRequest($httpMethod, $path, null, $headers, $options); if ($httpMethod != 'GET') { $request = $this->setBody($request, $body, $options); } try { $response = $this->client->send($request); } catch (\LogicException $e) { throw new \ErrorException($e->getMessage()); } catch (\RuntimeException $e) { throw new \RuntimeException($e->getMessage()); } return new Response($this->getBody($response), $response->getStatusCode(), $response->getHeaders()); }
[ "public", "function", "request", "(", "$", "path", ",", "$", "body", "=", "null", ",", "$", "httpMethod", "=", "'GET'", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "headers", "=", "array", "(", ")", ";", "$", "options", "=", "array_merge", "(", "$", "this", "->", "options", ",", "$", "options", ")", ";", "if", "(", "isset", "(", "$", "options", "[", "'headers'", "]", ")", ")", "{", "$", "headers", "=", "$", "options", "[", "'headers'", "]", ";", "unset", "(", "$", "options", "[", "'headers'", "]", ")", ";", "}", "$", "headers", "=", "array_merge", "(", "$", "this", "->", "headers", ",", "array_change_key_case", "(", "$", "headers", ")", ")", ";", "unset", "(", "$", "options", "[", "'body'", "]", ")", ";", "unset", "(", "$", "options", "[", "'base'", "]", ")", ";", "unset", "(", "$", "options", "[", "'user_agent'", "]", ")", ";", "$", "request", "=", "$", "this", "->", "createRequest", "(", "$", "httpMethod", ",", "$", "path", ",", "null", ",", "$", "headers", ",", "$", "options", ")", ";", "if", "(", "$", "httpMethod", "!=", "'GET'", ")", "{", "$", "request", "=", "$", "this", "->", "setBody", "(", "$", "request", ",", "$", "body", ",", "$", "options", ")", ";", "}", "try", "{", "$", "response", "=", "$", "this", "->", "client", "->", "send", "(", "$", "request", ")", ";", "}", "catch", "(", "\\", "LogicException", "$", "e", ")", "{", "throw", "new", "\\", "ErrorException", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "\\", "RuntimeException", "$", "e", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "$", "e", "->", "getMessage", "(", ")", ")", ";", "}", "return", "new", "Response", "(", "$", "this", "->", "getBody", "(", "$", "response", ")", ",", "$", "response", "->", "getStatusCode", "(", ")", ",", "$", "response", "->", "getHeaders", "(", ")", ")", ";", "}" ]
Intermediate function which does three main things - Transforms the body of request into correct format - Creates the requests with give parameters - Returns response body after parsing it into correct format
[ "Intermediate", "function", "which", "does", "three", "main", "things" ]
train
https://github.com/shipmile/shipmile-api-php/blob/b8272613b3a27f0f27e8722cbee277e41e9dfe59/lib/Shipmile/HttpClient/HttpClient.php#L99-L132
shipmile/shipmile-api-php
lib/Shipmile/HttpClient/HttpClient.php
HttpClient.createRequest
public function createRequest($httpMethod, $path, $body = null, array $headers = array(), array $options = array()) { $version = (isset($options['api_version']) ? "/".$options['api_version'] : ""); $path = $version.$path; return $this->client->createRequest($httpMethod, $path, $headers, $body, $options); }
php
public function createRequest($httpMethod, $path, $body = null, array $headers = array(), array $options = array()) { $version = (isset($options['api_version']) ? "/".$options['api_version'] : ""); $path = $version.$path; return $this->client->createRequest($httpMethod, $path, $headers, $body, $options); }
[ "public", "function", "createRequest", "(", "$", "httpMethod", ",", "$", "path", ",", "$", "body", "=", "null", ",", "array", "$", "headers", "=", "array", "(", ")", ",", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "version", "=", "(", "isset", "(", "$", "options", "[", "'api_version'", "]", ")", "?", "\"/\"", ".", "$", "options", "[", "'api_version'", "]", ":", "\"\"", ")", ";", "$", "path", "=", "$", "version", ".", "$", "path", ";", "return", "$", "this", "->", "client", "->", "createRequest", "(", "$", "httpMethod", ",", "$", "path", ",", "$", "headers", ",", "$", "body", ",", "$", "options", ")", ";", "}" ]
Creating a request with the given arguments If api_version is set, appends it immediately after host
[ "Creating", "a", "request", "with", "the", "given", "arguments" ]
train
https://github.com/shipmile/shipmile-api-php/blob/b8272613b3a27f0f27e8722cbee277e41e9dfe59/lib/Shipmile/HttpClient/HttpClient.php#L139-L146
shipmile/shipmile-api-php
lib/Shipmile/HttpClient/HttpClient.php
HttpClient.setBody
public function setBody(RequestInterface $request, $body, $options) { return RequestHandler::setBody($request, $body, $options); }
php
public function setBody(RequestInterface $request, $body, $options) { return RequestHandler::setBody($request, $body, $options); }
[ "public", "function", "setBody", "(", "RequestInterface", "$", "request", ",", "$", "body", ",", "$", "options", ")", "{", "return", "RequestHandler", "::", "setBody", "(", "$", "request", ",", "$", "body", ",", "$", "options", ")", ";", "}" ]
Set request body in correct format
[ "Set", "request", "body", "in", "correct", "format" ]
train
https://github.com/shipmile/shipmile-api-php/blob/b8272613b3a27f0f27e8722cbee277e41e9dfe59/lib/Shipmile/HttpClient/HttpClient.php#L159-L162
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Database/src/handlers/oracle.php
ezcDbHandlerOracle.processLimitOffset
protected function processLimitOffset( $queryString, $limit, $offset ) { if ( isset( $limit ) ) { if ( !isset( $offset ) ) { $offset = 0; } $min = $offset+1; $max = $offset+$limit; $queryString = "SELECT * FROM (SELECT a.*, ROWNUM rn FROM ($queryString) a WHERE rownum <= $max) WHERE rn >= $min"; } return $queryString; }
php
protected function processLimitOffset( $queryString, $limit, $offset ) { if ( isset( $limit ) ) { if ( !isset( $offset ) ) { $offset = 0; } $min = $offset+1; $max = $offset+$limit; $queryString = "SELECT * FROM (SELECT a.*, ROWNUM rn FROM ($queryString) a WHERE rownum <= $max) WHERE rn >= $min"; } return $queryString; }
[ "protected", "function", "processLimitOffset", "(", "$", "queryString", ",", "$", "limit", ",", "$", "offset", ")", "{", "if", "(", "isset", "(", "$", "limit", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "offset", ")", ")", "{", "$", "offset", "=", "0", ";", "}", "$", "min", "=", "$", "offset", "+", "1", ";", "$", "max", "=", "$", "offset", "+", "$", "limit", ";", "$", "queryString", "=", "\"SELECT * FROM (SELECT a.*, ROWNUM rn FROM ($queryString) a WHERE rownum <= $max) WHERE rn >= $min\"", ";", "}", "return", "$", "queryString", ";", "}" ]
Returns an SQL query with LIMIT/OFFSET functionality appended. The LIMIT/OFFSET is added to $queryString. $limit controls the maximum number of entries in the resultset. $offset controls where in the resultset results should be returned from. @param string $queryString @param int $limit @param int $offset @return string
[ "Returns", "an", "SQL", "query", "with", "LIMIT", "/", "OFFSET", "functionality", "appended", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Database/src/handlers/oracle.php#L120-L136
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getClient
public function getClient() { if (!$this->client) { $client = new GuzzleHelper(); $this->configureClient($client); return $this->client = $client->getClient(); } return $this->client; }
php
public function getClient() { if (!$this->client) { $client = new GuzzleHelper(); $this->configureClient($client); return $this->client = $client->getClient(); } return $this->client; }
[ "public", "function", "getClient", "(", ")", "{", "if", "(", "!", "$", "this", "->", "client", ")", "{", "$", "client", "=", "new", "GuzzleHelper", "(", ")", ";", "$", "this", "->", "configureClient", "(", "$", "client", ")", ";", "return", "$", "this", "->", "client", "=", "$", "client", "->", "getClient", "(", ")", ";", "}", "return", "$", "this", "->", "client", ";", "}" ]
Get new Curl instance @return Curl curl
[ "Get", "new", "Curl", "instance" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L36-L47
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.performRequest
public function performRequest($url) { $client = $this->getClient(); return $this->response = $client->get($url); }
php
public function performRequest($url) { $client = $this->getClient(); return $this->response = $client->get($url); }
[ "public", "function", "performRequest", "(", "$", "url", ")", "{", "$", "client", "=", "$", "this", "->", "getClient", "(", ")", ";", "return", "$", "this", "->", "response", "=", "$", "client", "->", "get", "(", "$", "url", ")", ";", "}" ]
Perform HTTP request @param string url @return CurlResponse response
[ "Perform", "HTTP", "request" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L66-L71
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.parse
public function parse($url) { $content = $this->performRequest($url)->getBody()->getContents(); $content = $this->convertEncodingToUTF8($content); return $this->getHtmlDomParser($content); }
php
public function parse($url) { $content = $this->performRequest($url)->getBody()->getContents(); $content = $this->convertEncodingToUTF8($content); return $this->getHtmlDomParser($content); }
[ "public", "function", "parse", "(", "$", "url", ")", "{", "$", "content", "=", "$", "this", "->", "performRequest", "(", "$", "url", ")", "->", "getBody", "(", ")", "->", "getContents", "(", ")", ";", "$", "content", "=", "$", "this", "->", "convertEncodingToUTF8", "(", "$", "content", ")", ";", "return", "$", "this", "->", "getHtmlDomParser", "(", "$", "content", ")", ";", "}" ]
Parse webpage @return string url;
[ "Parse", "webpage" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L102-L109
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getPageTitle
public function getPageTitle() { if (!$this->parser) { return; } $node = $this->parser->find('title', 0); if ($node) { return $node->innertext; } }
php
public function getPageTitle() { if (!$this->parser) { return; } $node = $this->parser->find('title', 0); if ($node) { return $node->innertext; } }
[ "public", "function", "getPageTitle", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "return", ";", "}", "$", "node", "=", "$", "this", "->", "parser", "->", "find", "(", "'title'", ",", "0", ")", ";", "if", "(", "$", "node", ")", "{", "return", "$", "node", "->", "innertext", ";", "}", "}" ]
Get page title @return string title
[ "Get", "page", "title" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L136-L147
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getPageDescription
public function getPageDescription() { if (!$this->parser) { return; } $node = $this->parser->find('meta[name=description]', 0); if ($node) { return $node->getAttribute('content'); } }
php
public function getPageDescription() { if (!$this->parser) { return; } $node = $this->parser->find('meta[name=description]', 0); if ($node) { return $node->getAttribute('content'); } }
[ "public", "function", "getPageDescription", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "return", ";", "}", "$", "node", "=", "$", "this", "->", "parser", "->", "find", "(", "'meta[name=description]'", ",", "0", ")", ";", "if", "(", "$", "node", ")", "{", "return", "$", "node", "->", "getAttribute", "(", "'content'", ")", ";", "}", "}" ]
Get page description @return string description
[ "Get", "page", "description" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L154-L165
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getPageKeywords
public function getPageKeywords() { if (!$this->parser) { return; } $node = $this->parser->find('meta[name=keywords]', 0); if ($node) { return $node->getAttribute('content'); } }
php
public function getPageKeywords() { if (!$this->parser) { return; } $node = $this->parser->find('meta[name=keywords]', 0); if ($node) { return $node->getAttribute('content'); } }
[ "public", "function", "getPageKeywords", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "return", ";", "}", "$", "node", "=", "$", "this", "->", "parser", "->", "find", "(", "'meta[name=keywords]'", ",", "0", ")", ";", "if", "(", "$", "node", ")", "{", "return", "$", "node", "->", "getAttribute", "(", "'content'", ")", ";", "}", "}" ]
Get page keywords @return string url
[ "Get", "page", "keywords" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L172-L183
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getPageCanonical
public function getPageCanonical() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=canonical]', 0); if ($node) { return $node->getAttribute('href'); } }
php
public function getPageCanonical() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=canonical]', 0); if ($node) { return $node->getAttribute('href'); } }
[ "public", "function", "getPageCanonical", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "return", ";", "}", "$", "node", "=", "$", "this", "->", "parser", "->", "find", "(", "'link[rel=canonical]'", ",", "0", ")", ";", "if", "(", "$", "node", ")", "{", "return", "$", "node", "->", "getAttribute", "(", "'href'", ")", ";", "}", "}" ]
Get page canonical url @return string url
[ "Get", "page", "canonical", "url" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L190-L201
chemel/dom-parser-helper
src/HtmlDomParserHelper.php
HtmlDomParserHelper.getPageFavicon
public function getPageFavicon() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=shortcut], link[rel=icon], link[rel=shortcut icon]', 0); if ($node) { return $node->getAttribute('href'); } }
php
public function getPageFavicon() { if (!$this->parser) { return; } $node = $this->parser->find('link[rel=shortcut], link[rel=icon], link[rel=shortcut icon]', 0); if ($node) { return $node->getAttribute('href'); } }
[ "public", "function", "getPageFavicon", "(", ")", "{", "if", "(", "!", "$", "this", "->", "parser", ")", "{", "return", ";", "}", "$", "node", "=", "$", "this", "->", "parser", "->", "find", "(", "'link[rel=shortcut], link[rel=icon], link[rel=shortcut icon]'", ",", "0", ")", ";", "if", "(", "$", "node", ")", "{", "return", "$", "node", "->", "getAttribute", "(", "'href'", ")", ";", "}", "}" ]
Get page favicon url @return string url
[ "Get", "page", "favicon", "url" ]
train
https://github.com/chemel/dom-parser-helper/blob/0ec7df13b19e3f3df4453023b37cba6bb16eb10a/src/HtmlDomParserHelper.php#L208-L219