repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
polyfony-inc/polyfony
Private/Polyfony/Format.php
Format.wrap
public static function wrap($text, $phrase, $wrapper = '<strong class="highlight">\\1</strong>') { if(empty($text)) { return ''; } if(empty($phrase)) { return $text; } if(is_array($phrase)) { foreach ($phrase as $word) { $pattern[] = '/(' . preg_quote($word, '/') . ')/i'; $replacement[] = $wrapper; } } else { $pattern = '/('.preg_quote($phrase, '/').')/i'; $replacement = $wrapper; } return preg_replace($pattern, $replacement, $text); }
php
public static function wrap($text, $phrase, $wrapper = '<strong class="highlight">\\1</strong>') { if(empty($text)) { return ''; } if(empty($phrase)) { return $text; } if(is_array($phrase)) { foreach ($phrase as $word) { $pattern[] = '/(' . preg_quote($word, '/') . ')/i'; $replacement[] = $wrapper; } } else { $pattern = '/('.preg_quote($phrase, '/').')/i'; $replacement = $wrapper; } return preg_replace($pattern, $replacement, $text); }
[ "public", "static", "function", "wrap", "(", "$", "text", ",", "$", "phrase", ",", "$", "wrapper", "=", "'<strong class=\"highlight\">\\\\1</strong>'", ")", "{", "if", "(", "empty", "(", "$", "text", ")", ")", "{", "return", "''", ";", "}", "if", "(", ...
will wrap a portion of text in another
[ "will", "wrap", "a", "portion", "of", "text", "in", "another" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Format.php#L165-L183
train
polyfony-inc/polyfony
Private/Polyfony/Format.php
Format.integer
public static function integer($value) :int { if(strrpos($value, '.')) { $value = str_replace(',', '' , $value); } elseif(strrpos($value, ',')) { $value = str_replace('.', '' , $value); } return(intval(preg_replace('/[^0-9.\-]/', '', str_replace(',', '.' , $value)))); }
php
public static function integer($value) :int { if(strrpos($value, '.')) { $value = str_replace(',', '' , $value); } elseif(strrpos($value, ',')) { $value = str_replace('.', '' , $value); } return(intval(preg_replace('/[^0-9.\-]/', '', str_replace(',', '.' , $value)))); }
[ "public", "static", "function", "integer", "(", "$", "value", ")", ":", "int", "{", "if", "(", "strrpos", "(", "$", "value", ",", "'.'", ")", ")", "{", "$", "value", "=", "str_replace", "(", "','", ",", "''", ",", "$", "value", ")", ";", "}", "...
will clean the value of anything but 0-9 and minus preserve sign return integer
[ "will", "clean", "the", "value", "of", "anything", "but", "0", "-", "9", "and", "minus", "preserve", "sign", "return", "integer" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Format.php#L192-L200
train
polyfony-inc/polyfony
Private/Polyfony/Format.php
Format.float
public static function float($value, int $precision = 2) :float { if(strrpos($value, '.')) { $value = str_replace(',', '' , $value); } elseif(strrpos($value, ',')) { $value = str_replace('.', '' , $value); } return(floatval( round(preg_replace('/[^0-9.\-]/', '', str_replace(',', '.' , $value)), $precision) )); }
php
public static function float($value, int $precision = 2) :float { if(strrpos($value, '.')) { $value = str_replace(',', '' , $value); } elseif(strrpos($value, ',')) { $value = str_replace('.', '' , $value); } return(floatval( round(preg_replace('/[^0-9.\-]/', '', str_replace(',', '.' , $value)), $precision) )); }
[ "public", "static", "function", "float", "(", "$", "value", ",", "int", "$", "precision", "=", "2", ")", ":", "float", "{", "if", "(", "strrpos", "(", "$", "value", ",", "'.'", ")", ")", "{", "$", "value", "=", "str_replace", "(", "','", ",", "''...
will clean the value of anything but 0-9\.- preserve sign return float
[ "will", "clean", "the", "value", "of", "anything", "but", "0", "-", "9", "\\", ".", "-", "preserve", "sign", "return", "float" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Format.php#L203-L213
train
polyfony-inc/polyfony
Private/Polyfony/Format.php
Format.csv
public static function csv(array $array, string $separator = "\t", string $encapsulate_cells = '"') :string { // declare our csv $csv = ''; // for each line of the array foreach($array as $cells) { // for each cell of that line foreach($cells as $cell) { // protect the cell's value, encapsulate it, and separate it, $csv .= $encapsulate_cells . str_replace($encapsulate_cells, '\\'.$encapsulate_cells, $cell) . $encapsulate_cells . $separator; } // skip to the next line $csv .= "\n"; } // return the formatted csv return $csv; }
php
public static function csv(array $array, string $separator = "\t", string $encapsulate_cells = '"') :string { // declare our csv $csv = ''; // for each line of the array foreach($array as $cells) { // for each cell of that line foreach($cells as $cell) { // protect the cell's value, encapsulate it, and separate it, $csv .= $encapsulate_cells . str_replace($encapsulate_cells, '\\'.$encapsulate_cells, $cell) . $encapsulate_cells . $separator; } // skip to the next line $csv .= "\n"; } // return the formatted csv return $csv; }
[ "public", "static", "function", "csv", "(", "array", "$", "array", ",", "string", "$", "separator", "=", "\"\\t\"", ",", "string", "$", "encapsulate_cells", "=", "'\"'", ")", ":", "string", "{", "// declare our csv", "$", "csv", "=", "''", ";", "// for eac...
convert an array to a csv
[ "convert", "an", "array", "to", "a", "csv" ]
76dac2f4141c8f480370236295c07dfa52e5c589
https://github.com/polyfony-inc/polyfony/blob/76dac2f4141c8f480370236295c07dfa52e5c589/Private/Polyfony/Format.php#L216-L233
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Util/MapperUtil.php
MapperUtil.map
public static function map($json, $class, LoggerInterface $logger = null) { $mapper = new JsonMapper(); // FIX optional parameters can be null (no phpdoc NULL tag needed) $mapper->bStrictNullTypes = false; if (!is_object($json)) { // must set when json is assoc array $mapper->bEnforceMapType = false; } if (!empty($logger)) { $mapper->setLogger($logger); } return $mapper->map($json, new $class()); }
php
public static function map($json, $class, LoggerInterface $logger = null) { $mapper = new JsonMapper(); // FIX optional parameters can be null (no phpdoc NULL tag needed) $mapper->bStrictNullTypes = false; if (!is_object($json)) { // must set when json is assoc array $mapper->bEnforceMapType = false; } if (!empty($logger)) { $mapper->setLogger($logger); } return $mapper->map($json, new $class()); }
[ "public", "static", "function", "map", "(", "$", "json", ",", "$", "class", ",", "LoggerInterface", "$", "logger", "=", "null", ")", "{", "$", "mapper", "=", "new", "JsonMapper", "(", ")", ";", "// FIX optional parameters can be null (no phpdoc NULL tag needed)", ...
Mapping JSON string to a instance of a given class. @param array | object $json The JSON to map, either an assoc. array or object (stdClass), never a string. @param string $class The full qualified name of the class to map to. @param LoggerInterface|null $logger @return mixed The created instance, never null- @throws \Exception If the mapping could not completed.
[ "Mapping", "JSON", "string", "to", "a", "instance", "of", "a", "given", "class", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Util/MapperUtil.php#L31-L46
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Util/MapperUtil.php
MapperUtil.jsonEncode
public static function jsonEncode($object, $filter = null, $nullFilter = null) { if (!empty($filter) || !empty($nullFilter)) { $object = clone $object; $vars = get_object_vars($object); if (!empty ($filter)) { foreach ($filter as $prop) { if (array_key_exists($prop, $vars)) { unset($object->{$prop}); } } } if (!empty ($nullFilter)) { foreach ($nullFilter as $prop) { if (array_key_exists($prop, $vars) && $vars[$prop] === null) { unset($object->{$prop}); } } } } return json_encode($object); }
php
public static function jsonEncode($object, $filter = null, $nullFilter = null) { if (!empty($filter) || !empty($nullFilter)) { $object = clone $object; $vars = get_object_vars($object); if (!empty ($filter)) { foreach ($filter as $prop) { if (array_key_exists($prop, $vars)) { unset($object->{$prop}); } } } if (!empty ($nullFilter)) { foreach ($nullFilter as $prop) { if (array_key_exists($prop, $vars) && $vars[$prop] === null) { unset($object->{$prop}); } } } } return json_encode($object); }
[ "public", "static", "function", "jsonEncode", "(", "$", "object", ",", "$", "filter", "=", "null", ",", "$", "nullFilter", "=", "null", ")", "{", "if", "(", "!", "empty", "(", "$", "filter", ")", "||", "!", "empty", "(", "$", "nullFilter", ")", ")"...
Encodes the given instance to a JSON string. @param mixed $object The instance to encode. @param array|null $filter Array with properties of the given instance to filter. @param array|null $nullFilter Array with properties of the given instance to filter when null. @return string The encoded string or false on failure.
[ "Encodes", "the", "given", "instance", "to", "a", "JSON", "string", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Util/MapperUtil.php#L55-L79
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Util/MapperUtil.php
MapperUtil.mapResponse
public static function mapResponse(ResponseInterface $response, $class = null, LoggerInterface $logger = null) { $dec = self::jsonDecode((string)$response->getBody()); if ($class != null) { return self::map($dec, $class, $logger); } return $dec; }
php
public static function mapResponse(ResponseInterface $response, $class = null, LoggerInterface $logger = null) { $dec = self::jsonDecode((string)$response->getBody()); if ($class != null) { return self::map($dec, $class, $logger); } return $dec; }
[ "public", "static", "function", "mapResponse", "(", "ResponseInterface", "$", "response", ",", "$", "class", "=", "null", ",", "LoggerInterface", "$", "logger", "=", "null", ")", "{", "$", "dec", "=", "self", "::", "jsonDecode", "(", "(", "string", ")", ...
Maps a response body which contains JSON to an object of a given class or to default PHP types. @param ResponseInterface $response The response @param string $class The full qualified name of the class to map to or null to map to default types. @param LoggerInterface|null $logger @return mixed The created instance, never null. @throws \Exception If the mapping could not completed.
[ "Maps", "a", "response", "body", "which", "contains", "JSON", "to", "an", "object", "of", "a", "given", "class", "or", "to", "default", "PHP", "types", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Util/MapperUtil.php#L89-L96
train
secucard/secucard-connect-php-sdk
src/SecucardConnect/Util/MapperUtil.php
MapperUtil.jsonDecode
public static function jsonDecode($json, $assoc = false) { $data = \json_decode($json, $assoc); if (JSON_ERROR_NONE !== json_last_error()) { $last = json_last_error(); throw new \InvalidArgumentException( 'Unable to parse JSON data: ' . (isset(self::$jsonErrors[$last]) ? self::$jsonErrors[$last] : 'Unknown error') ); } return $data; }
php
public static function jsonDecode($json, $assoc = false) { $data = \json_decode($json, $assoc); if (JSON_ERROR_NONE !== json_last_error()) { $last = json_last_error(); throw new \InvalidArgumentException( 'Unable to parse JSON data: ' . (isset(self::$jsonErrors[$last]) ? self::$jsonErrors[$last] : 'Unknown error') ); } return $data; }
[ "public", "static", "function", "jsonDecode", "(", "$", "json", ",", "$", "assoc", "=", "false", ")", "{", "$", "data", "=", "\\", "json_decode", "(", "$", "json", ",", "$", "assoc", ")", ";", "if", "(", "JSON_ERROR_NONE", "!==", "json_last_error", "("...
Decodes an JSON string into a object with properties of standard PHP types, including stdClass or assoc array. @param string $json The string to decode. @param boolean $assoc If true a assoc array is returned. @return mixed The created object, never null or other.
[ "Decodes", "an", "JSON", "string", "into", "a", "object", "with", "properties", "of", "standard", "PHP", "types", "including", "stdClass", "or", "assoc", "array", "." ]
d990686095e4e02d0924fc12b9bf60140fe8efab
https://github.com/secucard/secucard-connect-php-sdk/blob/d990686095e4e02d0924fc12b9bf60140fe8efab/src/SecucardConnect/Util/MapperUtil.php#L104-L117
train
diff-sniffer/core
src/ProjectLoader.php
ProjectLoader.registerClassLoader
public function registerClassLoader() : void { if ($this->root === null) { return; } $path = sprintf('%s/%s/autoload.php', $this->root, $this->getVendorDirectory()); if (!is_file($path)) { return; } require $path; }
php
public function registerClassLoader() : void { if ($this->root === null) { return; } $path = sprintf('%s/%s/autoload.php', $this->root, $this->getVendorDirectory()); if (!is_file($path)) { return; } require $path; }
[ "public", "function", "registerClassLoader", "(", ")", ":", "void", "{", "if", "(", "$", "this", "->", "root", "===", "null", ")", "{", "return", ";", "}", "$", "path", "=", "sprintf", "(", "'%s/%s/autoload.php'", ",", "$", "this", "->", "root", ",", ...
Registers class loader if it's defined in the project
[ "Registers", "class", "loader", "if", "it", "s", "defined", "in", "the", "project" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/ProjectLoader.php#L64-L77
train
diff-sniffer/core
src/ProjectLoader.php
ProjectLoader.findProjectRoot
private function findProjectRoot(string $dir) : ?string { do { $path = $dir . '/composer.json'; if (file_exists($path)) { return $dir; } $prev = $dir; $dir = dirname($dir); } while ($dir !== $prev); return null; }
php
private function findProjectRoot(string $dir) : ?string { do { $path = $dir . '/composer.json'; if (file_exists($path)) { return $dir; } $prev = $dir; $dir = dirname($dir); } while ($dir !== $prev); return null; }
[ "private", "function", "findProjectRoot", "(", "string", "$", "dir", ")", ":", "?", "string", "{", "do", "{", "$", "path", "=", "$", "dir", ".", "'/composer.json'", ";", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "return", "$", "dir",...
Finds project root by locating composer.json located in the current working directory or its closest parent @param string $dir Current working directory @return string|null
[ "Finds", "project", "root", "by", "locating", "composer", ".", "json", "located", "in", "the", "current", "working", "directory", "or", "its", "closest", "parent" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/ProjectLoader.php#L85-L99
train
diff-sniffer/core
src/ProjectLoader.php
ProjectLoader.loadComposerConfiguration
private function loadComposerConfiguration() : array { $contents = file_get_contents($this->root . '/composer.json'); $config = json_decode($contents, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new RuntimeException(json_last_error_msg()); } return $config; }
php
private function loadComposerConfiguration() : array { $contents = file_get_contents($this->root . '/composer.json'); $config = json_decode($contents, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new RuntimeException(json_last_error_msg()); } return $config; }
[ "private", "function", "loadComposerConfiguration", "(", ")", ":", "array", "{", "$", "contents", "=", "file_get_contents", "(", "$", "this", "->", "root", ".", "'/composer.json'", ")", ";", "$", "config", "=", "json_decode", "(", "$", "contents", ",", "true...
Loads composer configuration from the given file @return array Configuration parameters
[ "Loads", "composer", "configuration", "from", "the", "given", "file" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/ProjectLoader.php#L121-L131
train
diff-sniffer/core
src/ProjectLoader.php
ProjectLoader.massageConfig
private function massageConfig(array $config, string $configPath) : array { if (!isset($config['installed_paths'])) { return $config; } $config['installed_paths'] = implode(',', array_map(function ($path) use ($configPath) { return dirname($configPath) . '/' . $path; }, explode(',', $config['installed_paths']))); return $config; }
php
private function massageConfig(array $config, string $configPath) : array { if (!isset($config['installed_paths'])) { return $config; } $config['installed_paths'] = implode(',', array_map(function ($path) use ($configPath) { return dirname($configPath) . '/' . $path; }, explode(',', $config['installed_paths']))); return $config; }
[ "private", "function", "massageConfig", "(", "array", "$", "config", ",", "string", "$", "configPath", ")", ":", "array", "{", "if", "(", "!", "isset", "(", "$", "config", "[", "'installed_paths'", "]", ")", ")", "{", "return", "$", "config", ";", "}",...
Resolves relative installed paths against the configuration file path @param array $config Configuration parameters @param string $configPath Configuration file paths @return array Configuration parameters
[ "Resolves", "relative", "installed", "paths", "against", "the", "configuration", "file", "path" ]
583369a5f5c91496862f6bdf60b69565da4bc05d
https://github.com/diff-sniffer/core/blob/583369a5f5c91496862f6bdf60b69565da4bc05d/src/ProjectLoader.php#L155-L166
train
ventoviro/windwalker-core
src/Core/Form/AbstractFieldDefinition.php
AbstractFieldDefinition.define
public function define(Form $form) { $this->namespaces = new PriorityQueue(); $this->namespaces->insert('Windwalker\Form\Field', PriorityQueue::NORMAL); $this->bootTraits($this); $this->form = $form; $this->doDefine($form); }
php
public function define(Form $form) { $this->namespaces = new PriorityQueue(); $this->namespaces->insert('Windwalker\Form\Field', PriorityQueue::NORMAL); $this->bootTraits($this); $this->form = $form; $this->doDefine($form); }
[ "public", "function", "define", "(", "Form", "$", "form", ")", "{", "$", "this", "->", "namespaces", "=", "new", "PriorityQueue", "(", ")", ";", "$", "this", "->", "namespaces", "->", "insert", "(", "'Windwalker\\Form\\Field'", ",", "PriorityQueue", "::", ...
Define the form fields. @param Form $form The Windwalker form object. @return void
[ "Define", "the", "form", "fields", "." ]
0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074
https://github.com/ventoviro/windwalker-core/blob/0ed53059fc2d5d2d9b72f0e4aeef2fdf6aac0074/src/Core/Form/AbstractFieldDefinition.php#L99-L109
train
elvetemedve/behat-screenshot
src/Bex/Behat/ScreenshotExtension/Service/ScreenshotTaker.php
ScreenshotTaker.takeScreenshot
public function takeScreenshot() { try { $this->screenshots[] = $this->mink->getSession()->getScreenshot(); } catch (UnsupportedDriverActionException $e) { return; } catch (\Exception $e) { $this->output->writeln($e->getMessage()); } }
php
public function takeScreenshot() { try { $this->screenshots[] = $this->mink->getSession()->getScreenshot(); } catch (UnsupportedDriverActionException $e) { return; } catch (\Exception $e) { $this->output->writeln($e->getMessage()); } }
[ "public", "function", "takeScreenshot", "(", ")", "{", "try", "{", "$", "this", "->", "screenshots", "[", "]", "=", "$", "this", "->", "mink", "->", "getSession", "(", ")", "->", "getScreenshot", "(", ")", ";", "}", "catch", "(", "UnsupportedDriverAction...
Save the screenshot into a local buffer
[ "Save", "the", "screenshot", "into", "a", "local", "buffer" ]
9860b8d825dab027d0fc975914131fc758561674
https://github.com/elvetemedve/behat-screenshot/blob/9860b8d825dab027d0fc975914131fc758561674/src/Bex/Behat/ScreenshotExtension/Service/ScreenshotTaker.php#L50-L59
train
elvetemedve/behat-screenshot
src/Bex/Behat/ScreenshotExtension/Listener/ScreenshotListener.php
ScreenshotListener.saveScreenshot
public function saveScreenshot(AfterScenarioTested $event) { if ($this->shouldSaveScreenshot($event)) { $fileName = $this->filenameGenerator->generateFileName($event->getFeature(), $event->getScenario()); $image = $this->screenshotTaker->getImage(); $this->screenshotUploader->upload($image, $fileName); } $this->screenshotTaker->reset(); }
php
public function saveScreenshot(AfterScenarioTested $event) { if ($this->shouldSaveScreenshot($event)) { $fileName = $this->filenameGenerator->generateFileName($event->getFeature(), $event->getScenario()); $image = $this->screenshotTaker->getImage(); $this->screenshotUploader->upload($image, $fileName); } $this->screenshotTaker->reset(); }
[ "public", "function", "saveScreenshot", "(", "AfterScenarioTested", "$", "event", ")", "{", "if", "(", "$", "this", "->", "shouldSaveScreenshot", "(", "$", "event", ")", ")", "{", "$", "fileName", "=", "$", "this", "->", "filenameGenerator", "->", "generateF...
Save screenshot after scanerio if required @param AfterScenarioTested $event
[ "Save", "screenshot", "after", "scanerio", "if", "required" ]
9860b8d825dab027d0fc975914131fc758561674
https://github.com/elvetemedve/behat-screenshot/blob/9860b8d825dab027d0fc975914131fc758561674/src/Bex/Behat/ScreenshotExtension/Listener/ScreenshotListener.php#L92-L101
train
elvetemedve/behat-screenshot
src/Bex/Behat/ScreenshotExtension/Output/IndentedOutput.php
IndentedOutput.setFormatter
public function setFormatter(\Symfony\Component\Console\Formatter\OutputFormatterInterface $formatter) { $this->decoratedOutput->setFormatter($formatter); }
php
public function setFormatter(\Symfony\Component\Console\Formatter\OutputFormatterInterface $formatter) { $this->decoratedOutput->setFormatter($formatter); }
[ "public", "function", "setFormatter", "(", "\\", "Symfony", "\\", "Component", "\\", "Console", "\\", "Formatter", "\\", "OutputFormatterInterface", "$", "formatter", ")", "{", "$", "this", "->", "decoratedOutput", "->", "setFormatter", "(", "$", "formatter", ")...
Sets output formatter. @param \Symfony\Component\Console\Formatter\OutputFormatterInterface $formatter
[ "Sets", "output", "formatter", "." ]
9860b8d825dab027d0fc975914131fc758561674
https://github.com/elvetemedve/behat-screenshot/blob/9860b8d825dab027d0fc975914131fc758561674/src/Bex/Behat/ScreenshotExtension/Output/IndentedOutput.php#L160-L163
train
elvetemedve/behat-screenshot
src/Bex/Behat/ScreenshotExtension/Output/IndentedOutput.php
IndentedOutput.addIndentationToMessages
private function addIndentationToMessages($messages) { if (is_array($messages)) { array_walk( $messages, function ($message) { return $this->indentation . $message; } ); return $messages; } else { $messages = $this->indentation . $messages; return $messages; } }
php
private function addIndentationToMessages($messages) { if (is_array($messages)) { array_walk( $messages, function ($message) { return $this->indentation . $message; } ); return $messages; } else { $messages = $this->indentation . $messages; return $messages; } }
[ "private", "function", "addIndentationToMessages", "(", "$", "messages", ")", "{", "if", "(", "is_array", "(", "$", "messages", ")", ")", "{", "array_walk", "(", "$", "messages", ",", "function", "(", "$", "message", ")", "{", "return", "$", "this", "->"...
Prepend message with padding @param $messages @return array|string
[ "Prepend", "message", "with", "padding" ]
9860b8d825dab027d0fc975914131fc758561674
https://github.com/elvetemedve/behat-screenshot/blob/9860b8d825dab027d0fc975914131fc758561674/src/Bex/Behat/ScreenshotExtension/Output/IndentedOutput.php#L182-L196
train
elvetemedve/behat-screenshot
src/Bex/Behat/ScreenshotExtension/ServiceContainer/Config.php
Config.loadServices
public function loadServices(ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/config')); $loader->load('services.xml'); $this->imageDrivers = $this->driverLocator->findDrivers( $container, $this->imageDriverKeys, $this->imageDriverConfigs ); }
php
public function loadServices(ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/config')); $loader->load('services.xml'); $this->imageDrivers = $this->driverLocator->findDrivers( $container, $this->imageDriverKeys, $this->imageDriverConfigs ); }
[ "public", "function", "loadServices", "(", "ContainerBuilder", "$", "container", ")", "{", "$", "loader", "=", "new", "XmlFileLoader", "(", "$", "container", ",", "new", "FileLocator", "(", "__DIR__", ".", "'/config'", ")", ")", ";", "$", "loader", "->", "...
Init service container and load image drivers @param ContainerBuilder $container
[ "Init", "service", "container", "and", "load", "image", "drivers" ]
9860b8d825dab027d0fc975914131fc758561674
https://github.com/elvetemedve/behat-screenshot/blob/9860b8d825dab027d0fc975914131fc758561674/src/Bex/Behat/ScreenshotExtension/ServiceContainer/Config.php#L120-L129
train
flash-global/connect-client
src/MetadataProvider.php
MetadataProvider.getSPEntityConfiguration
public function getSPEntityConfiguration($entityID) { $url = $this->buildUrl(self::API_IDP . '?entityID=' . $entityID); $request = (new RequestDescriptor()) ->setMethod('GET') ->setUrl($url); $response = $this->send($request); $extractor = (new MessageExtractor())->setHydrator(new MessageHydrator()); /** @var SignedMessageDecorator $message */ $message = $extractor->extract(\json_decode($response->getBody(), true)); return $message->getMessage(); }
php
public function getSPEntityConfiguration($entityID) { $url = $this->buildUrl(self::API_IDP . '?entityID=' . $entityID); $request = (new RequestDescriptor()) ->setMethod('GET') ->setUrl($url); $response = $this->send($request); $extractor = (new MessageExtractor())->setHydrator(new MessageHydrator()); /** @var SignedMessageDecorator $message */ $message = $extractor->extract(\json_decode($response->getBody(), true)); return $message->getMessage(); }
[ "public", "function", "getSPEntityConfiguration", "(", "$", "entityID", ")", "{", "$", "url", "=", "$", "this", "->", "buildUrl", "(", "self", "::", "API_IDP", ".", "'?entityID='", ".", "$", "entityID", ")", ";", "$", "request", "=", "(", "new", "Request...
Get the SP entity configuration from Connect IdP @param string $entityID @return SpEntityConfigurationMessage
[ "Get", "the", "SP", "entity", "configuration", "from", "Connect", "IdP" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/MetadataProvider.php#L86-L102
train
flash-global/connect-client
src/Config/ConfigConsistency.php
ConfigConsistency.createRSAPrivateKey
public function createRSAPrivateKey() { $path = $this->getConfig()->getPrivateKeyFilePath(); $this->createDir($path); $this->getConfig()->setPrivateKey((new RsaKeyGen())->createPrivateKey()); if (@file_put_contents($path, $this->getConfig()->getPrivateKey()) === false) { throw new \Exception('Error when writing the RSA private key'); } }
php
public function createRSAPrivateKey() { $path = $this->getConfig()->getPrivateKeyFilePath(); $this->createDir($path); $this->getConfig()->setPrivateKey((new RsaKeyGen())->createPrivateKey()); if (@file_put_contents($path, $this->getConfig()->getPrivateKey()) === false) { throw new \Exception('Error when writing the RSA private key'); } }
[ "public", "function", "createRSAPrivateKey", "(", ")", "{", "$", "path", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getPrivateKeyFilePath", "(", ")", ";", "$", "this", "->", "createDir", "(", "$", "path", ")", ";", "$", "this", "->", "getCon...
Create and write the RSA private file @throws \Exception
[ "Create", "and", "write", "the", "RSA", "private", "file" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Config/ConfigConsistency.php#L107-L116
train
flash-global/connect-client
src/Config/ConfigConsistency.php
ConfigConsistency.createIdpMetadataFile
protected function createIdpMetadataFile() { $url = $this->getConfig()->getIdpEntityID() . $this->getConfig()->getIdpMetadataFileTarget(); try { $idp = file_get_contents($url); $path = $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getIdpMetadataFile(); $this->createDir($path); if (@file_put_contents($path, $idp) === false) { throw new \Exception(sprintf('Unable to write IdP Metadata on %s', $path)); } } catch (\Exception $e) { throw new \Exception(sprintf('Unable to fetch IdP Metadata on %s', $url)); } }
php
protected function createIdpMetadataFile() { $url = $this->getConfig()->getIdpEntityID() . $this->getConfig()->getIdpMetadataFileTarget(); try { $idp = file_get_contents($url); $path = $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getIdpMetadataFile(); $this->createDir($path); if (@file_put_contents($path, $idp) === false) { throw new \Exception(sprintf('Unable to write IdP Metadata on %s', $path)); } } catch (\Exception $e) { throw new \Exception(sprintf('Unable to fetch IdP Metadata on %s', $url)); } }
[ "protected", "function", "createIdpMetadataFile", "(", ")", "{", "$", "url", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getIdpEntityID", "(", ")", ".", "$", "this", "->", "getConfig", "(", ")", "->", "getIdpMetadataFileTarget", "(", ")", ";", ...
Create and write the IdP metadata XML file @throws \Exception
[ "Create", "and", "write", "the", "IdP", "metadata", "XML", "file" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Config/ConfigConsistency.php#L123-L138
train
flash-global/connect-client
src/Config/ConfigConsistency.php
ConfigConsistency.createSpMetadataFile
protected function createSpMetadataFile() { $url = $this->getConfig()->getIdpEntityID(); $entityID = $this->getConfig()->getEntityID(); $metadataProvider = new MetadataProvider([MetadataProvider::OPTION_BASEURL => $url]); try { $message = $metadataProvider->getSPEntityConfiguration($entityID); } catch (\Exception $e) { $message = new SpEntityConfigurationMessage(); } if (empty($message->getXml())) { if (!$message->getId()) { if (!$this->validateIdpMetadata()) { throw new \Exception('Unable to send registration request due to not found IdP metadata file'); } $idp = (new Metadata())->createEntityDescriptor( file_get_contents( $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getIdpMetadataFile() ) )->getFirstIdpSsoDescriptor(); $metadataProvider->subscribeApplication($this->getConfig(), $idp); } return false; } $path = $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getSpMetadataFile(); $this->createDir($path); if (@file_put_contents($path, $message->getXml()) === false) { throw new \Exception('Error in Sp MetadataFile writing'); } return true; }
php
protected function createSpMetadataFile() { $url = $this->getConfig()->getIdpEntityID(); $entityID = $this->getConfig()->getEntityID(); $metadataProvider = new MetadataProvider([MetadataProvider::OPTION_BASEURL => $url]); try { $message = $metadataProvider->getSPEntityConfiguration($entityID); } catch (\Exception $e) { $message = new SpEntityConfigurationMessage(); } if (empty($message->getXml())) { if (!$message->getId()) { if (!$this->validateIdpMetadata()) { throw new \Exception('Unable to send registration request due to not found IdP metadata file'); } $idp = (new Metadata())->createEntityDescriptor( file_get_contents( $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getIdpMetadataFile() ) )->getFirstIdpSsoDescriptor(); $metadataProvider->subscribeApplication($this->getConfig(), $idp); } return false; } $path = $this->getConfig()->getSamlMetadataBaseDir() . '/' . $this->getConfig()->getSpMetadataFile(); $this->createDir($path); if (@file_put_contents($path, $message->getXml()) === false) { throw new \Exception('Error in Sp MetadataFile writing'); } return true; }
[ "protected", "function", "createSpMetadataFile", "(", ")", "{", "$", "url", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getIdpEntityID", "(", ")", ";", "$", "entityID", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getEntityID", "(", ...
Create and write the SP metadata XML file @throws \Exception
[ "Create", "and", "write", "the", "SP", "metadata", "XML", "file" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Config/ConfigConsistency.php#L145-L184
train
flash-global/connect-client
src/Exception/PingException.php
PingException.getResponse
public function getResponse() { $response = new Response(); $message = new Message(); $message->setData(['message' => $this->getMessage()]); if (!empty($this->getPrivateKey())) { $message->setCertificate($this->getCertificate()); $message->sign($this->getPrivateKey()); } $response->getBody()->write(json_encode($message)); return $response ->withStatus($this->getCode()) ->withAddedHeader('Content-Type', 'application/json'); }
php
public function getResponse() { $response = new Response(); $message = new Message(); $message->setData(['message' => $this->getMessage()]); if (!empty($this->getPrivateKey())) { $message->setCertificate($this->getCertificate()); $message->sign($this->getPrivateKey()); } $response->getBody()->write(json_encode($message)); return $response ->withStatus($this->getCode()) ->withAddedHeader('Content-Type', 'application/json'); }
[ "public", "function", "getResponse", "(", ")", "{", "$", "response", "=", "new", "Response", "(", ")", ";", "$", "message", "=", "new", "Message", "(", ")", ";", "$", "message", "->", "setData", "(", "[", "'message'", "=>", "$", "this", "->", "getMes...
Returns a ResponseInterface method @return \Psr\Http\Message\ResponseInterface
[ "Returns", "a", "ResponseInterface", "method" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Exception/PingException.php#L79-L96
train
flash-global/connect-client
src/Config/Config.php
Config.registerProfileAssociation
public function registerProfileAssociation( callable $callback, $profileAssociationPath = '/connect/profile-association' ) { $this->profileAssociationCallback = $callback; $this->profileAssociationPath = $profileAssociationPath; return $this; }
php
public function registerProfileAssociation( callable $callback, $profileAssociationPath = '/connect/profile-association' ) { $this->profileAssociationCallback = $callback; $this->profileAssociationPath = $profileAssociationPath; return $this; }
[ "public", "function", "registerProfileAssociation", "(", "callable", "$", "callback", ",", "$", "profileAssociationPath", "=", "'/connect/profile-association'", ")", "{", "$", "this", "->", "profileAssociationCallback", "=", "$", "callback", ";", "$", "this", "->", ...
Register a profile association callback @param callable $callback @param string $profileAssociationPath @return $this
[ "Register", "a", "profile", "association", "callback" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Config/Config.php#L345-L353
train
flash-global/connect-client
src/Metadata.php
Metadata.load
public static function load($idpMetadataFilePath, $spMetadataFilePath) { $metadata = (new static()); return $metadata ->setIdentityProvider($metadata->createEntityDescriptor(file_get_contents($idpMetadataFilePath))) ->setServiceProvider($metadata->createEntityDescriptor(file_get_contents($spMetadataFilePath))); }
php
public static function load($idpMetadataFilePath, $spMetadataFilePath) { $metadata = (new static()); return $metadata ->setIdentityProvider($metadata->createEntityDescriptor(file_get_contents($idpMetadataFilePath))) ->setServiceProvider($metadata->createEntityDescriptor(file_get_contents($spMetadataFilePath))); }
[ "public", "static", "function", "load", "(", "$", "idpMetadataFilePath", ",", "$", "spMetadataFilePath", ")", "{", "$", "metadata", "=", "(", "new", "static", "(", ")", ")", ";", "return", "$", "metadata", "->", "setIdentityProvider", "(", "$", "metadata", ...
Create an instance of Metadata @param string $idpMetadataFilePath @param string $spMetadataFilePath @return Metadata
[ "Create", "an", "instance", "of", "Metadata" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Metadata.php#L33-L40
train
flash-global/connect-client
src/Metadata.php
Metadata.createEntityDescriptor
public function createEntityDescriptor($xml) { $deserializationContext = new DeserializationContext(); $deserializationContext->getDocument()->loadXML($xml); $ed = new EntityDescriptor(); $ed->deserialize($deserializationContext->getDocument(), $deserializationContext); return $ed; }
php
public function createEntityDescriptor($xml) { $deserializationContext = new DeserializationContext(); $deserializationContext->getDocument()->loadXML($xml); $ed = new EntityDescriptor(); $ed->deserialize($deserializationContext->getDocument(), $deserializationContext); return $ed; }
[ "public", "function", "createEntityDescriptor", "(", "$", "xml", ")", "{", "$", "deserializationContext", "=", "new", "DeserializationContext", "(", ")", ";", "$", "deserializationContext", "->", "getDocument", "(", ")", "->", "loadXML", "(", "$", "xml", ")", ...
Create an EntityDescriptor instance with its XML metadata contents @param string $xml @return EntityDescriptor
[ "Create", "an", "EntityDescriptor", "instance", "with", "its", "XML", "metadata", "contents" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Metadata.php#L175-L184
train
flash-global/connect-client
src/Connect.php
Connect.handleRequest
public function handleRequest($requestUri = null, $requestMethod = null) { if (!$this->isConfigConsistent() && false) { throw new \LogicException('The client configuration is not consistent'); } $pathInfo = $requestUri; if (false !== $pos = strpos($pathInfo, '?')) { $pathInfo = substr($pathInfo, 0, $pos); } $pathInfo = rawurldecode($pathInfo); $info = $this->getDispatcher()->dispatch($requestMethod, $pathInfo); if ($info[0] == Dispatcher::FOUND) { try { $response = $info[1]($this); if ($response instanceof ResponseInterface) { $this->setResponse($response); } } catch (ResponseExceptionInterface $e) { $this->setResponse($e->getResponse()); } } elseif (!$this->isAuthenticated()) { if (strtoupper($requestMethod) == 'GET') { $_SESSION[self::class][$this->getConfig()->getEntityID()]['targeted_path'] = $requestUri; } $request = $this->getSaml()->buildAuthnRequest(); $_SESSION[self::class][$this->getConfig()->getEntityID()]['SAML_RelayState'] = $request->getRelayState(); $this->setResponse($this->getSaml()->getHttpRedirectBindingResponse($request)); } return $this; }
php
public function handleRequest($requestUri = null, $requestMethod = null) { if (!$this->isConfigConsistent() && false) { throw new \LogicException('The client configuration is not consistent'); } $pathInfo = $requestUri; if (false !== $pos = strpos($pathInfo, '?')) { $pathInfo = substr($pathInfo, 0, $pos); } $pathInfo = rawurldecode($pathInfo); $info = $this->getDispatcher()->dispatch($requestMethod, $pathInfo); if ($info[0] == Dispatcher::FOUND) { try { $response = $info[1]($this); if ($response instanceof ResponseInterface) { $this->setResponse($response); } } catch (ResponseExceptionInterface $e) { $this->setResponse($e->getResponse()); } } elseif (!$this->isAuthenticated()) { if (strtoupper($requestMethod) == 'GET') { $_SESSION[self::class][$this->getConfig()->getEntityID()]['targeted_path'] = $requestUri; } $request = $this->getSaml()->buildAuthnRequest(); $_SESSION[self::class][$this->getConfig()->getEntityID()]['SAML_RelayState'] = $request->getRelayState(); $this->setResponse($this->getSaml()->getHttpRedirectBindingResponse($request)); } return $this; }
[ "public", "function", "handleRequest", "(", "$", "requestUri", "=", "null", ",", "$", "requestMethod", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "isConfigConsistent", "(", ")", "&&", "false", ")", "{", "throw", "new", "\\", "LogicExceptio...
Handle connect request @param string $requestUri @param string $requestMethod @return $this @throws \Exception
[ "Handle", "connect", "request" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Connect.php#L373-L411
train
flash-global/connect-client
src/Connect.php
Connect.emit
public function emit() { if (headers_sent($file, $line)) { throw new \LogicException('Headers already sent in %s on line %d', $file, $line); } if ($this->getResponse()) { (new Response\SapiEmitter())->emit($this->getResponse()); exit(); } }
php
public function emit() { if (headers_sent($file, $line)) { throw new \LogicException('Headers already sent in %s on line %d', $file, $line); } if ($this->getResponse()) { (new Response\SapiEmitter())->emit($this->getResponse()); exit(); } }
[ "public", "function", "emit", "(", ")", "{", "if", "(", "headers_sent", "(", "$", "file", ",", "$", "line", ")", ")", "{", "throw", "new", "\\", "LogicException", "(", "'Headers already sent in %s on line %d'", ",", "$", "file", ",", "$", "line", ")", ";...
Emit the client response if exists and die...
[ "Emit", "the", "client", "response", "if", "exists", "and", "die", "..." ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Connect.php#L416-L426
train
flash-global/connect-client
src/Connect.php
Connect.switchRole
public function switchRole($role) { if ($this->isAuthenticated()) { $entityId = $this->getConfig()->getEntityID(); try { $isRole = false; /** @var Attribution $attribution **/ foreach ($this->getUser()->getAttributions() as $attribution) { if ($attribution->getRole()->getRole() == $role && $attribution->getTarget()->getUrl() == $entityId ) { $isRole = true; } } if ($isRole) { $this->setUser($this->getUser()->setCurrentRole($role)); } else { throw new UserAttributionException('Role not found.', 400); } } catch (\Exception $e) { throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } } else { throw new UserAttributionException('User not found.', 400); } }
php
public function switchRole($role) { if ($this->isAuthenticated()) { $entityId = $this->getConfig()->getEntityID(); try { $isRole = false; /** @var Attribution $attribution **/ foreach ($this->getUser()->getAttributions() as $attribution) { if ($attribution->getRole()->getRole() == $role && $attribution->getTarget()->getUrl() == $entityId ) { $isRole = true; } } if ($isRole) { $this->setUser($this->getUser()->setCurrentRole($role)); } else { throw new UserAttributionException('Role not found.', 400); } } catch (\Exception $e) { throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } } else { throw new UserAttributionException('User not found.', 400); } }
[ "public", "function", "switchRole", "(", "$", "role", ")", "{", "if", "(", "$", "this", "->", "isAuthenticated", "(", ")", ")", "{", "$", "entityId", "=", "$", "this", "->", "getConfig", "(", ")", "->", "getEntityID", "(", ")", ";", "try", "{", "$"...
Switch the User role @param string $role
[ "Switch", "the", "User", "role" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Connect.php#L481-L509
train
flash-global/connect-client
src/Connect.php
Connect.switchLocalUsername
public function switchLocalUsername($localUsername, $role, $application = null) { if ($this->isAuthenticated()) { // If no Application, get current Application if (!$application) { $application = $this->getConfig()->getEntityID(); } try { $switchedRole = null; /** @var Attribution $attribution **/ foreach ($this->getUser()->getAttributions() as $attribution) { $pattern = '/:' . $role . ':' . $localUsername . '/'; if ($application == $attribution->getTarget()->getUrl() && preg_match($pattern, $attribution->getRole()->getRole()) ) { $switchedRole = $attribution->getRole(); } } if ($switchedRole) { $roles = explode(':', $switchedRole->getRole()); if (count($roles) == 3) { $role = $roles[1]; $this->getUser()->setCurrentRole($role); $this->getUser()->setLocalUsername($roles[2]); $this->setUser($this->getUser()); } else { $this->setUser($this->getUser()->setCurrentRole($switchedRole->getRole())); } } else { throw new UserAttributionException('Role not found.', 400); } } catch (\Exception $e) { throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } } else { throw new UserAttributionException('User not found.', 400); } }
php
public function switchLocalUsername($localUsername, $role, $application = null) { if ($this->isAuthenticated()) { // If no Application, get current Application if (!$application) { $application = $this->getConfig()->getEntityID(); } try { $switchedRole = null; /** @var Attribution $attribution **/ foreach ($this->getUser()->getAttributions() as $attribution) { $pattern = '/:' . $role . ':' . $localUsername . '/'; if ($application == $attribution->getTarget()->getUrl() && preg_match($pattern, $attribution->getRole()->getRole()) ) { $switchedRole = $attribution->getRole(); } } if ($switchedRole) { $roles = explode(':', $switchedRole->getRole()); if (count($roles) == 3) { $role = $roles[1]; $this->getUser()->setCurrentRole($role); $this->getUser()->setLocalUsername($roles[2]); $this->setUser($this->getUser()); } else { $this->setUser($this->getUser()->setCurrentRole($switchedRole->getRole())); } } else { throw new UserAttributionException('Role not found.', 400); } } catch (\Exception $e) { throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } } else { throw new UserAttributionException('User not found.', 400); } }
[ "public", "function", "switchLocalUsername", "(", "$", "localUsername", ",", "$", "role", ",", "$", "application", "=", "null", ")", "{", "if", "(", "$", "this", "->", "isAuthenticated", "(", ")", ")", "{", "// If no Application, get current Application", "if", ...
Switch the User role by localUsername @param string $localUsername @param string $role @param null $application
[ "Switch", "the", "User", "role", "by", "localUsername" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Connect.php#L518-L559
train
flash-global/connect-client
src/Exception/SamlException.php
SamlException.getContent
protected function getContent() { $response = new SamlResponse(); $response->setStatus(new Status(new StatusCode($this->status))); $context = new SerializationContext(); $response->serialize($context->getDocument(), $context); return $context->getDocument()->saveXML(); }
php
protected function getContent() { $response = new SamlResponse(); $response->setStatus(new Status(new StatusCode($this->status))); $context = new SerializationContext(); $response->serialize($context->getDocument(), $context); return $context->getDocument()->saveXML(); }
[ "protected", "function", "getContent", "(", ")", "{", "$", "response", "=", "new", "SamlResponse", "(", ")", ";", "$", "response", "->", "setStatus", "(", "new", "Status", "(", "new", "StatusCode", "(", "$", "this", "->", "status", ")", ")", ")", ";", ...
Returns the Saml error reporting @return string
[ "Returns", "the", "Saml", "error", "reporting" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Exception/SamlException.php#L53-L62
train
flash-global/connect-client
src/UserAttribution.php
UserAttribution.add
public function add($sourceId, $targetId, $roleId) { $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(self::IDP_ATTRIBUTIONS_API)) ->setMethod('POST'); $request->setBodyParams([ 'data' => json_encode([ 'source_id' => $sourceId, 'target_id' => $targetId, 'role_id' => $roleId, ]) ]); try { $response = json_decode($this->send($request)->getBody(), true); return (count($response['added']) > 0 ? reset($response['added']) : null); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function add($sourceId, $targetId, $roleId) { $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(self::IDP_ATTRIBUTIONS_API)) ->setMethod('POST'); $request->setBodyParams([ 'data' => json_encode([ 'source_id' => $sourceId, 'target_id' => $targetId, 'role_id' => $roleId, ]) ]); try { $response = json_decode($this->send($request)->getBody(), true); return (count($response['added']) > 0 ? reset($response['added']) : null); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "add", "(", "$", "sourceId", ",", "$", "targetId", ",", "$", "roleId", ")", "{", "$", "request", "=", "(", "new", "RequestDescriptor", "(", ")", ")", "->", "setUrl", "(", "$", "this", "->", "buildUrl", "(", "self", "::", "IDP_AT...
Add an Attribution @param int $sourceId @param int $targetId @param int $roleId @return Attribution|null
[ "Add", "an", "Attribution" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/UserAttribution.php#L47-L75
train
flash-global/connect-client
src/UserAttribution.php
UserAttribution.get
public function get($sourceId, $targetId = null) { $url = self::IDP_ATTRIBUTIONS_API . '/' . $sourceId; if ($targetId) { $url .= '?target=' . urlencode($targetId); } $request = (new RequestDescriptor()) ->setUrl($this->buildUrl($url)) ->setMethod('GET'); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function get($sourceId, $targetId = null) { $url = self::IDP_ATTRIBUTIONS_API . '/' . $sourceId; if ($targetId) { $url .= '?target=' . urlencode($targetId); } $request = (new RequestDescriptor()) ->setUrl($this->buildUrl($url)) ->setMethod('GET'); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "get", "(", "$", "sourceId", ",", "$", "targetId", "=", "null", ")", "{", "$", "url", "=", "self", "::", "IDP_ATTRIBUTIONS_API", ".", "'/'", ".", "$", "sourceId", ";", "if", "(", "$", "targetId", ")", "{", "$", "url", ".=", "'...
Get an User Attributions @param int $sourceId @param int|null $targetId @return Attribution[]
[ "Get", "an", "User", "Attributions" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/UserAttribution.php#L85-L109
train
flash-global/connect-client
src/UserAttribution.php
UserAttribution.remove
public function remove($sourceId, $targetId = null, $roleId = null) { $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(self::IDP_ATTRIBUTIONS_API)) ->setMethod('DELETE') ->setRawData(json_encode([ 'source_id' => $sourceId, 'target_id' => $targetId, 'role_id' => $roleId, ])); try { $this->send($request); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function remove($sourceId, $targetId = null, $roleId = null) { $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(self::IDP_ATTRIBUTIONS_API)) ->setMethod('DELETE') ->setRawData(json_encode([ 'source_id' => $sourceId, 'target_id' => $targetId, 'role_id' => $roleId, ])); try { $this->send($request); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(), true); throw new UserAttributionException($error['error'], $error['code'], $previous); } throw new UserAttributionException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "remove", "(", "$", "sourceId", ",", "$", "targetId", "=", "null", ",", "$", "roleId", "=", "null", ")", "{", "$", "request", "=", "(", "new", "RequestDescriptor", "(", ")", ")", "->", "setUrl", "(", "$", "this", "->", "buildUrl...
Remove attributions for a user. An application and a role can be defined to target more attributions more precisely. @param int $sourceId @param int $targetId @param int $roleId If omitted, all attributions link to this source / target will be deleted.
[ "Remove", "attributions", "for", "a", "user", ".", "An", "application", "and", "a", "role", "can", "be", "defined", "to", "target", "more", "attributions", "more", "precisely", "." ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/UserAttribution.php#L120-L144
train
flash-global/connect-client
src/Handler/RegisterAdminHandler.php
RegisterAdminHandler.generateXml
protected function generateXml(Connect $connect, $privateKey, $data) { $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey); $certificate = new X509Certificate(); $certificate->loadPem($certificateGen); $builder = new MetadataBuilder(); $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate); $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile(); file_put_contents($path, $xml); $message = (new SpEntityConfigurationMessage()) ->setXml($xml); $message = (new SignedMessageDecorator($message)) ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey)) ->sign($privateKey); $certificate = $connect->getSaml() ->getMetadata() ->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ->getCertificate() ->toPem(); return (new MessageResponse($message))->buildEncrypted($certificate); }
php
protected function generateXml(Connect $connect, $privateKey, $data) { $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey); $certificate = new X509Certificate(); $certificate->loadPem($certificateGen); $builder = new MetadataBuilder(); $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate); $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile(); file_put_contents($path, $xml); $message = (new SpEntityConfigurationMessage()) ->setXml($xml); $message = (new SignedMessageDecorator($message)) ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey)) ->sign($privateKey); $certificate = $connect->getSaml() ->getMetadata() ->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ->getCertificate() ->toPem(); return (new MessageResponse($message))->buildEncrypted($certificate); }
[ "protected", "function", "generateXml", "(", "Connect", "$", "connect", ",", "$", "privateKey", ",", "$", "data", ")", "{", "$", "certificateGen", "=", "(", "new", "X509CertificateGen", "(", ")", ")", "->", "createX509Certificate", "(", "$", "privateKey", ")...
Generate the SP metadata XML file @param Connect $connect @param string $privateKey @param array $data @return MessageResponse
[ "Generate", "the", "SP", "metadata", "XML", "file" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Handler/RegisterAdminHandler.php#L84-L112
train
flash-global/connect-client
src/UserAdmin.php
UserAdmin.fetchCertificate
protected function fetchCertificate() { $metadata = file_get_contents($this->getBaseUrl() . $this->getAdminSpMetadataFile()); $deserializationContext = new DeserializationContext(); $deserializationContext->getDocument()->loadXML($metadata); $ed = new EntityDescriptor(); $ed->deserialize($deserializationContext->getDocument(), $deserializationContext); $certificate = $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ? $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ->getCertificate() ->toPem() : $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ->toPem(); return $certificate; }
php
protected function fetchCertificate() { $metadata = file_get_contents($this->getBaseUrl() . $this->getAdminSpMetadataFile()); $deserializationContext = new DeserializationContext(); $deserializationContext->getDocument()->loadXML($metadata); $ed = new EntityDescriptor(); $ed->deserialize($deserializationContext->getDocument(), $deserializationContext); $certificate = $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ? $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION) ->getCertificate() ->toPem() : $ed->getFirstSpSsoDescriptor()->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ->toPem(); return $certificate; }
[ "protected", "function", "fetchCertificate", "(", ")", "{", "$", "metadata", "=", "file_get_contents", "(", "$", "this", "->", "getBaseUrl", "(", ")", ".", "$", "this", "->", "getAdminSpMetadataFile", "(", ")", ")", ";", "$", "deserializationContext", "=", "...
Fetch Connect Admin SP metadata an return encryption certificate @return string
[ "Fetch", "Connect", "Admin", "SP", "metadata", "an", "return", "encryption", "certificate" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/UserAdmin.php#L316-L335
train
flash-global/connect-client
src/UserAdmin.php
UserAdmin.createToken
protected function createToken() { $token = $this->getToken()->createApplicationToken( $this->connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID(), $this->connect->getSaml()->getPrivateKey() ); return $token['token']; }
php
protected function createToken() { $token = $this->getToken()->createApplicationToken( $this->connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID(), $this->connect->getSaml()->getPrivateKey() ); return $token['token']; }
[ "protected", "function", "createToken", "(", ")", "{", "$", "token", "=", "$", "this", "->", "getToken", "(", ")", "->", "createApplicationToken", "(", "$", "this", "->", "connect", "->", "getSaml", "(", ")", "->", "getMetadata", "(", ")", "->", "getServ...
Get a token @return string
[ "Get", "a", "token" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/UserAdmin.php#L342-L349
train
flash-global/connect-client
src/MetadataBuilder.php
MetadataBuilder.build
public function build($entityID, $acs, $logout, $certificate) { $entityDescriptor = (new EntityDescriptor()) ->setEntityID($entityID) ->setID(Helper::generateID()); $spSsoDescriptor = (new SpSsoDescriptor()) ->addKeyDescriptor( (new KeyDescriptor()) ->setUse(KeyDescriptor::USE_SIGNING) ->setCertificate($certificate) ) ->addKeyDescriptor( (new KeyDescriptor()) ->setUse(KeyDescriptor::USE_ENCRYPTION) ->setCertificate($certificate) ) ->setWantAssertionsSigned(true) ->setAuthnRequestsSigned(true) ->addSingleLogoutService( $logout = (new SingleLogoutService()) ->setBinding(SamlConstants::BINDING_SAML2_HTTP_REDIRECT) ->setLocation($logout) ) ->addAssertionConsumerService( $acs = (new AssertionConsumerService()) ->setBinding(SamlConstants::BINDING_SAML2_HTTP_POST) ->setLocation($acs) ); $entityDescriptor->addItem($spSsoDescriptor); $serializationContext = new SerializationContext(); $entityDescriptor->serialize($serializationContext->getDocument(), $serializationContext); $data = $serializationContext->getDocument()->saveXML(); return $data; }
php
public function build($entityID, $acs, $logout, $certificate) { $entityDescriptor = (new EntityDescriptor()) ->setEntityID($entityID) ->setID(Helper::generateID()); $spSsoDescriptor = (new SpSsoDescriptor()) ->addKeyDescriptor( (new KeyDescriptor()) ->setUse(KeyDescriptor::USE_SIGNING) ->setCertificate($certificate) ) ->addKeyDescriptor( (new KeyDescriptor()) ->setUse(KeyDescriptor::USE_ENCRYPTION) ->setCertificate($certificate) ) ->setWantAssertionsSigned(true) ->setAuthnRequestsSigned(true) ->addSingleLogoutService( $logout = (new SingleLogoutService()) ->setBinding(SamlConstants::BINDING_SAML2_HTTP_REDIRECT) ->setLocation($logout) ) ->addAssertionConsumerService( $acs = (new AssertionConsumerService()) ->setBinding(SamlConstants::BINDING_SAML2_HTTP_POST) ->setLocation($acs) ); $entityDescriptor->addItem($spSsoDescriptor); $serializationContext = new SerializationContext(); $entityDescriptor->serialize($serializationContext->getDocument(), $serializationContext); $data = $serializationContext->getDocument()->saveXML(); return $data; }
[ "public", "function", "build", "(", "$", "entityID", ",", "$", "acs", ",", "$", "logout", ",", "$", "certificate", ")", "{", "$", "entityDescriptor", "=", "(", "new", "EntityDescriptor", "(", ")", ")", "->", "setEntityID", "(", "$", "entityID", ")", "-...
Build the SP SAML metadata @param $entityID @param $acs @param $logout @param $certificate @return string
[ "Build", "the", "SP", "SAML", "metadata" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/MetadataBuilder.php#L57-L96
train
flash-global/connect-client
src/Token.php
Token.create
public function create(Connect $connect) { $tokenRequest = $this->getTokenizer()->signTokenRequest( $this->getTokenizer()->createTokenRequest( $connect->getUser(), $connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID() ), $connect->getSaml()->getPrivateKey() ); $request = (new RequestDescriptor()) ->setUrl($this->buildUrl('/api/token')) ->setMethod('POST'); $request->setBodyParams(['token-request' => json_encode($tokenRequest->toArray())]); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function create(Connect $connect) { $tokenRequest = $this->getTokenizer()->signTokenRequest( $this->getTokenizer()->createTokenRequest( $connect->getUser(), $connect->getSaml()->getMetadata()->getServiceProvider()->getEntityID() ), $connect->getSaml()->getPrivateKey() ); $request = (new RequestDescriptor()) ->setUrl($this->buildUrl('/api/token')) ->setMethod('POST'); $request->setBodyParams(['token-request' => json_encode($tokenRequest->toArray())]); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "create", "(", "Connect", "$", "connect", ")", "{", "$", "tokenRequest", "=", "$", "this", "->", "getTokenizer", "(", ")", "->", "signTokenRequest", "(", "$", "this", "->", "getTokenizer", "(", ")", "->", "createTokenRequest", "(", "$...
Create a Token @param Connect $connect @return string
[ "Create", "a", "Token" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Token.php#L101-L129
train
flash-global/connect-client
src/Token.php
Token.createApplicationToken
public function createApplicationToken($application, $privateKey) { $tokenRequest = $this->getTokenizer()->signTokenRequest( $this->getTokenizer()->createApplicationTokenRequest( $application ), $privateKey ); $request = (new RequestDescriptor()) ->setUrl($this->buildUrl('/api/token')) ->setMethod('POST'); $request->setBodyParams([ 'token-request' => json_encode($tokenRequest->toArray()) ]); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function createApplicationToken($application, $privateKey) { $tokenRequest = $this->getTokenizer()->signTokenRequest( $this->getTokenizer()->createApplicationTokenRequest( $application ), $privateKey ); $request = (new RequestDescriptor()) ->setUrl($this->buildUrl('/api/token')) ->setMethod('POST'); $request->setBodyParams([ 'token-request' => json_encode($tokenRequest->toArray()) ]); try { return json_decode($this->send($request)->getBody(), true); } catch (\Exception $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "createApplicationToken", "(", "$", "application", ",", "$", "privateKey", ")", "{", "$", "tokenRequest", "=", "$", "this", "->", "getTokenizer", "(", ")", "->", "signTokenRequest", "(", "$", "this", "->", "getTokenizer", "(", ")", "->"...
Create an application token @param string $application @param resource|string $privateKey @return string
[ "Create", "an", "application", "token" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Token.php#L139-L168
train
flash-global/connect-client
src/Token.php
Token.validate
public function validate($token) { if ($this->hasCache()) { $body = $this->getCache()->get($token); // Check if token is expired if (!is_null($body)) { $body = json_decode($body, true); if (new \DateTime($body['expire_at']) >= new \DateTime()) { return $this->buildValidationReturn($body); } else { $this->getCache()->delete($token); throw new TokenException('The provided token is expired'); } } } $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(sprintf('/api/token/validate?token=%s', (string) $token))) ->setMethod('GET'); try { $body = json_decode($this->send($request)->getBody(), true); if ($this->hasCache()) { $this->getCache()->set( $token, json_encode($body), (new \DateTime())->diff(new \DateTime($body['expire_at'])) ); } return $this->buildValidationReturn($body); } catch (ApiClientException $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
php
public function validate($token) { if ($this->hasCache()) { $body = $this->getCache()->get($token); // Check if token is expired if (!is_null($body)) { $body = json_decode($body, true); if (new \DateTime($body['expire_at']) >= new \DateTime()) { return $this->buildValidationReturn($body); } else { $this->getCache()->delete($token); throw new TokenException('The provided token is expired'); } } } $request = (new RequestDescriptor()) ->setUrl($this->buildUrl(sprintf('/api/token/validate?token=%s', (string) $token))) ->setMethod('GET'); try { $body = json_decode($this->send($request)->getBody(), true); if ($this->hasCache()) { $this->getCache()->set( $token, json_encode($body), (new \DateTime())->diff(new \DateTime($body['expire_at'])) ); } return $this->buildValidationReturn($body); } catch (ApiClientException $e) { $previous = $e->getPrevious(); if ($previous instanceof BadResponseException) { $error = json_decode($previous->getResponse()->getBody(true), true); throw new TokenException($error['error'], $error['code'], $previous); } throw new TokenException($e->getMessage(), $e->getCode(), $e->getPrevious()); } }
[ "public", "function", "validate", "(", "$", "token", ")", "{", "if", "(", "$", "this", "->", "hasCache", "(", ")", ")", "{", "$", "body", "=", "$", "this", "->", "getCache", "(", ")", "->", "get", "(", "$", "token", ")", ";", "// Check if token is ...
Validate a Token @param string $token @return array @throws ApiClientException
[ "Validate", "a", "Token" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Token.php#L179-L223
train
flash-global/connect-client
src/Token.php
Token.buildValidationReturn
protected function buildValidationReturn(array $body) { if (isset($body['user'])) { $body['user'] = new User($body['user']); } $body['application'] = new Application($body['application']); $body['expire_at'] = new \DateTime($body['expire_at']); return $body; }
php
protected function buildValidationReturn(array $body) { if (isset($body['user'])) { $body['user'] = new User($body['user']); } $body['application'] = new Application($body['application']); $body['expire_at'] = new \DateTime($body['expire_at']); return $body; }
[ "protected", "function", "buildValidationReturn", "(", "array", "$", "body", ")", "{", "if", "(", "isset", "(", "$", "body", "[", "'user'", "]", ")", ")", "{", "$", "body", "[", "'user'", "]", "=", "new", "User", "(", "$", "body", "[", "'user'", "]...
Build the validation return @param array $body @return array
[ "Build", "the", "validation", "return" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Token.php#L232-L242
train
flash-global/connect-client
src/Saml.php
Saml.buildAuthnRequest
public function buildAuthnRequest() { $authnRequest = (new AuthnRequest()) ->setAssertionConsumerServiceURL($this->getMetadata()->getFirstAcs()->getLocation()) ->setProtocolBinding($this->getMetadata()->getFirstAcs()->getBinding()) ->setID(Helper::generateID()) ->setIssueInstant(new \DateTime()) ->setDestination($this->getMetadata()->getFirstSso()->getLocation()) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())) ->setRelayState(Helper::generateID()); if ($this->getMetadata()->getFirstIdpSsoDescriptor()->getWantAuthnRequestsSigned()) { $authnRequest->setSignature( new SignatureWriter( $this->getMetadata() ->getFirstSpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate(), KeyHelper::createPrivateKey($this->getPrivateKey(), '') ) ); } return $authnRequest; }
php
public function buildAuthnRequest() { $authnRequest = (new AuthnRequest()) ->setAssertionConsumerServiceURL($this->getMetadata()->getFirstAcs()->getLocation()) ->setProtocolBinding($this->getMetadata()->getFirstAcs()->getBinding()) ->setID(Helper::generateID()) ->setIssueInstant(new \DateTime()) ->setDestination($this->getMetadata()->getFirstSso()->getLocation()) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())) ->setRelayState(Helper::generateID()); if ($this->getMetadata()->getFirstIdpSsoDescriptor()->getWantAuthnRequestsSigned()) { $authnRequest->setSignature( new SignatureWriter( $this->getMetadata() ->getFirstSpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate(), KeyHelper::createPrivateKey($this->getPrivateKey(), '') ) ); } return $authnRequest; }
[ "public", "function", "buildAuthnRequest", "(", ")", "{", "$", "authnRequest", "=", "(", "new", "AuthnRequest", "(", ")", ")", "->", "setAssertionConsumerServiceURL", "(", "$", "this", "->", "getMetadata", "(", ")", "->", "getFirstAcs", "(", ")", "->", "getL...
Returns a AuthnRequest @return \LightSaml\Model\Protocol\SamlMessage
[ "Returns", "a", "AuthnRequest" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L173-L197
train
flash-global/connect-client
src/Saml.php
Saml.createLogoutResponse
public function createLogoutResponse() { return (new LogoutResponse()) ->setStatus(new Status(new StatusCode(SamlConstants::STATUS_SUCCESS))) ->setID(Helper::generateID()) ->setVersion(SamlConstants::VERSION_20) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())) ->setIssueInstant(new \DateTime()); }
php
public function createLogoutResponse() { return (new LogoutResponse()) ->setStatus(new Status(new StatusCode(SamlConstants::STATUS_SUCCESS))) ->setID(Helper::generateID()) ->setVersion(SamlConstants::VERSION_20) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())) ->setIssueInstant(new \DateTime()); }
[ "public", "function", "createLogoutResponse", "(", ")", "{", "return", "(", "new", "LogoutResponse", "(", ")", ")", "->", "setStatus", "(", "new", "Status", "(", "new", "StatusCode", "(", "SamlConstants", "::", "STATUS_SUCCESS", ")", ")", ")", "->", "setID",...
Create a Saml Logout Response @return LogoutResponse|SamlMessage
[ "Create", "a", "Saml", "Logout", "Response" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L204-L212
train
flash-global/connect-client
src/Saml.php
Saml.prepareLogoutResponse
public function prepareLogoutResponse(LogoutRequest $request) { $response = $this->createLogoutResponse(); $idp = $this->getMetadata()->getFirstIdpSsoDescriptor(); $location = $idp->getFirstSingleLogoutService()->getResponseLocation() ? $idp->getFirstSingleLogoutService()->getResponseLocation() : $idp->getFirstSingleLogoutService()->getLocation(); $response->setDestination($location); $response->setRelayState($request->getRelayState()); $this->signMessage($response); return $response; }
php
public function prepareLogoutResponse(LogoutRequest $request) { $response = $this->createLogoutResponse(); $idp = $this->getMetadata()->getFirstIdpSsoDescriptor(); $location = $idp->getFirstSingleLogoutService()->getResponseLocation() ? $idp->getFirstSingleLogoutService()->getResponseLocation() : $idp->getFirstSingleLogoutService()->getLocation(); $response->setDestination($location); $response->setRelayState($request->getRelayState()); $this->signMessage($response); return $response; }
[ "public", "function", "prepareLogoutResponse", "(", "LogoutRequest", "$", "request", ")", "{", "$", "response", "=", "$", "this", "->", "createLogoutResponse", "(", ")", ";", "$", "idp", "=", "$", "this", "->", "getMetadata", "(", ")", "->", "getFirstIdpSsoD...
Prepare a LogoutResponse to be send @param LogoutRequest $request @return LogoutResponse
[ "Prepare", "a", "LogoutResponse", "to", "be", "send" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L221-L237
train
flash-global/connect-client
src/Saml.php
Saml.createLogoutRequest
public function createLogoutRequest() { return (new LogoutRequest()) ->setID(Helper::generateID()) ->setVersion(SamlConstants::VERSION_20) ->setIssueInstant(new \DateTime()) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())); }
php
public function createLogoutRequest() { return (new LogoutRequest()) ->setID(Helper::generateID()) ->setVersion(SamlConstants::VERSION_20) ->setIssueInstant(new \DateTime()) ->setIssuer(new Issuer($this->getMetadata()->getServiceProvider()->getEntityID())); }
[ "public", "function", "createLogoutRequest", "(", ")", "{", "return", "(", "new", "LogoutRequest", "(", ")", ")", "->", "setID", "(", "Helper", "::", "generateID", "(", ")", ")", "->", "setVersion", "(", "SamlConstants", "::", "VERSION_20", ")", "->", "set...
Create a Saml Logout Request @return LogoutRequest|SamlMessage
[ "Create", "a", "Saml", "Logout", "Request" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L244-L251
train
flash-global/connect-client
src/Saml.php
Saml.prepareLogoutRequest
public function prepareLogoutRequest(User $user, $sessionIndex = null) { $request = $this->createLogoutRequest(); $request->setNameID( new NameID( $user->getUserName(), SamlConstants::NAME_ID_FORMAT_UNSPECIFIED ) ); if (!is_null($sessionIndex)) { $request->setSessionIndex($sessionIndex); } $request->setDestination( $this->getMetadata()->getFirstIdpSsoDescriptor()->getFirstSingleLogoutService()->getLocation() ); $request->setRelayState(Helper::generateID()); $this->signMessage($request); return $request; }
php
public function prepareLogoutRequest(User $user, $sessionIndex = null) { $request = $this->createLogoutRequest(); $request->setNameID( new NameID( $user->getUserName(), SamlConstants::NAME_ID_FORMAT_UNSPECIFIED ) ); if (!is_null($sessionIndex)) { $request->setSessionIndex($sessionIndex); } $request->setDestination( $this->getMetadata()->getFirstIdpSsoDescriptor()->getFirstSingleLogoutService()->getLocation() ); $request->setRelayState(Helper::generateID()); $this->signMessage($request); return $request; }
[ "public", "function", "prepareLogoutRequest", "(", "User", "$", "user", ",", "$", "sessionIndex", "=", "null", ")", "{", "$", "request", "=", "$", "this", "->", "createLogoutRequest", "(", ")", ";", "$", "request", "->", "setNameID", "(", "new", "NameID", ...
Prepare LogoutRequest before sending @param User $user @param null $sessionIndex @return LogoutRequest|SamlMessage
[ "Prepare", "LogoutRequest", "before", "sending" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L261-L285
train
flash-global/connect-client
src/Saml.php
Saml.getHttpRedirectBindingResponse
public function getHttpRedirectBindingResponse(AuthnRequest $request = null) { if (is_null($request)) { $request = $this->buildAuthnRequest(); } $context = new MessageContext(); $context->setMessage($request); $binding = (new BindingFactory())->create(SamlConstants::BINDING_SAML2_HTTP_REDIRECT); return new RedirectResponse($binding->send($context)->getTargetUrl()); }
php
public function getHttpRedirectBindingResponse(AuthnRequest $request = null) { if (is_null($request)) { $request = $this->buildAuthnRequest(); } $context = new MessageContext(); $context->setMessage($request); $binding = (new BindingFactory())->create(SamlConstants::BINDING_SAML2_HTTP_REDIRECT); return new RedirectResponse($binding->send($context)->getTargetUrl()); }
[ "public", "function", "getHttpRedirectBindingResponse", "(", "AuthnRequest", "$", "request", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "request", ")", ")", "{", "$", "request", "=", "$", "this", "->", "buildAuthnRequest", "(", ")", ";", "}", ...
Returns the AuthnRequest using HTTP Redirect Binding to Identity Provider SSO location @param AuthnRequest $request @return RedirectResponse
[ "Returns", "the", "AuthnRequest", "using", "HTTP", "Redirect", "Binding", "to", "Identity", "Provider", "SSO", "location" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L294-L306
train
flash-global/connect-client
src/Saml.php
Saml.getHttpPostBindingResponse
public function getHttpPostBindingResponse(SamlMessage $message) { $bindingFactory = new BindingFactory(); $postBinding = $bindingFactory->create(SamlConstants::BINDING_SAML2_HTTP_POST); $messageContext = new MessageContext(); $messageContext->setMessage($message); $httpResponse = $postBinding->send($messageContext); return new HtmlResponse($httpResponse->getContent()); }
php
public function getHttpPostBindingResponse(SamlMessage $message) { $bindingFactory = new BindingFactory(); $postBinding = $bindingFactory->create(SamlConstants::BINDING_SAML2_HTTP_POST); $messageContext = new MessageContext(); $messageContext->setMessage($message); $httpResponse = $postBinding->send($messageContext); return new HtmlResponse($httpResponse->getContent()); }
[ "public", "function", "getHttpPostBindingResponse", "(", "SamlMessage", "$", "message", ")", "{", "$", "bindingFactory", "=", "new", "BindingFactory", "(", ")", ";", "$", "postBinding", "=", "$", "bindingFactory", "->", "create", "(", "SamlConstants", "::", "BIN...
Returns the HtmlResponse with the form of PostBinding as content @param SamlMessage $message @return HtmlResponse
[ "Returns", "the", "HtmlResponse", "with", "the", "form", "of", "PostBinding", "as", "content" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L315-L326
train
flash-global/connect-client
src/Saml.php
Saml.signMessage
public function signMessage(SamlMessage $message) { return $message->setSignature( new SignatureWriter( $this->getMetadata() ->getFirstSpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate(), KeyHelper::createPrivateKey($this->getPrivateKey(), '') ) ); }
php
public function signMessage(SamlMessage $message) { return $message->setSignature( new SignatureWriter( $this->getMetadata() ->getFirstSpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate(), KeyHelper::createPrivateKey($this->getPrivateKey(), '') ) ); }
[ "public", "function", "signMessage", "(", "SamlMessage", "$", "message", ")", "{", "return", "$", "message", "->", "setSignature", "(", "new", "SignatureWriter", "(", "$", "this", "->", "getMetadata", "(", ")", "->", "getFirstSpSsoDescriptor", "(", ")", "->", ...
Sign a Saml Message @param SamlMessage $message @return SamlMessage
[ "Sign", "a", "Saml", "Message" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L335-L346
train
flash-global/connect-client
src/Saml.php
Saml.validateSignature
public function validateSignature($message, XMLSecurityKey $key) { $reader = $message->getSignature(); if ($reader instanceof AbstractSignatureReader) { try { return $reader->validate($key); } catch (\Exception $e) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied', $e); } } else { throw new SecurityException('Saml message signature is not specified'); } }
php
public function validateSignature($message, XMLSecurityKey $key) { $reader = $message->getSignature(); if ($reader instanceof AbstractSignatureReader) { try { return $reader->validate($key); } catch (\Exception $e) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied', $e); } } else { throw new SecurityException('Saml message signature is not specified'); } }
[ "public", "function", "validateSignature", "(", "$", "message", ",", "XMLSecurityKey", "$", "key", ")", "{", "$", "reader", "=", "$", "message", "->", "getSignature", "(", ")", ";", "if", "(", "$", "reader", "instanceof", "AbstractSignatureReader", ")", "{",...
Validate a signed message @param SamlMessage|Assertion $message @param XMLSecurityKey $key @return bool @throws SamlException|SecurityException
[ "Validate", "a", "signed", "message" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L358-L370
train
flash-global/connect-client
src/Saml.php
Saml.validateIssuer
public function validateIssuer(SamlMessage $message) { if ($this->getMetadata()->getIdentityProvider()->getEntityID() != $message->getIssuer()->getValue()) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
php
public function validateIssuer(SamlMessage $message) { if ($this->getMetadata()->getIdentityProvider()->getEntityID() != $message->getIssuer()->getValue()) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
[ "public", "function", "validateIssuer", "(", "SamlMessage", "$", "message", ")", "{", "if", "(", "$", "this", "->", "getMetadata", "(", ")", "->", "getIdentityProvider", "(", ")", "->", "getEntityID", "(", ")", "!=", "$", "message", "->", "getIssuer", "(",...
Validate IdP Response issuer @param SamlMessage $message @throws SamlException
[ "Validate", "IdP", "Response", "issuer" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L391-L396
train
flash-global/connect-client
src/Saml.php
Saml.validateDestination
public function validateDestination(Response $response) { if ($this->getMetadata()->getFirstSpSsoDescriptor()->getFirstAssertionConsumerService()->getLocation() != $response->getDestination() ) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
php
public function validateDestination(Response $response) { if ($this->getMetadata()->getFirstSpSsoDescriptor()->getFirstAssertionConsumerService()->getLocation() != $response->getDestination() ) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
[ "public", "function", "validateDestination", "(", "Response", "$", "response", ")", "{", "if", "(", "$", "this", "->", "getMetadata", "(", ")", "->", "getFirstSpSsoDescriptor", "(", ")", "->", "getFirstAssertionConsumerService", "(", ")", "->", "getLocation", "(...
Validate IdP Response destination @param Response $response @throws SamlException
[ "Validate", "IdP", "Response", "destination" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L405-L412
train
flash-global/connect-client
src/Saml.php
Saml.validateRelayState
public function validateRelayState(Response $response, $relayState) { if ($response->getRelayState() != null && $response->getRelayState() != $relayState) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
php
public function validateRelayState(Response $response, $relayState) { if ($response->getRelayState() != null && $response->getRelayState() != $relayState) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
[ "public", "function", "validateRelayState", "(", "Response", "$", "response", ",", "$", "relayState", ")", "{", "if", "(", "$", "response", "->", "getRelayState", "(", ")", "!=", "null", "&&", "$", "response", "->", "getRelayState", "(", ")", "!=", "$", ...
Validate IdP Response RelayState @param Response $response @param string $relayState @throws SamlException
[ "Validate", "IdP", "Response", "RelayState" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L422-L427
train
flash-global/connect-client
src/Saml.php
Saml.validateNameId
public function validateNameId(LogoutRequest $request, User $user) { if ($request->getNameID()->getValue() != $user->getUserName()) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
php
public function validateNameId(LogoutRequest $request, User $user) { if ($request->getNameID()->getValue() != $user->getUserName()) { throw new SamlException('urn:oasis:names:tc:SAML:2.0:status:RequestDenied'); } }
[ "public", "function", "validateNameId", "(", "LogoutRequest", "$", "request", ",", "User", "$", "user", ")", "{", "if", "(", "$", "request", "->", "getNameID", "(", ")", "->", "getValue", "(", ")", "!=", "$", "user", "->", "getUserName", "(", ")", ")",...
Validate a LogoutRequest NameId @param LogoutRequest $request @param User $user @throws SamlException
[ "Validate", "a", "LogoutRequest", "NameId" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L437-L442
train
flash-global/connect-client
src/Saml.php
Saml.validateResponse
public function validateResponse(Response $response, $relayState) { $this->validateIssuer($response); $this->validateDestination($response); if ($relayState) { $this->validateRelayState($response, $relayState); } $public = KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ); if ($this->hasSignature($response)) { $this->validateSignature($response, $public); } if ($response->getAllEncryptedAssertions()) { $private = KeyHelper::createPrivateKey($this->getPrivateKey(), null); /** @var EncryptedAssertionReader $encryptedAssertion */ foreach ($response->getAllEncryptedAssertions() as $encryptedAssertion) { $assertion = $encryptedAssertion->decryptAssertion($private, new DeserializationContext()); if ($this->hasSignature($assertion)) { $this->validateSignature($assertion, $public); } $response->addAssertion($assertion); } } }
php
public function validateResponse(Response $response, $relayState) { $this->validateIssuer($response); $this->validateDestination($response); if ($relayState) { $this->validateRelayState($response, $relayState); } $public = KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ); if ($this->hasSignature($response)) { $this->validateSignature($response, $public); } if ($response->getAllEncryptedAssertions()) { $private = KeyHelper::createPrivateKey($this->getPrivateKey(), null); /** @var EncryptedAssertionReader $encryptedAssertion */ foreach ($response->getAllEncryptedAssertions() as $encryptedAssertion) { $assertion = $encryptedAssertion->decryptAssertion($private, new DeserializationContext()); if ($this->hasSignature($assertion)) { $this->validateSignature($assertion, $public); } $response->addAssertion($assertion); } } }
[ "public", "function", "validateResponse", "(", "Response", "$", "response", ",", "$", "relayState", ")", "{", "$", "this", "->", "validateIssuer", "(", "$", "response", ")", ";", "$", "this", "->", "validateDestination", "(", "$", "response", ")", ";", "if...
Validate a IdP Response @param Response $response @param $relayState
[ "Validate", "a", "IdP", "Response" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L450-L482
train
flash-global/connect-client
src/Saml.php
Saml.validateLogoutRequest
public function validateLogoutRequest(LogoutRequest $request, User $user) { $this->validateIssuer($request); $this->validateNameId($request, $user); if ($this->hasSignature($request)) { $this->validateSignature( $request, KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ) ); } }
php
public function validateLogoutRequest(LogoutRequest $request, User $user) { $this->validateIssuer($request); $this->validateNameId($request, $user); if ($this->hasSignature($request)) { $this->validateSignature( $request, KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ) ); } }
[ "public", "function", "validateLogoutRequest", "(", "LogoutRequest", "$", "request", ",", "User", "$", "user", ")", "{", "$", "this", "->", "validateIssuer", "(", "$", "request", ")", ";", "$", "this", "->", "validateNameId", "(", "$", "request", ",", "$",...
Validate a LogoutRequest @param LogoutRequest $request @param User $user
[ "Validate", "a", "LogoutRequest" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L490-L505
train
flash-global/connect-client
src/Saml.php
Saml.validateLogoutResponse
public function validateLogoutResponse(LogoutResponse $response) { $this->validateIssuer($response); if ($this->hasSignature($response)) { $this->validateSignature( $response, KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ) ); } }
php
public function validateLogoutResponse(LogoutResponse $response) { $this->validateIssuer($response); if ($this->hasSignature($response)) { $this->validateSignature( $response, KeyHelper::createPublicKey( $this->getMetadata()->getFirstIdpSsoDescriptor() ->getFirstKeyDescriptor(KeyDescriptor::USE_SIGNING) ->getCertificate() ) ); } }
[ "public", "function", "validateLogoutResponse", "(", "LogoutResponse", "$", "response", ")", "{", "$", "this", "->", "validateIssuer", "(", "$", "response", ")", ";", "if", "(", "$", "this", "->", "hasSignature", "(", "$", "response", ")", ")", "{", "$", ...
Validate a LogoutResponse @param LogoutResponse $response
[ "Validate", "a", "LogoutResponse" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L512-L526
train
flash-global/connect-client
src/Saml.php
Saml.retrieveUserFromAssertion
public function retrieveUserFromAssertion(Assertion $assertion) { $user = null; $role = null; foreach ($assertion->getAllAttributeStatements() as $attributeStatement) { foreach ($attributeStatement->getAllAttributes() as $attribute) { switch ($attribute->getName()) { case 'user_entity': $user = new User(\json_decode($attribute->getFirstAttributeValue(), true)); break; case ClaimTypes::ROLE: $role = $attribute->getFirstAttributeValue(); } } } if ($user instanceof User) { $user->setCurrentRole($role); } return $user; }
php
public function retrieveUserFromAssertion(Assertion $assertion) { $user = null; $role = null; foreach ($assertion->getAllAttributeStatements() as $attributeStatement) { foreach ($attributeStatement->getAllAttributes() as $attribute) { switch ($attribute->getName()) { case 'user_entity': $user = new User(\json_decode($attribute->getFirstAttributeValue(), true)); break; case ClaimTypes::ROLE: $role = $attribute->getFirstAttributeValue(); } } } if ($user instanceof User) { $user->setCurrentRole($role); } return $user; }
[ "public", "function", "retrieveUserFromAssertion", "(", "Assertion", "$", "assertion", ")", "{", "$", "user", "=", "null", ";", "$", "role", "=", "null", ";", "foreach", "(", "$", "assertion", "->", "getAllAttributeStatements", "(", ")", "as", "$", "attribut...
Retrieves a User instance from Response Assertion send by IdP @param Assertion $assertion @return User
[ "Retrieves", "a", "User", "instance", "from", "Response", "Assertion", "send", "by", "IdP" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L535-L557
train
flash-global/connect-client
src/Saml.php
Saml.receiveMessage
protected function receiveMessage() { if (empty($_POST)) { $_POST = $this->retrievePostWithInputStream(); } $request = Request::createFromGlobals(); try { $binding = (new BindingFactory())->getBindingByRequest($request); } catch (\Exception $e) { return null; } $context = new MessageContext(); $binding->receive($request, $context); return $context; }
php
protected function receiveMessage() { if (empty($_POST)) { $_POST = $this->retrievePostWithInputStream(); } $request = Request::createFromGlobals(); try { $binding = (new BindingFactory())->getBindingByRequest($request); } catch (\Exception $e) { return null; } $context = new MessageContext(); $binding->receive($request, $context); return $context; }
[ "protected", "function", "receiveMessage", "(", ")", "{", "if", "(", "empty", "(", "$", "_POST", ")", ")", "{", "$", "_POST", "=", "$", "this", "->", "retrievePostWithInputStream", "(", ")", ";", "}", "$", "request", "=", "Request", "::", "createFromGlob...
Receive Saml message from globals variables @return MessageContext
[ "Receive", "Saml", "message", "from", "globals", "variables" ]
003db4187fbba0c0b7bd7a1c53d8487da06748bd
https://github.com/flash-global/connect-client/blob/003db4187fbba0c0b7bd7a1c53d8487da06748bd/src/Saml.php#L564-L582
train
hostnet/entity-plugin-lib
src/EntityPackage.php
EntityPackage.getFlattenedRequiredPackages
public function getFlattenedRequiredPackages() { $result = []; foreach ($this->getRequiredPackages() as $dependency) { $name = $dependency->getPackage()->getName(); $result[$name] = $dependency; $result = array_merge($result, $dependency->getFlattenedRequiredPackages()); } return $result; }
php
public function getFlattenedRequiredPackages() { $result = []; foreach ($this->getRequiredPackages() as $dependency) { $name = $dependency->getPackage()->getName(); $result[$name] = $dependency; $result = array_merge($result, $dependency->getFlattenedRequiredPackages()); } return $result; }
[ "public", "function", "getFlattenedRequiredPackages", "(", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getRequiredPackages", "(", ")", "as", "$", "dependency", ")", "{", "$", "name", "=", "$", "dependency", "->", "get...
Flattens the dependency tree of this package. All the packages it directly or indirectly references will be uniquely in this list. @return EntityPackage[]
[ "Flattens", "the", "dependency", "tree", "of", "this", "package", ".", "All", "the", "packages", "it", "directly", "or", "indirectly", "references", "will", "be", "uniquely", "in", "this", "list", "." ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/EntityPackage.php#L102-L111
train
mmoreram/BaseBundle
DependencyInjection/SimpleBaseExtension.php
SimpleBaseExtension.getConfigurationInstance
protected function getConfigurationInstance(): ? ConfigurationInterface { return $this->mappingBagProvider ? new BaseConfiguration( $this->getAlias(), $this->mappingBagProvider ) : null; }
php
protected function getConfigurationInstance(): ? ConfigurationInterface { return $this->mappingBagProvider ? new BaseConfiguration( $this->getAlias(), $this->mappingBagProvider ) : null; }
[ "protected", "function", "getConfigurationInstance", "(", ")", ":", "?", "ConfigurationInterface", "{", "return", "$", "this", "->", "mappingBagProvider", "?", "new", "BaseConfiguration", "(", "$", "this", "->", "getAlias", "(", ")", ",", "$", "this", "->", "m...
Return a new Configuration instance. If object returned by this method is an instance of ConfigurationInterface, extension will use the Configuration to read all bundle config definitions. Also will call getParametrizationValues method to load some config values to internal parameters. @return ConfigurationInterface|null
[ "Return", "a", "new", "Configuration", "instance", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/DependencyInjection/SimpleBaseExtension.php#L132-L140
train
rinvex/cortex-contacts
src/Http/Controllers/Adminarea/ContactsController.php
ContactsController.stash
public function stash(ImportFormRequest $request, Contact $contact, DefaultImporter $importer) { // Handle the import $importer->config['resource'] = $contact; $importer->handleImport(); }
php
public function stash(ImportFormRequest $request, Contact $contact, DefaultImporter $importer) { // Handle the import $importer->config['resource'] = $contact; $importer->handleImport(); }
[ "public", "function", "stash", "(", "ImportFormRequest", "$", "request", ",", "Contact", "$", "contact", ",", "DefaultImporter", "$", "importer", ")", "{", "// Handle the import", "$", "importer", "->", "config", "[", "'resource'", "]", "=", "$", "contact", ";...
Stash contacts. @param \Cortex\Foundation\Http\Requests\ImportFormRequest $request @param \Cortex\Foundation\Importers\DefaultImporter $importer @return void
[ "Stash", "contacts", "." ]
d27aef100c442bd560809be5a6653737434b2e62
https://github.com/rinvex/cortex-contacts/blob/d27aef100c442bd560809be5a6653737434b2e62/src/Http/Controllers/Adminarea/ContactsController.php#L83-L88
train
mmoreram/BaseBundle
DependencyInjection/BaseConfiguration.php
BaseConfiguration.addMappingNode
protected function addMappingNode( string $nodeName, string $entityClass, string $entityMappingFile, string $entityManager, bool $entityEnabled ): NodeDefinition { $builder = new TreeBuilder(); $node = $builder->root($nodeName); $node ->treatFalseLike([ 'enabled' => false, ]) ->addDefaultsIfNotSet() ->children() ->scalarNode('class') ->defaultValue($entityClass) ->cannotBeEmpty() ->end() ->scalarNode('mapping_file') ->defaultValue($entityMappingFile) ->cannotBeEmpty() ->end() ->scalarNode('manager') ->defaultValue($entityManager) ->cannotBeEmpty() ->end() ->booleanNode('enabled') ->defaultValue($entityEnabled) ->end() ->end() ->end(); return $node; }
php
protected function addMappingNode( string $nodeName, string $entityClass, string $entityMappingFile, string $entityManager, bool $entityEnabled ): NodeDefinition { $builder = new TreeBuilder(); $node = $builder->root($nodeName); $node ->treatFalseLike([ 'enabled' => false, ]) ->addDefaultsIfNotSet() ->children() ->scalarNode('class') ->defaultValue($entityClass) ->cannotBeEmpty() ->end() ->scalarNode('mapping_file') ->defaultValue($entityMappingFile) ->cannotBeEmpty() ->end() ->scalarNode('manager') ->defaultValue($entityManager) ->cannotBeEmpty() ->end() ->booleanNode('enabled') ->defaultValue($entityEnabled) ->end() ->end() ->end(); return $node; }
[ "protected", "function", "addMappingNode", "(", "string", "$", "nodeName", ",", "string", "$", "entityClass", ",", "string", "$", "entityMappingFile", ",", "string", "$", "entityManager", ",", "bool", "$", "entityEnabled", ")", ":", "NodeDefinition", "{", "$", ...
Add a mapping node into configuration. @param string $nodeName @param string $entityClass @param string $entityMappingFile @param string $entityManager @param bool $entityEnabled @return NodeDefinition Node
[ "Add", "a", "mapping", "node", "into", "configuration", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/DependencyInjection/BaseConfiguration.php#L101-L135
train
mmoreram/BaseBundle
DependencyInjection/BaseConfiguration.php
BaseConfiguration.addDetectedMappingNodes
private function addDetectedMappingNodes( ArrayNodeDefinition $rootNode, MappingBagCollection $mappingBagCollection ) { $mappingNode = $rootNode ->children() ->arrayNode('mapping') ->addDefaultsIfNotSet() ->children(); foreach ($mappingBagCollection->all() as $mappingBag) { if ($mappingBag->isOverwritable()) { $mappingNode->append($this->addMappingNode( $mappingBag->getEntityName(), $mappingBag->getEntityNamespace(), $mappingBag->getEntityMappingFilePath(), $mappingBag->getManagerName(), $mappingBag->getEntityIsEnabled() )); } } }
php
private function addDetectedMappingNodes( ArrayNodeDefinition $rootNode, MappingBagCollection $mappingBagCollection ) { $mappingNode = $rootNode ->children() ->arrayNode('mapping') ->addDefaultsIfNotSet() ->children(); foreach ($mappingBagCollection->all() as $mappingBag) { if ($mappingBag->isOverwritable()) { $mappingNode->append($this->addMappingNode( $mappingBag->getEntityName(), $mappingBag->getEntityNamespace(), $mappingBag->getEntityMappingFilePath(), $mappingBag->getManagerName(), $mappingBag->getEntityIsEnabled() )); } } }
[ "private", "function", "addDetectedMappingNodes", "(", "ArrayNodeDefinition", "$", "rootNode", ",", "MappingBagCollection", "$", "mappingBagCollection", ")", "{", "$", "mappingNode", "=", "$", "rootNode", "->", "children", "(", ")", "->", "arrayNode", "(", "'mapping...
Add all mapping nodes injected in the mappingBagCollection. @param ArrayNodeDefinition $rootNode @param MappingBagCollection $mappingBagCollection
[ "Add", "all", "mapping", "nodes", "injected", "in", "the", "mappingBagCollection", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/DependencyInjection/BaseConfiguration.php#L143-L164
train
mmoreram/BaseBundle
Mapping/MappingBag.php
MappingBag.getParamFormat
public function getParamFormat(string $type): string { return ltrim(($this->containerPrefix.'.entity.'.$this->entityName.'.'.$type), '.'); }
php
public function getParamFormat(string $type): string { return ltrim(($this->containerPrefix.'.entity.'.$this->entityName.'.'.$type), '.'); }
[ "public", "function", "getParamFormat", "(", "string", "$", "type", ")", ":", "string", "{", "return", "ltrim", "(", "(", "$", "this", "->", "containerPrefix", ".", "'.entity.'", ".", "$", "this", "->", "entityName", ".", "'.'", ".", "$", "type", ")", ...
Get entity parametrization by type. @param string $type @return string
[ "Get", "entity", "parametrization", "by", "type", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/Mapping/MappingBag.php#L328-L331
train
mmoreram/BaseBundle
Mapping/MappingBag.php
MappingBag.createReducedMappingBag
private function createReducedMappingBag(bool $isOverwritable): ReducedMappingBag { return new ReducedMappingBag( $isOverwritable ? $this->getParamFormat('class') : $this->getEntityNamespace(), $isOverwritable ? $this->getParamFormat('mapping_file') : $this->getEntityMappingFilePath(), $isOverwritable ? $this->getParamFormat('manager') : $this->managerName, $isOverwritable ? $this->getParamFormat('enabled') : $this->entityIsEnabled ); }
php
private function createReducedMappingBag(bool $isOverwritable): ReducedMappingBag { return new ReducedMappingBag( $isOverwritable ? $this->getParamFormat('class') : $this->getEntityNamespace(), $isOverwritable ? $this->getParamFormat('mapping_file') : $this->getEntityMappingFilePath(), $isOverwritable ? $this->getParamFormat('manager') : $this->managerName, $isOverwritable ? $this->getParamFormat('enabled') : $this->entityIsEnabled ); }
[ "private", "function", "createReducedMappingBag", "(", "bool", "$", "isOverwritable", ")", ":", "ReducedMappingBag", "{", "return", "new", "ReducedMappingBag", "(", "$", "isOverwritable", "?", "$", "this", "->", "getParamFormat", "(", "'class'", ")", ":", "$", "...
Create a new instance of ReducedMappingBag given the local information stored. @param bool $isOverwritable @return ReducedMappingBag
[ "Create", "a", "new", "instance", "of", "ReducedMappingBag", "given", "the", "local", "information", "stored", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/Mapping/MappingBag.php#L341-L349
train
gyselroth/micro-auth
src/Adapter/Oidc.php
Oidc.getDiscoveryDocument
public function getDiscoveryDocument(): array { if ($apc = extension_loaded('apc') && apc_exists($this->provider_url)) { return apc_get($this->provider_url); } $ch = curl_init(); $url = $this->getDiscoveryUrl(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $this->logger->debug('fetch openid-connect discovery document from ['.$url.']', [ 'category' => get_class($this), ]); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (200 === $code) { $discovery = json_decode($result, true); $this->logger->debug('received openid-connect discovery document from ['.$url.']', [ 'category' => get_class($this), 'discovery' => $discovery, ]); if (true === $apc) { apc_store($this->provider_url, $discovery); } return $discovery; } $this->logger->error('failed to receive openid-connect discovery document from ['.$url.'], request ended with status ['.$code.']', [ 'category' => get_class($this), ]); throw new OidcException\DiscoveryNotFound('failed to get openid-connect discovery document'); }
php
public function getDiscoveryDocument(): array { if ($apc = extension_loaded('apc') && apc_exists($this->provider_url)) { return apc_get($this->provider_url); } $ch = curl_init(); $url = $this->getDiscoveryUrl(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $this->logger->debug('fetch openid-connect discovery document from ['.$url.']', [ 'category' => get_class($this), ]); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (200 === $code) { $discovery = json_decode($result, true); $this->logger->debug('received openid-connect discovery document from ['.$url.']', [ 'category' => get_class($this), 'discovery' => $discovery, ]); if (true === $apc) { apc_store($this->provider_url, $discovery); } return $discovery; } $this->logger->error('failed to receive openid-connect discovery document from ['.$url.'], request ended with status ['.$code.']', [ 'category' => get_class($this), ]); throw new OidcException\DiscoveryNotFound('failed to get openid-connect discovery document'); }
[ "public", "function", "getDiscoveryDocument", "(", ")", ":", "array", "{", "if", "(", "$", "apc", "=", "extension_loaded", "(", "'apc'", ")", "&&", "apc_exists", "(", "$", "this", "->", "provider_url", ")", ")", "{", "return", "apc_get", "(", "$", "this"...
Get discovery document. @return array
[ "Get", "discovery", "document", "." ]
9c08a6afc94f76635fb7d29f56fb8409e383677f
https://github.com/gyselroth/micro-auth/blob/9c08a6afc94f76635fb7d29f56fb8409e383677f/src/Adapter/Oidc.php#L154-L190
train
gyselroth/micro-auth
src/Adapter/Oidc.php
Oidc.verifyToken
protected function verifyToken(string $token): bool { if ($this->token_validation_url) { $this->logger->debug('validate oauth2 token via rfc7662 token validation endpoint ['.$this->token_validation_url.']', [ 'category' => get_class($this), ]); $url = str_replace('{token}', $token, $this->token_validation_url); } else { $discovery = $this->getDiscoveryDocument(); if (!(isset($discovery['userinfo_endpoint']))) { throw new OidcException\UserEndpointNotSet('userinfo_endpoint could not be determained'); } $this->logger->debug('validate token via openid-connect userinfo_endpoint ['.$discovery['userinfo_endpoint'].']', [ 'category' => get_class($this), ]); $url = $discovery['userinfo_endpoint'].'?access_token='.$token; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $response = json_decode($result, true); if (200 === $code) { $attributes = json_decode($result, true); $this->logger->debug('successfully verified oauth2 access token via authorization server', [ 'category' => get_class($this), ]); if (!isset($attributes[$this->identity_attribute])) { throw new Exception\IdentityAttributeNotFound('identity attribute '.$this->identity_attribute.' not found in oauth2 response'); } $this->identifier = $attributes[$this->identity_attribute]; if ($this->token_validation_url) { $this->attributes = $attributes; } else { $this->access_token = $token; } return true; } $this->logger->error('failed verify oauth2 access token via authorization server, received status ['.$code.']', [ 'category' => get_class($this), ]); throw new OidcException\InvalidAccessToken('failed verify oauth2 access token via authorization server'); }
php
protected function verifyToken(string $token): bool { if ($this->token_validation_url) { $this->logger->debug('validate oauth2 token via rfc7662 token validation endpoint ['.$this->token_validation_url.']', [ 'category' => get_class($this), ]); $url = str_replace('{token}', $token, $this->token_validation_url); } else { $discovery = $this->getDiscoveryDocument(); if (!(isset($discovery['userinfo_endpoint']))) { throw new OidcException\UserEndpointNotSet('userinfo_endpoint could not be determained'); } $this->logger->debug('validate token via openid-connect userinfo_endpoint ['.$discovery['userinfo_endpoint'].']', [ 'category' => get_class($this), ]); $url = $discovery['userinfo_endpoint'].'?access_token='.$token; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $response = json_decode($result, true); if (200 === $code) { $attributes = json_decode($result, true); $this->logger->debug('successfully verified oauth2 access token via authorization server', [ 'category' => get_class($this), ]); if (!isset($attributes[$this->identity_attribute])) { throw new Exception\IdentityAttributeNotFound('identity attribute '.$this->identity_attribute.' not found in oauth2 response'); } $this->identifier = $attributes[$this->identity_attribute]; if ($this->token_validation_url) { $this->attributes = $attributes; } else { $this->access_token = $token; } return true; } $this->logger->error('failed verify oauth2 access token via authorization server, received status ['.$code.']', [ 'category' => get_class($this), ]); throw new OidcException\InvalidAccessToken('failed verify oauth2 access token via authorization server'); }
[ "protected", "function", "verifyToken", "(", "string", "$", "token", ")", ":", "bool", "{", "if", "(", "$", "this", "->", "token_validation_url", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'validate oauth2 token via rfc7662 token validation endpoi...
Token verification. @param string $token @return bool
[ "Token", "verification", "." ]
9c08a6afc94f76635fb7d29f56fb8409e383677f
https://github.com/gyselroth/micro-auth/blob/9c08a6afc94f76635fb7d29f56fb8409e383677f/src/Adapter/Oidc.php#L243-L297
train
hostnet/entity-plugin-lib
src/ReflectionGenerator.php
ReflectionGenerator.generate
public function generate(PackageClass $package_class) { $parent = $this->getParentClass($package_class); $class_name = $package_class->getShortName(); $generated_namespace = $package_class->getGeneratedNamespaceName(); $methods = $this->getMethods($package_class); $params = [ 'class_name' => $class_name, 'namespace' => $generated_namespace, 'methods' => $methods, 'parent' => $parent ? $parent->getShortName() : null, ]; $interface = $this->environment->render('interface.php.twig', $params); $path = $package_class->getGeneratedDirectory(); $this->filesystem->dumpFile($path . $class_name . 'Interface.php', $interface); }
php
public function generate(PackageClass $package_class) { $parent = $this->getParentClass($package_class); $class_name = $package_class->getShortName(); $generated_namespace = $package_class->getGeneratedNamespaceName(); $methods = $this->getMethods($package_class); $params = [ 'class_name' => $class_name, 'namespace' => $generated_namespace, 'methods' => $methods, 'parent' => $parent ? $parent->getShortName() : null, ]; $interface = $this->environment->render('interface.php.twig', $params); $path = $package_class->getGeneratedDirectory(); $this->filesystem->dumpFile($path . $class_name . 'Interface.php', $interface); }
[ "public", "function", "generate", "(", "PackageClass", "$", "package_class", ")", "{", "$", "parent", "=", "$", "this", "->", "getParentClass", "(", "$", "package_class", ")", ";", "$", "class_name", "=", "$", "package_class", "->", "getShortName", "(", ")",...
Generates the interface @param PackageClass $package_class @throws Error
[ "Generates", "the", "interface" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/ReflectionGenerator.php#L38-L55
train
hostnet/entity-plugin-lib
src/ReflectionGenerator.php
ReflectionGenerator.getMethods
protected function getMethods(PackageClass $package_class) { try { $class = new \ReflectionClass($package_class->getName()); } catch (\ReflectionException $e) { return []; } $methods = $class->getMethods(); foreach ($methods as $key => $method) { if ($method->name === '__construct') { // The interface should not contain the constructor unset($methods[$key]); continue; } $methods[$key] = new ReflectionMethod($method); } return $methods; }
php
protected function getMethods(PackageClass $package_class) { try { $class = new \ReflectionClass($package_class->getName()); } catch (\ReflectionException $e) { return []; } $methods = $class->getMethods(); foreach ($methods as $key => $method) { if ($method->name === '__construct') { // The interface should not contain the constructor unset($methods[$key]); continue; } $methods[$key] = new ReflectionMethod($method); } return $methods; }
[ "protected", "function", "getMethods", "(", "PackageClass", "$", "package_class", ")", "{", "try", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "package_class", "->", "getName", "(", ")", ")", ";", "}", "catch", "(", "\\", "ReflectionE...
Which methods do we have to generate? @return \ReflectionMethod[]
[ "Which", "methods", "do", "we", "have", "to", "generate?" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/ReflectionGenerator.php#L62-L81
train
hostnet/entity-plugin-lib
src/ReflectionGenerator.php
ReflectionGenerator.getParentClass
protected function getParentClass(PackageClass $package_class) { try { $base_class = new \ReflectionClass($package_class->getName()); } catch (\ReflectionException $e) { return null; } if (false === ($parent_reflection = $base_class->getParentClass()) || dirname($parent_reflection->getFileName()) !== dirname($base_class->getFileName()) ) { return null; } return new PackageClass($parent_reflection->getName(), $parent_reflection->getFileName()); }
php
protected function getParentClass(PackageClass $package_class) { try { $base_class = new \ReflectionClass($package_class->getName()); } catch (\ReflectionException $e) { return null; } if (false === ($parent_reflection = $base_class->getParentClass()) || dirname($parent_reflection->getFileName()) !== dirname($base_class->getFileName()) ) { return null; } return new PackageClass($parent_reflection->getName(), $parent_reflection->getFileName()); }
[ "protected", "function", "getParentClass", "(", "PackageClass", "$", "package_class", ")", "{", "try", "{", "$", "base_class", "=", "new", "\\", "ReflectionClass", "(", "$", "package_class", "->", "getName", "(", ")", ")", ";", "}", "catch", "(", "\\", "Re...
Get the Parent of the given base class, if any. @param PackageClass $package_class the base for which the parent needs to be extracted. @return NULL|\Hostnet\Component\EntityPlugin\PackageClass the parent class if any, otherwise null is returned.
[ "Get", "the", "Parent", "of", "the", "given", "base", "class", "if", "any", "." ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/ReflectionGenerator.php#L89-L103
train
PackageFactory/atomic-fusion-proptypes
Classes/Error/ExceptionHandler/PropTypeExceptionHandler.php
PropTypeExceptionHandler.handleRenderingException
public function handleRenderingException($fusionPath, \Exception $exception) { if ($exception instanceof PropTypeException) { return $this->handlePropTypeException($fusionPath, $exception, $exception->getReferenceCode()); } else { parent::handleRenderingException($fusionPath, $exception); } }
php
public function handleRenderingException($fusionPath, \Exception $exception) { if ($exception instanceof PropTypeException) { return $this->handlePropTypeException($fusionPath, $exception, $exception->getReferenceCode()); } else { parent::handleRenderingException($fusionPath, $exception); } }
[ "public", "function", "handleRenderingException", "(", "$", "fusionPath", ",", "\\", "Exception", "$", "exception", ")", "{", "if", "(", "$", "exception", "instanceof", "PropTypeException", ")", "{", "return", "$", "this", "->", "handlePropTypeException", "(", "...
In all aspects other than handling of PropTypeException this behaves exactly as the BubblingHandler which is the internal fusion exception handler by default. @param array $fusionPath @param \Exception $exception @return string @throws \Neos\Flow\Configuration\Exception\InvalidConfigurationException @throws \Neos\Flow\Mvc\Exception\StopActionException
[ "In", "all", "aspects", "other", "than", "handling", "of", "PropTypeException", "this", "behaves", "exactly", "as", "the", "BubblingHandler", "which", "is", "the", "internal", "fusion", "exception", "handler", "by", "default", "." ]
cf872a5c82c2c7d05b0be850b90307e0c3b4ee4c
https://github.com/PackageFactory/atomic-fusion-proptypes/blob/cf872a5c82c2c7d05b0be850b90307e0c3b4ee4c/Classes/Error/ExceptionHandler/PropTypeExceptionHandler.php#L46-L53
train
mmoreram/BaseBundle
BaseBundle.php
BaseBundle.registerCommands
public function registerCommands(Application $application) { foreach ($this->getCommands() as $command) { $application->add($command); } }
php
public function registerCommands(Application $application) { foreach ($this->getCommands() as $command) { $application->add($command); } }
[ "public", "function", "registerCommands", "(", "Application", "$", "application", ")", "{", "foreach", "(", "$", "this", "->", "getCommands", "(", ")", "as", "$", "command", ")", "{", "$", "application", "->", "add", "(", "$", "command", ")", ";", "}", ...
Register Commands. @param Application $application
[ "Register", "Commands", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/BaseBundle.php#L67-L72
train
mirko-pagliai/cakephp-link-scanner
src/Command/LinkScannerCommand.php
LinkScannerCommand.execute
public function execute(Arguments $args, ConsoleIo $io) { try { //Will trigger events provided by `LinkScannerCommandEventListener` $this->LinkScanner->getEventManager()->on(new LinkScannerCommandEventListener($args, $io)); if ($args->getOption('follow-redirects')) { $this->LinkScanner->setConfig('followRedirects', true); } if ($args->getOption('force')) { $this->LinkScanner->setConfig('lockFile', false); } if ($args->hasOption('full-base-url')) { $this->LinkScanner->setConfig('fullBaseUrl', $args->getOption('full-base-url')); } if ($args->hasOption('max-depth')) { $this->LinkScanner->setConfig('maxDepth', $args->getOption('max-depth')); } if ($args->getOption('no-cache')) { $this->LinkScanner->setConfig('cache', false); } if ($args->getOption('no-external-links')) { $this->LinkScanner->setConfig('externalLinks', false); } if ($args->hasOption('timeout')) { $this->LinkScanner->Client->setConfig('timeout', $args->getOption('timeout')); } $this->LinkScanner->scan(); if ($args->getOption('export-with-filename') || $args->getOption('export')) { $this->LinkScanner->export($args->getOption('export-with-filename')); } } catch (Exception $e) { $io->error($e->getMessage()); $this->abort(); } return null; }
php
public function execute(Arguments $args, ConsoleIo $io) { try { //Will trigger events provided by `LinkScannerCommandEventListener` $this->LinkScanner->getEventManager()->on(new LinkScannerCommandEventListener($args, $io)); if ($args->getOption('follow-redirects')) { $this->LinkScanner->setConfig('followRedirects', true); } if ($args->getOption('force')) { $this->LinkScanner->setConfig('lockFile', false); } if ($args->hasOption('full-base-url')) { $this->LinkScanner->setConfig('fullBaseUrl', $args->getOption('full-base-url')); } if ($args->hasOption('max-depth')) { $this->LinkScanner->setConfig('maxDepth', $args->getOption('max-depth')); } if ($args->getOption('no-cache')) { $this->LinkScanner->setConfig('cache', false); } if ($args->getOption('no-external-links')) { $this->LinkScanner->setConfig('externalLinks', false); } if ($args->hasOption('timeout')) { $this->LinkScanner->Client->setConfig('timeout', $args->getOption('timeout')); } $this->LinkScanner->scan(); if ($args->getOption('export-with-filename') || $args->getOption('export')) { $this->LinkScanner->export($args->getOption('export-with-filename')); } } catch (Exception $e) { $io->error($e->getMessage()); $this->abort(); } return null; }
[ "public", "function", "execute", "(", "Arguments", "$", "args", ",", "ConsoleIo", "$", "io", ")", "{", "try", "{", "//Will trigger events provided by `LinkScannerCommandEventListener`", "$", "this", "->", "LinkScanner", "->", "getEventManager", "(", ")", "->", "on",...
Performs a complete scan @param Arguments $args The command arguments @param ConsoleIo $io The console io @return null|int The exit code or null for success @see LinkScannerCommandEventListener::implementedEvents() @uses $LinkScanner
[ "Performs", "a", "complete", "scan" ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Command/LinkScannerCommand.php#L51-L90
train
PackageFactory/atomic-fusion-proptypes
Classes/Validators/InstanceOfValidator.php
InstanceOfValidator.isValid
protected function isValid($value) { if (is_null($value)) { return; } elseif ($value) { $context = [$value]; } else { $context = []; } $q = new FlowQuery($context); if ($q->is('[instanceof ' . $this->options['type'] . ']')) { return; } $this->addError('The value is expected to satisfy the %s flowQuery condition.', 1515144113, [ $this->options['type'] ]); }
php
protected function isValid($value) { if (is_null($value)) { return; } elseif ($value) { $context = [$value]; } else { $context = []; } $q = new FlowQuery($context); if ($q->is('[instanceof ' . $this->options['type'] . ']')) { return; } $this->addError('The value is expected to satisfy the %s flowQuery condition.', 1515144113, [ $this->options['type'] ]); }
[ "protected", "function", "isValid", "(", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "value", ")", ")", "{", "return", ";", "}", "elseif", "(", "$", "value", ")", "{", "$", "context", "=", "[", "$", "value", "]", ";", "}", "else", "...
Checks if the given value is a valid via FlowQuery. @param mixed $value The value that should be validated @return void
[ "Checks", "if", "the", "given", "value", "is", "a", "valid", "via", "FlowQuery", "." ]
cf872a5c82c2c7d05b0be850b90307e0c3b4ee4c
https://github.com/PackageFactory/atomic-fusion-proptypes/blob/cf872a5c82c2c7d05b0be850b90307e0c3b4ee4c/Classes/Validators/InstanceOfValidator.php#L28-L47
train
hiqdev/hiapi
src/console/QueueController.php
QueueController.requeue
private function requeue(string $queueName, AMQPMessage $msg, NotProcessableException $exception): void { $tries = 0; $headers = $msg->get_properties()['application_headers']; if ($headers instanceof AMQPTable) { $tries = $headers->getNativeData()['x-number-of-tries'] ?? 0; } if ($exception->getMaxTries() !== null && $tries >= $exception->getMaxTries()) { $this->logger->debug('No tries left for message. Marking it as an error', ['message' => $msg, 'exception' => $exception]); $this->handleError($queueName, $msg, $exception); return; } // Init delay exchange $channel = $this->amqp->channel(); $delayExchange = "$queueName.delayed"; $channel->exchange_declare($delayExchange, 'x-delayed-message', false, true, true, false, false, new AMQPTable([ 'x-delayed-type' => 'direct', ])); $channel->queue_bind($queueName, $delayExchange); // Send message $delayDuration = 1000 * $exception->getSecondsBeforeRetry() * (int)pow($exception->getProgressionMultiplier(), $tries); $delayMessage = new AMQPMessage($msg->getBody(), array_merge($msg->get_properties(), [ 'application_headers' => new AMQPTable([ 'x-delay' => $delayDuration, 'x-number-of-tries' => $tries + 1, ]), ])); $channel->basic_publish($delayMessage, $delayExchange, ''); $this->logger->debug('Delayed message for ' . $delayDuration, ['message' => $msg, 'exception' => $exception]); }
php
private function requeue(string $queueName, AMQPMessage $msg, NotProcessableException $exception): void { $tries = 0; $headers = $msg->get_properties()['application_headers']; if ($headers instanceof AMQPTable) { $tries = $headers->getNativeData()['x-number-of-tries'] ?? 0; } if ($exception->getMaxTries() !== null && $tries >= $exception->getMaxTries()) { $this->logger->debug('No tries left for message. Marking it as an error', ['message' => $msg, 'exception' => $exception]); $this->handleError($queueName, $msg, $exception); return; } // Init delay exchange $channel = $this->amqp->channel(); $delayExchange = "$queueName.delayed"; $channel->exchange_declare($delayExchange, 'x-delayed-message', false, true, true, false, false, new AMQPTable([ 'x-delayed-type' => 'direct', ])); $channel->queue_bind($queueName, $delayExchange); // Send message $delayDuration = 1000 * $exception->getSecondsBeforeRetry() * (int)pow($exception->getProgressionMultiplier(), $tries); $delayMessage = new AMQPMessage($msg->getBody(), array_merge($msg->get_properties(), [ 'application_headers' => new AMQPTable([ 'x-delay' => $delayDuration, 'x-number-of-tries' => $tries + 1, ]), ])); $channel->basic_publish($delayMessage, $delayExchange, ''); $this->logger->debug('Delayed message for ' . $delayDuration, ['message' => $msg, 'exception' => $exception]); }
[ "private", "function", "requeue", "(", "string", "$", "queueName", ",", "AMQPMessage", "$", "msg", ",", "NotProcessableException", "$", "exception", ")", ":", "void", "{", "$", "tries", "=", "0", ";", "$", "headers", "=", "$", "msg", "->", "get_properties"...
Resends message to queue with a delay @param string $queueName @param AMQPMessage $msg @param NotProcessableException $exception
[ "Resends", "message", "to", "queue", "with", "a", "delay" ]
2b3b334b247f69068b1f21b19e8ea013b1bae947
https://github.com/hiqdev/hiapi/blob/2b3b334b247f69068b1f21b19e8ea013b1bae947/src/console/QueueController.php#L139-L171
train
rinvex/cortex-contacts
src/Http/Controllers/Managerarea/ContactsController.php
ContactsController.destroy
public function destroy(Contact $contact) { $contact->delete(); return intend([ 'url' => route('managerarea.contacts.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/contacts::common.contact'), 'identifier' => $contact->full_name])], ]); }
php
public function destroy(Contact $contact) { $contact->delete(); return intend([ 'url' => route('managerarea.contacts.index'), 'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/contacts::common.contact'), 'identifier' => $contact->full_name])], ]); }
[ "public", "function", "destroy", "(", "Contact", "$", "contact", ")", "{", "$", "contact", "->", "delete", "(", ")", ";", "return", "intend", "(", "[", "'url'", "=>", "route", "(", "'managerarea.contacts.index'", ")", ",", "'with'", "=>", "[", "'warning'",...
Destroy given contact. @param \Cortex\Contacts\Models\Contact $contact @throws \Exception @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
[ "Destroy", "given", "contact", "." ]
d27aef100c442bd560809be5a6653737434b2e62
https://github.com/rinvex/cortex-contacts/blob/d27aef100c442bd560809be5a6653737434b2e62/src/Http/Controllers/Managerarea/ContactsController.php#L218-L226
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner._createLockFile
protected function _createLockFile() { is_true_or_fail(!$this->getConfig('lockFile') || !file_exists($this->lockFile), __d( 'link-scanner', 'Lock file `{0}` already exists, maybe a scan is already in progress. If not, remove it manually', $this->lockFile ), RuntimeException::class); return $this->getConfig('lockFile') ? new File($this->lockFile, true) !== false : true; }
php
protected function _createLockFile() { is_true_or_fail(!$this->getConfig('lockFile') || !file_exists($this->lockFile), __d( 'link-scanner', 'Lock file `{0}` already exists, maybe a scan is already in progress. If not, remove it manually', $this->lockFile ), RuntimeException::class); return $this->getConfig('lockFile') ? new File($this->lockFile, true) !== false : true; }
[ "protected", "function", "_createLockFile", "(", ")", "{", "is_true_or_fail", "(", "!", "$", "this", "->", "getConfig", "(", "'lockFile'", ")", "||", "!", "file_exists", "(", "$", "this", "->", "lockFile", ")", ",", "__d", "(", "'link-scanner'", ",", "'Loc...
Internal method to create a lock file @return bool @throws RuntimeException @uses $lockFile
[ "Internal", "method", "to", "create", "a", "lock", "file" ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L142-L151
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner._getResponse
protected function _getResponse($url) { $this->alreadyScanned[] = $url; $cacheKey = sprintf('response_%s', md5(serialize($url))); $response = $this->getConfig('cache') ? Cache::read($cacheKey, 'LinkScanner') : null; if ($response && is_array($response)) { list($response, $body) = $response; $stream = new Stream('php://memory', 'wb+'); $stream->write($body); $stream->rewind(); $response = $response->withBody($stream); } if (!$response instanceof Response) { try { $response = $this->Client->get($url); if ($this->getConfig('cache') && ($response->isOk() || $response->isRedirect())) { Cache::write($cacheKey, [$response, (string)$response->getBody()], 'LinkScanner'); } } catch (Exception $e) { $response = (new Response)->withStatus(404); } } return $response; }
php
protected function _getResponse($url) { $this->alreadyScanned[] = $url; $cacheKey = sprintf('response_%s', md5(serialize($url))); $response = $this->getConfig('cache') ? Cache::read($cacheKey, 'LinkScanner') : null; if ($response && is_array($response)) { list($response, $body) = $response; $stream = new Stream('php://memory', 'wb+'); $stream->write($body); $stream->rewind(); $response = $response->withBody($stream); } if (!$response instanceof Response) { try { $response = $this->Client->get($url); if ($this->getConfig('cache') && ($response->isOk() || $response->isRedirect())) { Cache::write($cacheKey, [$response, (string)$response->getBody()], 'LinkScanner'); } } catch (Exception $e) { $response = (new Response)->withStatus(404); } } return $response; }
[ "protected", "function", "_getResponse", "(", "$", "url", ")", "{", "$", "this", "->", "alreadyScanned", "[", "]", "=", "$", "url", ";", "$", "cacheKey", "=", "sprintf", "(", "'response_%s'", ",", "md5", "(", "serialize", "(", "$", "url", ")", ")", "...
Performs a single GET request and returns a `ScanResponse` instance. The response will be cached, if that's ok and the cache is enabled. @param string $url The url or path you want to request @return Response @uses $Client @uses $alreadyScanned @uses $fullBaseUrl
[ "Performs", "a", "single", "GET", "request", "and", "returns", "a", "ScanResponse", "instance", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L163-L192
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner._recursiveScan
protected function _recursiveScan($url, $referer = null) { $response = $this->_singleScan($url, $referer); if (!$response) { return; } //Returns, if the maximum scanning depth has been reached if ($this->getConfig('maxDepth') && ++$this->currentDepth >= $this->getConfig('maxDepth')) { return; } //Returns, if the response is not ok if (!$response->isOk()) { $this->dispatchEvent('LinkScanner.responseNotOk', [$url]); return; } //Continues scanning for the links found foreach ((new BodyParser($response->getBody(), $url))->extractLinks() as $link) { if (!$this->canBeScanned($link)) { continue; } $this->dispatchEvent('LinkScanner.foundLinkToBeScanned', [$link]); //Single scan for external links, recursive scan for internal links call_user_func_array([$this, is_external_url($link, $this->hostname) ? '_singleScan' : __METHOD__], [$link, $url]); } }
php
protected function _recursiveScan($url, $referer = null) { $response = $this->_singleScan($url, $referer); if (!$response) { return; } //Returns, if the maximum scanning depth has been reached if ($this->getConfig('maxDepth') && ++$this->currentDepth >= $this->getConfig('maxDepth')) { return; } //Returns, if the response is not ok if (!$response->isOk()) { $this->dispatchEvent('LinkScanner.responseNotOk', [$url]); return; } //Continues scanning for the links found foreach ((new BodyParser($response->getBody(), $url))->extractLinks() as $link) { if (!$this->canBeScanned($link)) { continue; } $this->dispatchEvent('LinkScanner.foundLinkToBeScanned', [$link]); //Single scan for external links, recursive scan for internal links call_user_func_array([$this, is_external_url($link, $this->hostname) ? '_singleScan' : __METHOD__], [$link, $url]); } }
[ "protected", "function", "_recursiveScan", "(", "$", "url", ",", "$", "referer", "=", "null", ")", "{", "$", "response", "=", "$", "this", "->", "_singleScan", "(", "$", "url", ",", "$", "referer", ")", ";", "if", "(", "!", "$", "response", ")", "{...
Internal method to perform a recursive scan. It recursively repeats the scan for all urls found that have not already been scanned. ### Events This method will trigger some events: - `LinkScanner.foundLinkToBeScanned`: will be triggered when other links to be scanned are found; - `LinkScanner.responseNotOk`: will be triggered when a single url is scanned and the response is not ok. @param string|array $url Url to scan @param string|null $referer Referer of this url @return void @uses _singleScan() @uses canBeScanned() @uses $alreadyScanned @uses $currentDepth @uses $hostname
[ "Internal", "method", "to", "perform", "a", "recursive", "scan", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L215-L245
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner._singleScan
protected function _singleScan($url, $referer = null) { $url = clean_url($url, true, true); if (!$this->canBeScanned($url)) { return null; } $this->dispatchEvent('LinkScanner.beforeScanUrl', [$url]); $response = $this->_getResponse($url); $this->dispatchEvent('LinkScanner.afterScanUrl', [$response]); //Follows redirects if ($response->isRedirect() && $this->getConfig('followRedirects')) { $location = $response->getHeaderLine('location'); if (!$this->canBeScanned($location)) { return null; } $this->dispatchEvent('LinkScanner.foundRedirect', [$location]); return call_user_func([$this, __METHOD__], $location); } $this->ResultScan = $this->ResultScan->appendItem(new ScanEntity([ 'code' => $response->getStatusCode(), 'external' => is_external_url($url, $this->hostname), 'location' => $response->getHeaderLine('Location'), 'type' => $response->getHeaderLine('content-type'), ] + compact('url', 'referer'))); return $response; }
php
protected function _singleScan($url, $referer = null) { $url = clean_url($url, true, true); if (!$this->canBeScanned($url)) { return null; } $this->dispatchEvent('LinkScanner.beforeScanUrl', [$url]); $response = $this->_getResponse($url); $this->dispatchEvent('LinkScanner.afterScanUrl', [$response]); //Follows redirects if ($response->isRedirect() && $this->getConfig('followRedirects')) { $location = $response->getHeaderLine('location'); if (!$this->canBeScanned($location)) { return null; } $this->dispatchEvent('LinkScanner.foundRedirect', [$location]); return call_user_func([$this, __METHOD__], $location); } $this->ResultScan = $this->ResultScan->appendItem(new ScanEntity([ 'code' => $response->getStatusCode(), 'external' => is_external_url($url, $this->hostname), 'location' => $response->getHeaderLine('Location'), 'type' => $response->getHeaderLine('content-type'), ] + compact('url', 'referer'))); return $response; }
[ "protected", "function", "_singleScan", "(", "$", "url", ",", "$", "referer", "=", "null", ")", "{", "$", "url", "=", "clean_url", "(", "$", "url", ",", "true", ",", "true", ")", ";", "if", "(", "!", "$", "this", "->", "canBeScanned", "(", "$", "...
Internal method to perform a single scan. ### Events This method will trigger some events: - `LinkScanner.beforeScanUrl`: will be triggered before a single url is scanned; - `LinkScanner.afterScanUrl`: will be triggered after a single url is scanned; - `LinkScanner.foundRedirect`: will be triggered if a redirect is found. @param string|array $url Url to scan @param string|null $referer Referer of this url @return ScanResponse|null @uses _getResponse() @uses canBeScanned() @uses $ResultScan @uses $hostname
[ "Internal", "method", "to", "perform", "a", "single", "scan", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L265-L296
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.canBeScanned
protected function canBeScanned($url) { if (!is_url($url) || in_array($url, $this->alreadyScanned) || (!$this->getConfig('externalLinks') && is_external_url($url, $this->hostname))) { return false; } foreach ((array)$this->getConfig('excludeLinks') as $pattern) { if (preg_match($pattern, $url)) { return false; } } return true; }
php
protected function canBeScanned($url) { if (!is_url($url) || in_array($url, $this->alreadyScanned) || (!$this->getConfig('externalLinks') && is_external_url($url, $this->hostname))) { return false; } foreach ((array)$this->getConfig('excludeLinks') as $pattern) { if (preg_match($pattern, $url)) { return false; } } return true; }
[ "protected", "function", "canBeScanned", "(", "$", "url", ")", "{", "if", "(", "!", "is_url", "(", "$", "url", ")", "||", "in_array", "(", "$", "url", ",", "$", "this", "->", "alreadyScanned", ")", "||", "(", "!", "$", "this", "->", "getConfig", "(...
Checks if an url can be scanned. Returns false if: - the url has already been scanned; - it's an external url and the external url scan has been disabled; - the url matches the url patterns to be excluded. @param string $url Url to check @return bool @uses $alreadyScanned @uses $hostname
[ "Checks", "if", "an", "url", "can", "be", "scanned", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L310-L324
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.serialize
public function serialize() { //Unsets the event class and event manager. For the `Client` instance, // it takes only configuration and cookies $properties = get_object_vars($this); unset($properties['_eventClass'], $properties['_eventManager']); $properties['Client'] = $this->Client->getConfig() + ['cookieJar' => $this->Client->cookies()]; return serialize($properties); }
php
public function serialize() { //Unsets the event class and event manager. For the `Client` instance, // it takes only configuration and cookies $properties = get_object_vars($this); unset($properties['_eventClass'], $properties['_eventManager']); $properties['Client'] = $this->Client->getConfig() + ['cookieJar' => $this->Client->cookies()]; return serialize($properties); }
[ "public", "function", "serialize", "(", ")", "{", "//Unsets the event class and event manager. For the `Client` instance,", "// it takes only configuration and cookies", "$", "properties", "=", "get_object_vars", "(", "$", "this", ")", ";", "unset", "(", "$", "properties", ...
Returns the string representation of the object @return string @uses $Client
[ "Returns", "the", "string", "representation", "of", "the", "object" ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L331-L340
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.unserialize
public function unserialize($serialized) { //Resets the event list and the Client instance $properties = unserialize($serialized); $this->getEventManager()->setEventList(new EventList); $this->Client = new Client($properties['Client']); unset($properties['Client']); foreach ($properties as $name => $value) { $this->$name = $value; } }
php
public function unserialize($serialized) { //Resets the event list and the Client instance $properties = unserialize($serialized); $this->getEventManager()->setEventList(new EventList); $this->Client = new Client($properties['Client']); unset($properties['Client']); foreach ($properties as $name => $value) { $this->$name = $value; } }
[ "public", "function", "unserialize", "(", "$", "serialized", ")", "{", "//Resets the event list and the Client instance", "$", "properties", "=", "unserialize", "(", "$", "serialized", ")", ";", "$", "this", "->", "getEventManager", "(", ")", "->", "setEventList", ...
Called during unserialization of the object @param string $serialized The string representation of the object @return void @uses $Client
[ "Called", "during", "unserialization", "of", "the", "object" ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L348-L359
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.export
public function export($filename = null) { is_true_or_fail(!$this->ResultScan->isEmpty(), __d('link-scanner', 'There is no result to export. Perhaps the scan was not performed?'), RuntimeException::class); $filename = $filename ?: sprintf('results_%s_%s', $this->hostname, $this->startTime); $filename = Folder::isAbsolute($filename) ? $filename : Folder::slashTerm($this->getConfig('target')) . $filename; (new File($filename, true))->write(serialize($this)); $this->dispatchEvent('LinkScanner.resultsExported', [$filename]); return $filename; }
php
public function export($filename = null) { is_true_or_fail(!$this->ResultScan->isEmpty(), __d('link-scanner', 'There is no result to export. Perhaps the scan was not performed?'), RuntimeException::class); $filename = $filename ?: sprintf('results_%s_%s', $this->hostname, $this->startTime); $filename = Folder::isAbsolute($filename) ? $filename : Folder::slashTerm($this->getConfig('target')) . $filename; (new File($filename, true))->write(serialize($this)); $this->dispatchEvent('LinkScanner.resultsExported', [$filename]); return $filename; }
[ "public", "function", "export", "(", "$", "filename", "=", "null", ")", "{", "is_true_or_fail", "(", "!", "$", "this", "->", "ResultScan", "->", "isEmpty", "(", ")", ",", "__d", "(", "'link-scanner'", ",", "'There is no result to export. Perhaps the scan was not p...
Exports scan results. The filename will be generated automatically, or you can indicate a relative or absolute path. ### Events This method will trigger some events: - `LinkScanner.resultsExported`: will be triggered when the results have been exported. @param string|null $filename Filename where to export @return string @see serialize() @throws RuntimeException @uses $ResultScan @uses $hostname @uses $startTime
[ "Exports", "scan", "results", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L378-L388
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.import
public static function import($filename) { try { $filename = Folder::isAbsolute($filename) ? $filename : Folder::slashTerm(self::getConfig('target')) . $filename; $instance = unserialize(file_get_contents($filename)); } catch (Exception $e) { $message = preg_replace('/^file_get_contents\([\/\w\d:\-\\\\]+\): /', null, $e->getMessage()); throw new RuntimeException(__d('link-scanner', 'Failed to import results from file `{0}` with message `{1}`', $filename, $message)); } $instance->dispatchEvent('LinkScanner.resultsImported', [$filename]); return $instance; }
php
public static function import($filename) { try { $filename = Folder::isAbsolute($filename) ? $filename : Folder::slashTerm(self::getConfig('target')) . $filename; $instance = unserialize(file_get_contents($filename)); } catch (Exception $e) { $message = preg_replace('/^file_get_contents\([\/\w\d:\-\\\\]+\): /', null, $e->getMessage()); throw new RuntimeException(__d('link-scanner', 'Failed to import results from file `{0}` with message `{1}`', $filename, $message)); } $instance->dispatchEvent('LinkScanner.resultsImported', [$filename]); return $instance; }
[ "public", "static", "function", "import", "(", "$", "filename", ")", "{", "try", "{", "$", "filename", "=", "Folder", "::", "isAbsolute", "(", "$", "filename", ")", "?", "$", "filename", ":", "Folder", "::", "slashTerm", "(", "self", "::", "getConfig", ...
Imports scan results. You can indicate a relative or absolute path. ### Events This method will trigger some events: - `LinkScanner.resultsImported`: will be triggered when the results have been exported. @param string $filename Filename from which to import @return \LinkScanner\Utility\LinkScanner @see unserialize() @throws RuntimeException
[ "Imports", "scan", "results", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L403-L416
train
mirko-pagliai/cakephp-link-scanner
src/Utility/LinkScanner.php
LinkScanner.scan
public function scan() { //Sets the full base url $fullBaseUrl = $this->getConfig('fullBaseUrl', Configure::read('App.fullBaseUrl') ?: 'http://localhost'); is_true_or_fail(is_url($fullBaseUrl), __d('link-scanner', 'Invalid full base url `{0}`', $fullBaseUrl), InvalidArgumentException::class); $this->hostname = get_hostname_from_url($fullBaseUrl); $this->_createLockFile(); $this->startTime = time(); $maxNestingLevel = ini_set('xdebug.max_nesting_level', -1); try { $this->dispatchEvent('LinkScanner.scanStarted', [$this->startTime, $fullBaseUrl]); $this->_recursiveScan($fullBaseUrl); $this->endTime = time(); $this->dispatchEvent('LinkScanner.scanCompleted', [$this->startTime, $this->endTime, $this->ResultScan]); } finally { ini_set('xdebug.max_nesting_level', $maxNestingLevel); @unlink($this->lockFile); } return $this; }
php
public function scan() { //Sets the full base url $fullBaseUrl = $this->getConfig('fullBaseUrl', Configure::read('App.fullBaseUrl') ?: 'http://localhost'); is_true_or_fail(is_url($fullBaseUrl), __d('link-scanner', 'Invalid full base url `{0}`', $fullBaseUrl), InvalidArgumentException::class); $this->hostname = get_hostname_from_url($fullBaseUrl); $this->_createLockFile(); $this->startTime = time(); $maxNestingLevel = ini_set('xdebug.max_nesting_level', -1); try { $this->dispatchEvent('LinkScanner.scanStarted', [$this->startTime, $fullBaseUrl]); $this->_recursiveScan($fullBaseUrl); $this->endTime = time(); $this->dispatchEvent('LinkScanner.scanCompleted', [$this->startTime, $this->endTime, $this->ResultScan]); } finally { ini_set('xdebug.max_nesting_level', $maxNestingLevel); @unlink($this->lockFile); } return $this; }
[ "public", "function", "scan", "(", ")", "{", "//Sets the full base url", "$", "fullBaseUrl", "=", "$", "this", "->", "getConfig", "(", "'fullBaseUrl'", ",", "Configure", "::", "read", "(", "'App.fullBaseUrl'", ")", "?", ":", "'http://localhost'", ")", ";", "is...
Performs a complete scan. ### Events This method will trigger some events: - `LinkScanner.scanStarted`: will be triggered before the scan starts; - `LinkScanner.scanCompleted`: will be triggered after the scan is finished. Other events will be triggered by `_recursiveScan()` and `_singleScan()` methods. @return $this @throws InvalidArgumentException @uses _createLockFile() @uses _recursiveScan() @uses $ResultScan @uses $endTime @uses $hostname @uses $lockFile @uses $startTime
[ "Performs", "a", "complete", "scan", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/Utility/LinkScanner.php#L439-L462
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.getGraph
private function getGraph() { if ($this->graph === null) { $local_repository = $this->composer->getRepositoryManager()->getLocalRepository(); $packages = $local_repository->getPackages(); $packages[] = $this->composer->getPackage(); $supported_packages = $this->getSupportedPackages($packages); $this->setUpAutoloading(); $this->graph = new EntityPackageBuilder($this, $supported_packages); } return $this->graph; }
php
private function getGraph() { if ($this->graph === null) { $local_repository = $this->composer->getRepositoryManager()->getLocalRepository(); $packages = $local_repository->getPackages(); $packages[] = $this->composer->getPackage(); $supported_packages = $this->getSupportedPackages($packages); $this->setUpAutoloading(); $this->graph = new EntityPackageBuilder($this, $supported_packages); } return $this->graph; }
[ "private", "function", "getGraph", "(", ")", "{", "if", "(", "$", "this", "->", "graph", "===", "null", ")", "{", "$", "local_repository", "=", "$", "this", "->", "composer", "->", "getRepositoryManager", "(", ")", "->", "getLocalRepository", "(", ")", "...
Calculate the dependency graph @return \Hostnet\Component\EntityPlugin\EntityPackageBuilder
[ "Calculate", "the", "dependency", "graph" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L84-L95
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.postAutoloadDump
public function postAutoloadDump() { $graph = $this->getGraph(); $this->io->write('<info>Pass 3/3: Performing individual generation</info>'); $this->generateConcreteIndividualCode($graph); }
php
public function postAutoloadDump() { $graph = $this->getGraph(); $this->io->write('<info>Pass 3/3: Performing individual generation</info>'); $this->generateConcreteIndividualCode($graph); }
[ "public", "function", "postAutoloadDump", "(", ")", "{", "$", "graph", "=", "$", "this", "->", "getGraph", "(", ")", ";", "$", "this", "->", "io", "->", "write", "(", "'<info>Pass 3/3: Performing individual generation</info>'", ")", ";", "$", "this", "->", "...
Gets called on the POST_AUTOLOAD_DUMP event
[ "Gets", "called", "on", "the", "POST_AUTOLOAD_DUMP", "event" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L113-L119
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.getSupportedPackages
private function getSupportedPackages(array $packages) { $supported_packages = []; foreach ($packages as $package) { /* @var $package \Composer\Package\PackageInterface */ if ($this->supportsPackage($package)) { $supported_packages[] = $package; } } return $supported_packages; }
php
private function getSupportedPackages(array $packages) { $supported_packages = []; foreach ($packages as $package) { /* @var $package \Composer\Package\PackageInterface */ if ($this->supportsPackage($package)) { $supported_packages[] = $package; } } return $supported_packages; }
[ "private", "function", "getSupportedPackages", "(", "array", "$", "packages", ")", "{", "$", "supported_packages", "=", "[", "]", ";", "foreach", "(", "$", "packages", "as", "$", "package", ")", "{", "/* @var $package \\Composer\\Package\\PackageInterface */", "if",...
Gives all packages that we need to install @param RootPackageInterface[] $packages @return \Composer\Package\PackageInterface[]
[ "Gives", "all", "packages", "that", "we", "need", "to", "install" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L126-L136
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.setUpAutoloading
private function setUpAutoloading() { //Pre-required variable's $package = $this->composer->getPackage(); $autoload_generator = $this->composer->getAutoloadGenerator(); $local_repository = $this->composer->getRepositoryManager()->getLocalRepository(); $installation_manager = $this->composer->getInstallationManager(); if (!$installation_manager) { $installation_manager = new InstallationManager(); } //API stolen from Composer see DumpAutoloadCommand.php $package_map = $autoload_generator->buildPackageMap( $installation_manager, $package, $local_repository->getCanonicalPackages() ); $autoloads = $autoload_generator->parseAutoloads($package_map, $package); //Create the classloader and register the classes. $class_loader = $autoload_generator->createLoader($autoloads); $class_loader->register(); }
php
private function setUpAutoloading() { //Pre-required variable's $package = $this->composer->getPackage(); $autoload_generator = $this->composer->getAutoloadGenerator(); $local_repository = $this->composer->getRepositoryManager()->getLocalRepository(); $installation_manager = $this->composer->getInstallationManager(); if (!$installation_manager) { $installation_manager = new InstallationManager(); } //API stolen from Composer see DumpAutoloadCommand.php $package_map = $autoload_generator->buildPackageMap( $installation_manager, $package, $local_repository->getCanonicalPackages() ); $autoloads = $autoload_generator->parseAutoloads($package_map, $package); //Create the classloader and register the classes. $class_loader = $autoload_generator->createLoader($autoloads); $class_loader->register(); }
[ "private", "function", "setUpAutoloading", "(", ")", "{", "//Pre-required variable's", "$", "package", "=", "$", "this", "->", "composer", "->", "getPackage", "(", ")", ";", "$", "autoload_generator", "=", "$", "this", "->", "composer", "->", "getAutoloadGenerat...
Ensures all the packages are autoloaded, needed because classes are read using reflection.
[ "Ensures", "all", "the", "packages", "are", "autoloaded", "needed", "because", "classes", "are", "read", "using", "reflection", "." ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L154-L176
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.generateEmptyCode
private function generateEmptyCode(EntityPackageBuilder $graph) { foreach ($graph->getEntityPackages() as $entity_package) { /* @var $entity_package EntityPackage */ $this->writeIfVerbose( ' - Preparing package <info>' . $entity_package->getPackage() ->getName() . '</info>' ); foreach ($entity_package->getEntityContent()->getClasses() as $entity) { $this->writeIfVeryVerbose( ' - Generating empty interface for <info>' . $entity->getName() . '</info>' ); $this->empty_generator->generate($entity); } } }
php
private function generateEmptyCode(EntityPackageBuilder $graph) { foreach ($graph->getEntityPackages() as $entity_package) { /* @var $entity_package EntityPackage */ $this->writeIfVerbose( ' - Preparing package <info>' . $entity_package->getPackage() ->getName() . '</info>' ); foreach ($entity_package->getEntityContent()->getClasses() as $entity) { $this->writeIfVeryVerbose( ' - Generating empty interface for <info>' . $entity->getName() . '</info>' ); $this->empty_generator->generate($entity); } } }
[ "private", "function", "generateEmptyCode", "(", "EntityPackageBuilder", "$", "graph", ")", "{", "foreach", "(", "$", "graph", "->", "getEntityPackages", "(", ")", "as", "$", "entity_package", ")", "{", "/* @var $entity_package EntityPackage */", "$", "this", "->", ...
Ensure all interfaces and traits exist @see EmptyGenerator @param EntityPackageBuilder $graph
[ "Ensure", "all", "interfaces", "and", "traits", "exist" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L204-L219
train
hostnet/entity-plugin-lib
src/Installer.php
Installer.generateConcreteIndividualCode
private function generateConcreteIndividualCode(EntityPackageBuilder $graph) { foreach ($graph->getEntityPackages() as $entity_package) { /* @var $entity_package EntityPackage */ $this->writeIfVerbose( ' - Generating for package <info>' . $entity_package->getPackage() ->getName() . '</info>' ); foreach ($entity_package->getEntityContent()->getClasses() as $entity) { $this->writeIfVeryVerbose( ' - Generating interface for <info>' . $entity->getName() . '</info>' ); $this->reflection_generator->generate($entity); } } }
php
private function generateConcreteIndividualCode(EntityPackageBuilder $graph) { foreach ($graph->getEntityPackages() as $entity_package) { /* @var $entity_package EntityPackage */ $this->writeIfVerbose( ' - Generating for package <info>' . $entity_package->getPackage() ->getName() . '</info>' ); foreach ($entity_package->getEntityContent()->getClasses() as $entity) { $this->writeIfVeryVerbose( ' - Generating interface for <info>' . $entity->getName() . '</info>' ); $this->reflection_generator->generate($entity); } } }
[ "private", "function", "generateConcreteIndividualCode", "(", "EntityPackageBuilder", "$", "graph", ")", "{", "foreach", "(", "$", "graph", "->", "getEntityPackages", "(", ")", "as", "$", "entity_package", ")", "{", "/* @var $entity_package EntityPackage */", "$", "th...
Ensure all interfaces and traits are filled with correct methods @param EntityPackageBuilder $graph
[ "Ensure", "all", "interfaces", "and", "traits", "are", "filled", "with", "correct", "methods" ]
49e2292ad64f9a679f3bf3d21880b024e16e5680
https://github.com/hostnet/entity-plugin-lib/blob/49e2292ad64f9a679f3bf3d21880b024e16e5680/src/Installer.php#L226-L241
train
mirko-pagliai/cakephp-link-scanner
src/ResultScan.php
ResultScan.parseItems
protected function parseItems($items) { $items = $items instanceof Traversable ? $items->toArray() : $items; return array_map(function ($item) { return $item instanceof ScanEntity ? $item : new ScanEntity($item); }, $items); }
php
protected function parseItems($items) { $items = $items instanceof Traversable ? $items->toArray() : $items; return array_map(function ($item) { return $item instanceof ScanEntity ? $item : new ScanEntity($item); }, $items); }
[ "protected", "function", "parseItems", "(", "$", "items", ")", "{", "$", "items", "=", "$", "items", "instanceof", "Traversable", "?", "$", "items", "->", "toArray", "(", ")", ":", "$", "items", ";", "return", "array_map", "(", "function", "(", "$", "i...
Internal method to parse items. Ensures that each item is a `ScanEntity` and has all the properties it needs @param array|Traversable $items Array of items @return array Parsed items
[ "Internal", "method", "to", "parse", "items", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/ResultScan.php#L31-L38
train
mirko-pagliai/cakephp-link-scanner
src/ResultScan.php
ResultScan.append
public function append($items) { return new ResultScan(array_merge($this->buffered()->toArray(), $this->parseItems($items))); }
php
public function append($items) { return new ResultScan(array_merge($this->buffered()->toArray(), $this->parseItems($items))); }
[ "public", "function", "append", "(", "$", "items", ")", "{", "return", "new", "ResultScan", "(", "array_merge", "(", "$", "this", "->", "buffered", "(", ")", "->", "toArray", "(", ")", ",", "$", "this", "->", "parseItems", "(", "$", "items", ")", ")"...
Appends items. Returns a new `ResultScan` instance as the result of concatenating the list of elements in this collection with the passed list of elements @param array|Traversable $items Items @return \LinkScanner\ResultScan @uses parseItems()
[ "Appends", "items", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/ResultScan.php#L59-L62
train
mirko-pagliai/cakephp-link-scanner
src/ResultScan.php
ResultScan.prepend
public function prepend($items) { return new ResultScan(array_merge($this->parseItems($items), $this->buffered()->toArray())); }
php
public function prepend($items) { return new ResultScan(array_merge($this->parseItems($items), $this->buffered()->toArray())); }
[ "public", "function", "prepend", "(", "$", "items", ")", "{", "return", "new", "ResultScan", "(", "array_merge", "(", "$", "this", "->", "parseItems", "(", "$", "items", ")", ",", "$", "this", "->", "buffered", "(", ")", "->", "toArray", "(", ")", ")...
Prepends items. Returns a new `ResultScan` instance as the result of concatenating the passed list of elements with the list of elements in this collection @param array|Traversable $items Items @return \LinkScanner\ResultScan @uses parseItems()
[ "Prepends", "items", "." ]
3889f0059f97d7ad7cc95572bd7cfb0384b0f636
https://github.com/mirko-pagliai/cakephp-link-scanner/blob/3889f0059f97d7ad7cc95572bd7cfb0384b0f636/src/ResultScan.php#L73-L76
train
mmoreram/BaseBundle
CompilerPass/MappingCompilerPass.php
MappingCompilerPass.addObjectManager
private function addObjectManager( ContainerBuilder $container, MappingBag $mappingBag ): string { $reducedMappingBag = $mappingBag->getReducedMappingBag(); $definition = new Definition('Doctrine\Common\Persistence\ObjectManager'); $definition->setFactory([ new Reference('base.object_manager_provider'), 'getObjectManagerByEntityNamespace', ]); $class = $this->resolveParameterName($container, $reducedMappingBag->getEntityClass()); $definition->setArguments([$class]); $aliasName = ltrim(($mappingBag->getContainerPrefix().'.'.$mappingBag->getContainerObjectManagerName().'.'.$mappingBag->getEntityName()), '.'); $container->setDefinition( $aliasName, $definition ); return $aliasName; }
php
private function addObjectManager( ContainerBuilder $container, MappingBag $mappingBag ): string { $reducedMappingBag = $mappingBag->getReducedMappingBag(); $definition = new Definition('Doctrine\Common\Persistence\ObjectManager'); $definition->setFactory([ new Reference('base.object_manager_provider'), 'getObjectManagerByEntityNamespace', ]); $class = $this->resolveParameterName($container, $reducedMappingBag->getEntityClass()); $definition->setArguments([$class]); $aliasName = ltrim(($mappingBag->getContainerPrefix().'.'.$mappingBag->getContainerObjectManagerName().'.'.$mappingBag->getEntityName()), '.'); $container->setDefinition( $aliasName, $definition ); return $aliasName; }
[ "private", "function", "addObjectManager", "(", "ContainerBuilder", "$", "container", ",", "MappingBag", "$", "mappingBag", ")", ":", "string", "{", "$", "reducedMappingBag", "=", "$", "mappingBag", "->", "getReducedMappingBag", "(", ")", ";", "$", "definition", ...
Add object manager alias and return the assigned name. @param ContainerBuilder $container @param MappingBag $mappingBag @return string
[ "Add", "object", "manager", "alias", "and", "return", "the", "assigned", "name", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/CompilerPass/MappingCompilerPass.php#L113-L132
train
mmoreram/BaseBundle
CompilerPass/MappingCompilerPass.php
MappingCompilerPass.addObjectDirector
private function addObjectDirector( ContainerBuilder $container, MappingBag $mappingBag, string $objectManagerAliasName, string $objectRepositoryAliasName ) { $definition = new Definition('Mmoreram\BaseBundle\ORM\ObjectDirector'); $definition->setArguments([ new Reference($objectManagerAliasName), new Reference($objectRepositoryAliasName), ]); $definitionName = ltrim(($mappingBag->getContainerPrefix().'.object_director.'.$mappingBag->getEntityName()), '.'); $container->setDefinition( $definitionName, $definition ); }
php
private function addObjectDirector( ContainerBuilder $container, MappingBag $mappingBag, string $objectManagerAliasName, string $objectRepositoryAliasName ) { $definition = new Definition('Mmoreram\BaseBundle\ORM\ObjectDirector'); $definition->setArguments([ new Reference($objectManagerAliasName), new Reference($objectRepositoryAliasName), ]); $definitionName = ltrim(($mappingBag->getContainerPrefix().'.object_director.'.$mappingBag->getEntityName()), '.'); $container->setDefinition( $definitionName, $definition ); }
[ "private", "function", "addObjectDirector", "(", "ContainerBuilder", "$", "container", ",", "MappingBag", "$", "mappingBag", ",", "string", "$", "objectManagerAliasName", ",", "string", "$", "objectRepositoryAliasName", ")", "{", "$", "definition", "=", "new", "Defi...
Add directors. @param ContainerBuilder $container @param MappingBag $mappingBag @param string $objectManagerAliasName @param string $objectRepositoryAliasName
[ "Add", "directors", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/CompilerPass/MappingCompilerPass.php#L171-L187
train
mmoreram/BaseBundle
CompilerPass/MappingCompilerPass.php
MappingCompilerPass.resolveParameterName
private function resolveParameterName( ContainerBuilder $container, $parameterName ) { if (!is_string($parameterName)) { return $parameterName; } return $container->hasParameter($parameterName) ? $container->getParameter($parameterName) : $parameterName; }
php
private function resolveParameterName( ContainerBuilder $container, $parameterName ) { if (!is_string($parameterName)) { return $parameterName; } return $container->hasParameter($parameterName) ? $container->getParameter($parameterName) : $parameterName; }
[ "private", "function", "resolveParameterName", "(", "ContainerBuilder", "$", "container", ",", "$", "parameterName", ")", "{", "if", "(", "!", "is_string", "(", "$", "parameterName", ")", ")", "{", "return", "$", "parameterName", ";", "}", "return", "$", "co...
Return value of parameter name if exists Return itself otherwise. @param ContainerBuilder $container @param mixed $parameterName @return mixed
[ "Return", "value", "of", "parameter", "name", "if", "exists", "Return", "itself", "otherwise", "." ]
5df60df71a659631cb95afd38c8884eda01d418b
https://github.com/mmoreram/BaseBundle/blob/5df60df71a659631cb95afd38c8884eda01d418b/CompilerPass/MappingCompilerPass.php#L198-L209
train