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
dereuromark/cakephp-tags
src/View/Helper/TagCloudHelper.php
TagCloudHelper.display
public function display(array $tags, array $options = [], array $attrs = []) { if (empty($tags)) { return ''; } $options += $this->_config; $tags = $this->calculateWeights($tags); $weights = Hash::extract($tags, $options['extract']); $maxWeight = max($weights); $minWeight = min($weights); // find the range of values $spread = $maxWeight - $minWeight; if ($spread == 0) { $spread = 1; } if ($options['shuffle'] == true) { shuffle($tags); } $cloud = []; foreach ($tags as $tag) { $tagWeight = $tag['weight']; $size = $options['minSize'] + ( ($tagWeight - $minWeight) * ( ($options['maxSize'] - $options['minSize']) / $spread ) ); $size = $tag['size'] = ceil($size); $content = $this->Html->link( $tag[$options['tagModel']]['label'], $this->_tagUrl($tag, $options), ['id' => 'tag-' . $tag[$options['tagModel']]['id']] ); $data = compact('size', 'content'); $cloud[] = $this->templater()->format('item', $data); } $content = implode(PHP_EOL, $cloud); $attrs = $this->templater()->formatAttributes($attrs); $data = compact('attrs', 'content'); return $this->templater()->format('wrapper', $data); }
php
public function display(array $tags, array $options = [], array $attrs = []) { if (empty($tags)) { return ''; } $options += $this->_config; $tags = $this->calculateWeights($tags); $weights = Hash::extract($tags, $options['extract']); $maxWeight = max($weights); $minWeight = min($weights); // find the range of values $spread = $maxWeight - $minWeight; if ($spread == 0) { $spread = 1; } if ($options['shuffle'] == true) { shuffle($tags); } $cloud = []; foreach ($tags as $tag) { $tagWeight = $tag['weight']; $size = $options['minSize'] + ( ($tagWeight - $minWeight) * ( ($options['maxSize'] - $options['minSize']) / $spread ) ); $size = $tag['size'] = ceil($size); $content = $this->Html->link( $tag[$options['tagModel']]['label'], $this->_tagUrl($tag, $options), ['id' => 'tag-' . $tag[$options['tagModel']]['id']] ); $data = compact('size', 'content'); $cloud[] = $this->templater()->format('item', $data); } $content = implode(PHP_EOL, $cloud); $attrs = $this->templater()->formatAttributes($attrs); $data = compact('attrs', 'content'); return $this->templater()->format('wrapper', $data); }
[ "public", "function", "display", "(", "array", "$", "tags", ",", "array", "$", "options", "=", "[", "]", ",", "array", "$", "attrs", "=", "[", "]", ")", "{", "if", "(", "empty", "(", "$", "tags", ")", ")", "{", "return", "''", ";", "}", "$", "options", "+=", "$", "this", "->", "_config", ";", "$", "tags", "=", "$", "this", "->", "calculateWeights", "(", "$", "tags", ")", ";", "$", "weights", "=", "Hash", "::", "extract", "(", "$", "tags", ",", "$", "options", "[", "'extract'", "]", ")", ";", "$", "maxWeight", "=", "max", "(", "$", "weights", ")", ";", "$", "minWeight", "=", "min", "(", "$", "weights", ")", ";", "// find the range of values", "$", "spread", "=", "$", "maxWeight", "-", "$", "minWeight", ";", "if", "(", "$", "spread", "==", "0", ")", "{", "$", "spread", "=", "1", ";", "}", "if", "(", "$", "options", "[", "'shuffle'", "]", "==", "true", ")", "{", "shuffle", "(", "$", "tags", ")", ";", "}", "$", "cloud", "=", "[", "]", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "tagWeight", "=", "$", "tag", "[", "'weight'", "]", ";", "$", "size", "=", "$", "options", "[", "'minSize'", "]", "+", "(", "(", "$", "tagWeight", "-", "$", "minWeight", ")", "*", "(", "(", "$", "options", "[", "'maxSize'", "]", "-", "$", "options", "[", "'minSize'", "]", ")", "/", "$", "spread", ")", ")", ";", "$", "size", "=", "$", "tag", "[", "'size'", "]", "=", "ceil", "(", "$", "size", ")", ";", "$", "content", "=", "$", "this", "->", "Html", "->", "link", "(", "$", "tag", "[", "$", "options", "[", "'tagModel'", "]", "]", "[", "'label'", "]", ",", "$", "this", "->", "_tagUrl", "(", "$", "tag", ",", "$", "options", ")", ",", "[", "'id'", "=>", "'tag-'", ".", "$", "tag", "[", "$", "options", "[", "'tagModel'", "]", "]", "[", "'id'", "]", "]", ")", ";", "$", "data", "=", "compact", "(", "'size'", ",", "'content'", ")", ";", "$", "cloud", "[", "]", "=", "$", "this", "->", "templater", "(", ")", "->", "format", "(", "'item'", ",", "$", "data", ")", ";", "}", "$", "content", "=", "implode", "(", "PHP_EOL", ",", "$", "cloud", ")", ";", "$", "attrs", "=", "$", "this", "->", "templater", "(", ")", "->", "formatAttributes", "(", "$", "attrs", ")", ";", "$", "data", "=", "compact", "(", "'attrs'", ",", "'content'", ")", ";", "return", "$", "this", "->", "templater", "(", ")", "->", "format", "(", "'wrapper'", ",", "$", "data", ")", ";", "}" ]
Method to output a tag-cloud formatted based on the weight of the tags Valid option keys are: - shuffle: true to shuffle the tag list, false to display them in the same order than passed [default: true] - extract: Hash::extract() compatible format string. Path to extract weight values from the $tags array [default: {n}.weight] - templates: Set your wrapper and item (usually ul/li elements). {{size}} will be replaced with tag size calculated from the weight - maxSize: size of the heaviest tag [default: 160] - minSize: size of the lightest tag [default: 80] - url: an array containing the default url - named: the named parameter used to send the tag [default: by]. @param array $tags Tag array to display. @param array $options Display options. @param array $attrs For ul element @return string
[ "Method", "to", "output", "a", "tag", "-", "cloud", "formatted", "based", "on", "the", "weight", "of", "the", "tags" ]
22f4502bffa0254e90d40507c5e6b84abcb800af
https://github.com/dereuromark/cakephp-tags/blob/22f4502bffa0254e90d40507c5e6b84abcb800af/src/View/Helper/TagCloudHelper.php#L71-L118
train
dereuromark/cakephp-tags
src/View/Helper/TagHelper.php
TagHelper.control
public function control(array $options = []) { if ($this->getConfig('strategy') === 'array') { $tags = (array)$this->Form->getSourceValue($this->getConfig('field')); $options += [ 'options' => array_combine($tags, $tags), 'val' => $tags, 'type' => 'select', 'multiple' => true, ]; } $options += [ 'label' => __d('tags', 'Tags'), ]; return $this->Form->control($this->getConfig('field'), $options); }
php
public function control(array $options = []) { if ($this->getConfig('strategy') === 'array') { $tags = (array)$this->Form->getSourceValue($this->getConfig('field')); $options += [ 'options' => array_combine($tags, $tags), 'val' => $tags, 'type' => 'select', 'multiple' => true, ]; } $options += [ 'label' => __d('tags', 'Tags'), ]; return $this->Form->control($this->getConfig('field'), $options); }
[ "public", "function", "control", "(", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "getConfig", "(", "'strategy'", ")", "===", "'array'", ")", "{", "$", "tags", "=", "(", "array", ")", "$", "this", "->", "Form", "->", "getSourceValue", "(", "$", "this", "->", "getConfig", "(", "'field'", ")", ")", ";", "$", "options", "+=", "[", "'options'", "=>", "array_combine", "(", "$", "tags", ",", "$", "tags", ")", ",", "'val'", "=>", "$", "tags", ",", "'type'", "=>", "'select'", ",", "'multiple'", "=>", "true", ",", "]", ";", "}", "$", "options", "+=", "[", "'label'", "=>", "__d", "(", "'tags'", ",", "'Tags'", ")", ",", "]", ";", "return", "$", "this", "->", "Form", "->", "control", "(", "$", "this", "->", "getConfig", "(", "'field'", ")", ",", "$", "options", ")", ";", "}" ]
Convenience method for tag list form input. @param array $options @return string
[ "Convenience", "method", "for", "tag", "list", "form", "input", "." ]
22f4502bffa0254e90d40507c5e6b84abcb800af
https://github.com/dereuromark/cakephp-tags/blob/22f4502bffa0254e90d40507c5e6b84abcb800af/src/View/Helper/TagHelper.php#L57-L74
train
rdohms/dms-filter-bundle
src/DMS/Bundle/FilterBundle/Loader/ContainerAwareLoader.php
ContainerAwareLoader.getFilterForRule
public function getFilterForRule(Rule $rule) { $filterIdentifier = $rule->getFilter(); if ($this->container === null || !$this->container->has($filterIdentifier)) { return parent::getFilterForRule($rule); } return $this->container->get($filterIdentifier); }
php
public function getFilterForRule(Rule $rule) { $filterIdentifier = $rule->getFilter(); if ($this->container === null || !$this->container->has($filterIdentifier)) { return parent::getFilterForRule($rule); } return $this->container->get($filterIdentifier); }
[ "public", "function", "getFilterForRule", "(", "Rule", "$", "rule", ")", "{", "$", "filterIdentifier", "=", "$", "rule", "->", "getFilter", "(", ")", ";", "if", "(", "$", "this", "->", "container", "===", "null", "||", "!", "$", "this", "->", "container", "->", "has", "(", "$", "filterIdentifier", ")", ")", "{", "return", "parent", "::", "getFilterForRule", "(", "$", "rule", ")", ";", "}", "return", "$", "this", "->", "container", "->", "get", "(", "$", "filterIdentifier", ")", ";", "}" ]
Attempts to load Filter from Container or hands off to parent loader. @param Rule $rule @return BaseFilter|null|\stdClass @throws \UnexpectedValueException
[ "Attempts", "to", "load", "Filter", "from", "Container", "or", "hands", "off", "to", "parent", "loader", "." ]
25ff741f3339a41bec7c170a4f0d086a05960b90
https://github.com/rdohms/dms-filter-bundle/blob/25ff741f3339a41bec7c170a4f0d086a05960b90/src/DMS/Bundle/FilterBundle/Loader/ContainerAwareLoader.php#L33-L42
train
mvar/log-parser
src/LogIterator.php
LogIterator.current
public function current() { if ($this->currentLine === null) { $this->readLine(); } try { $data = $this->parser->parseLine($this->currentLine); } catch (MatchException $exception) { $data = null; } return $data; }
php
public function current() { if ($this->currentLine === null) { $this->readLine(); } try { $data = $this->parser->parseLine($this->currentLine); } catch (MatchException $exception) { $data = null; } return $data; }
[ "public", "function", "current", "(", ")", "{", "if", "(", "$", "this", "->", "currentLine", "===", "null", ")", "{", "$", "this", "->", "readLine", "(", ")", ";", "}", "try", "{", "$", "data", "=", "$", "this", "->", "parser", "->", "parseLine", "(", "$", "this", "->", "currentLine", ")", ";", "}", "catch", "(", "MatchException", "$", "exception", ")", "{", "$", "data", "=", "null", ";", "}", "return", "$", "data", ";", "}" ]
Returns parsed current line. @return array|null
[ "Returns", "parsed", "current", "line", "." ]
f7fc6d907924b603f9d97ab2df5f9a6106cc5d84
https://github.com/mvar/log-parser/blob/f7fc6d907924b603f9d97ab2df5f9a6106cc5d84/src/LogIterator.php#L118-L131
train
dereuromark/cakephp-setup
src/Shell/MailmapShell.php
MailmapShell.generate
public function generate($path = null) { $path = $this->getPath($path); $this->out('Reading ' . $path . '.mailmap'); $existingMap = $this->parseMailmap($path); $this->out('Found ' . count($this->map) . ' existing entries in .mailmap file'); $rows = $this->parseHistory($path, $existingMap); $array = []; foreach ($rows as $row) { $key = strtolower($row['email']); $array[$key][] = $row; } $map = $this->map; foreach ($array as $elements) { if (count($elements) < 2) { continue; } $primary = array_shift($elements); $map[] = $primary['content']; foreach ($elements as $element) { $map[] = $primary['content'] . ' ' . $element['content']; } } $file = $path . '.mailmap'; if ($this->params['dry-run']) { $file = TMP . '.mailmap'; } file_put_contents($file, implode(PHP_EOL, $map)); $this->out((count($map) - count($this->map)) . ' additional rows written to ' . $file); }
php
public function generate($path = null) { $path = $this->getPath($path); $this->out('Reading ' . $path . '.mailmap'); $existingMap = $this->parseMailmap($path); $this->out('Found ' . count($this->map) . ' existing entries in .mailmap file'); $rows = $this->parseHistory($path, $existingMap); $array = []; foreach ($rows as $row) { $key = strtolower($row['email']); $array[$key][] = $row; } $map = $this->map; foreach ($array as $elements) { if (count($elements) < 2) { continue; } $primary = array_shift($elements); $map[] = $primary['content']; foreach ($elements as $element) { $map[] = $primary['content'] . ' ' . $element['content']; } } $file = $path . '.mailmap'; if ($this->params['dry-run']) { $file = TMP . '.mailmap'; } file_put_contents($file, implode(PHP_EOL, $map)); $this->out((count($map) - count($this->map)) . ' additional rows written to ' . $file); }
[ "public", "function", "generate", "(", "$", "path", "=", "null", ")", "{", "$", "path", "=", "$", "this", "->", "getPath", "(", "$", "path", ")", ";", "$", "this", "->", "out", "(", "'Reading '", ".", "$", "path", ".", "'.mailmap'", ")", ";", "$", "existingMap", "=", "$", "this", "->", "parseMailmap", "(", "$", "path", ")", ";", "$", "this", "->", "out", "(", "'Found '", ".", "count", "(", "$", "this", "->", "map", ")", ".", "' existing entries in .mailmap file'", ")", ";", "$", "rows", "=", "$", "this", "->", "parseHistory", "(", "$", "path", ",", "$", "existingMap", ")", ";", "$", "array", "=", "[", "]", ";", "foreach", "(", "$", "rows", "as", "$", "row", ")", "{", "$", "key", "=", "strtolower", "(", "$", "row", "[", "'email'", "]", ")", ";", "$", "array", "[", "$", "key", "]", "[", "]", "=", "$", "row", ";", "}", "$", "map", "=", "$", "this", "->", "map", ";", "foreach", "(", "$", "array", "as", "$", "elements", ")", "{", "if", "(", "count", "(", "$", "elements", ")", "<", "2", ")", "{", "continue", ";", "}", "$", "primary", "=", "array_shift", "(", "$", "elements", ")", ";", "$", "map", "[", "]", "=", "$", "primary", "[", "'content'", "]", ";", "foreach", "(", "$", "elements", "as", "$", "element", ")", "{", "$", "map", "[", "]", "=", "$", "primary", "[", "'content'", "]", ".", "' '", ".", "$", "element", "[", "'content'", "]", ";", "}", "}", "$", "file", "=", "$", "path", ".", "'.mailmap'", ";", "if", "(", "$", "this", "->", "params", "[", "'dry-run'", "]", ")", "{", "$", "file", "=", "TMP", ".", "'.mailmap'", ";", "}", "file_put_contents", "(", "$", "file", ",", "implode", "(", "PHP_EOL", ",", "$", "map", ")", ")", ";", "$", "this", "->", "out", "(", "(", "count", "(", "$", "map", ")", "-", "count", "(", "$", "this", "->", "map", ")", ")", ".", "' additional rows written to '", ".", "$", "file", ")", ";", "}" ]
Generates .mailmap file. @param string|null $path @return void
[ "Generates", ".", "mailmap", "file", "." ]
8642d546652bf3d75beb1513370dcf3490b17389
https://github.com/dereuromark/cakephp-setup/blob/8642d546652bf3d75beb1513370dcf3490b17389/src/Shell/MailmapShell.php#L28-L67
train
rdohms/dms-filter-bundle
src/DMS/Bundle/FilterBundle/Filter/ContainerFilter.php
ContainerFilter.apply
public function apply(Rule $rule, $value) { if (!$this->container->has($rule->service)) { throw new \RuntimeException("Unable to find service '{$rule->service}' to execute defined rule."); } $service = $this->container->get($rule->service); if (! \is_callable([$service, $rule->method])) { throw new \RuntimeException("Unable to find the method '{$rule->method}' in service '{$rule->service}'."); } $method = $rule->method; return $service->$method($value); }
php
public function apply(Rule $rule, $value) { if (!$this->container->has($rule->service)) { throw new \RuntimeException("Unable to find service '{$rule->service}' to execute defined rule."); } $service = $this->container->get($rule->service); if (! \is_callable([$service, $rule->method])) { throw new \RuntimeException("Unable to find the method '{$rule->method}' in service '{$rule->service}'."); } $method = $rule->method; return $service->$method($value); }
[ "public", "function", "apply", "(", "Rule", "$", "rule", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "container", "->", "has", "(", "$", "rule", "->", "service", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unable to find service '{$rule->service}' to execute defined rule.\"", ")", ";", "}", "$", "service", "=", "$", "this", "->", "container", "->", "get", "(", "$", "rule", "->", "service", ")", ";", "if", "(", "!", "\\", "is_callable", "(", "[", "$", "service", ",", "$", "rule", "->", "method", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Unable to find the method '{$rule->method}' in service '{$rule->service}'.\"", ")", ";", "}", "$", "method", "=", "$", "rule", "->", "method", ";", "return", "$", "service", "->", "$", "method", "(", "$", "value", ")", ";", "}" ]
Enforces the desired filtering on the the value returning a filtered value. @param Service|Rule $rule @param mixed $value @throws \RuntimeException @return mixed
[ "Enforces", "the", "desired", "filtering", "on", "the", "the", "value", "returning", "a", "filtered", "value", "." ]
25ff741f3339a41bec7c170a4f0d086a05960b90
https://github.com/rdohms/dms-filter-bundle/blob/25ff741f3339a41bec7c170a4f0d086a05960b90/src/DMS/Bundle/FilterBundle/Filter/ContainerFilter.php#L40-L55
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.hide_promo
private function hide_promo() { $hide_promo = get_transient( 'yoast_i18n_' . $this->project_slug . '_promo_hide' ); if ( ! $hide_promo ) { if ( filter_input( INPUT_GET, 'remove_i18n_promo', FILTER_VALIDATE_INT ) === 1 ) { // No expiration time, so this would normally not expire, but it wouldn't be copied to other sites etc. set_transient( 'yoast_i18n_' . $this->project_slug . '_promo_hide', true ); $hide_promo = true; } } return $hide_promo; }
php
private function hide_promo() { $hide_promo = get_transient( 'yoast_i18n_' . $this->project_slug . '_promo_hide' ); if ( ! $hide_promo ) { if ( filter_input( INPUT_GET, 'remove_i18n_promo', FILTER_VALIDATE_INT ) === 1 ) { // No expiration time, so this would normally not expire, but it wouldn't be copied to other sites etc. set_transient( 'yoast_i18n_' . $this->project_slug . '_promo_hide', true ); $hide_promo = true; } } return $hide_promo; }
[ "private", "function", "hide_promo", "(", ")", "{", "$", "hide_promo", "=", "get_transient", "(", "'yoast_i18n_'", ".", "$", "this", "->", "project_slug", ".", "'_promo_hide'", ")", ";", "if", "(", "!", "$", "hide_promo", ")", "{", "if", "(", "filter_input", "(", "INPUT_GET", ",", "'remove_i18n_promo'", ",", "FILTER_VALIDATE_INT", ")", "===", "1", ")", "{", "// No expiration time, so this would normally not expire, but it wouldn't be copied to other sites etc.", "set_transient", "(", "'yoast_i18n_'", ".", "$", "this", "->", "project_slug", ".", "'_promo_hide'", ",", "true", ")", ";", "$", "hide_promo", "=", "true", ";", "}", "}", "return", "$", "hide_promo", ";", "}" ]
Check whether the promo should be hidden or not. @access private @return bool
[ "Check", "whether", "the", "promo", "should", "be", "hidden", "or", "not", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L191-L201
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.promo_message
private function promo_message() { $this->translation_details(); $message = false; if ( $this->translation_exists && $this->translation_loaded && $this->percent_translated < 90 ) { /* translators: 1: language name; 3: completion percentage; 4: link to translation platform. */ $message = __( 'As you can see, there is a translation of this plugin in %1$s. This translation is currently %3$d%% complete. We need your help to make it complete and to fix any errors. Please register at %4$s to help complete the translation to %1$s!', $this->textdomain ); } elseif ( ! $this->translation_loaded && $this->translation_exists ) { /* translators: 1: language name; 2: plugin name; 3: completion percentage; 4: link to translation platform. */ $message = __( 'You\'re using WordPress in %1$s. While %2$s has been translated to %1$s for %3$d%%, it\'s not been shipped with the plugin yet. You can help! Register at %4$s to help complete the translation to %1$s!', $this->textdomain ); } elseif ( ! $this->translation_exists ) { /* translators: 2: plugin name; 4: link to translation platform. */ $message = __( 'You\'re using WordPress in a language we don\'t support yet. We\'d love for %2$s to be translated in that language too, but unfortunately, it isn\'t right now. You can change that! Register at %4$s to help translate it!', $this->textdomain ); } $registration_link = sprintf( '<a href="%1$s">%2$s</a>', esc_url( $this->register_url ), esc_html( $this->glotpress_name ) ); $message = sprintf( esc_html( $message ), esc_html( $this->locale_name ), esc_html( $this->plugin_name ), (int) $this->percent_translated, $registration_link ); if ( $message ) { $message = '<p>' . $message . '</p><p><a href="' . esc_url( $this->register_url ) . '">' . esc_html__( 'Register now &raquo;', $this->textdomain ) . '</a></p>'; } return $message; }
php
private function promo_message() { $this->translation_details(); $message = false; if ( $this->translation_exists && $this->translation_loaded && $this->percent_translated < 90 ) { /* translators: 1: language name; 3: completion percentage; 4: link to translation platform. */ $message = __( 'As you can see, there is a translation of this plugin in %1$s. This translation is currently %3$d%% complete. We need your help to make it complete and to fix any errors. Please register at %4$s to help complete the translation to %1$s!', $this->textdomain ); } elseif ( ! $this->translation_loaded && $this->translation_exists ) { /* translators: 1: language name; 2: plugin name; 3: completion percentage; 4: link to translation platform. */ $message = __( 'You\'re using WordPress in %1$s. While %2$s has been translated to %1$s for %3$d%%, it\'s not been shipped with the plugin yet. You can help! Register at %4$s to help complete the translation to %1$s!', $this->textdomain ); } elseif ( ! $this->translation_exists ) { /* translators: 2: plugin name; 4: link to translation platform. */ $message = __( 'You\'re using WordPress in a language we don\'t support yet. We\'d love for %2$s to be translated in that language too, but unfortunately, it isn\'t right now. You can change that! Register at %4$s to help translate it!', $this->textdomain ); } $registration_link = sprintf( '<a href="%1$s">%2$s</a>', esc_url( $this->register_url ), esc_html( $this->glotpress_name ) ); $message = sprintf( esc_html( $message ), esc_html( $this->locale_name ), esc_html( $this->plugin_name ), (int) $this->percent_translated, $registration_link ); if ( $message ) { $message = '<p>' . $message . '</p><p><a href="' . esc_url( $this->register_url ) . '">' . esc_html__( 'Register now &raquo;', $this->textdomain ) . '</a></p>'; } return $message; }
[ "private", "function", "promo_message", "(", ")", "{", "$", "this", "->", "translation_details", "(", ")", ";", "$", "message", "=", "false", ";", "if", "(", "$", "this", "->", "translation_exists", "&&", "$", "this", "->", "translation_loaded", "&&", "$", "this", "->", "percent_translated", "<", "90", ")", "{", "/* translators: 1: language name; 3: completion percentage; 4: link to translation platform. */", "$", "message", "=", "__", "(", "'As you can see, there is a translation of this plugin in %1$s. This translation is currently %3$d%% complete. We need your help to make it complete and to fix any errors. Please register at %4$s to help complete the translation to %1$s!'", ",", "$", "this", "->", "textdomain", ")", ";", "}", "elseif", "(", "!", "$", "this", "->", "translation_loaded", "&&", "$", "this", "->", "translation_exists", ")", "{", "/* translators: 1: language name; 2: plugin name; 3: completion percentage; 4: link to translation platform. */", "$", "message", "=", "__", "(", "'You\\'re using WordPress in %1$s. While %2$s has been translated to %1$s for %3$d%%, it\\'s not been shipped with the plugin yet. You can help! Register at %4$s to help complete the translation to %1$s!'", ",", "$", "this", "->", "textdomain", ")", ";", "}", "elseif", "(", "!", "$", "this", "->", "translation_exists", ")", "{", "/* translators: 2: plugin name; 4: link to translation platform. */", "$", "message", "=", "__", "(", "'You\\'re using WordPress in a language we don\\'t support yet. We\\'d love for %2$s to be translated in that language too, but unfortunately, it isn\\'t right now. You can change that! Register at %4$s to help translate it!'", ",", "$", "this", "->", "textdomain", ")", ";", "}", "$", "registration_link", "=", "sprintf", "(", "'<a href=\"%1$s\">%2$s</a>'", ",", "esc_url", "(", "$", "this", "->", "register_url", ")", ",", "esc_html", "(", "$", "this", "->", "glotpress_name", ")", ")", ";", "$", "message", "=", "sprintf", "(", "esc_html", "(", "$", "message", ")", ",", "esc_html", "(", "$", "this", "->", "locale_name", ")", ",", "esc_html", "(", "$", "this", "->", "plugin_name", ")", ",", "(", "int", ")", "$", "this", "->", "percent_translated", ",", "$", "registration_link", ")", ";", "if", "(", "$", "message", ")", "{", "$", "message", "=", "'<p>'", ".", "$", "message", ".", "'</p><p><a href=\"'", ".", "esc_url", "(", "$", "this", "->", "register_url", ")", ".", "'\">'", ".", "esc_html__", "(", "'Register now &raquo;'", ",", "$", "this", "->", "textdomain", ")", ".", "'</a></p>'", ";", "}", "return", "$", "message", ";", "}" ]
Generates a promo message. @access private @return bool|string $message
[ "Generates", "a", "promo", "message", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L225-L263
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.promo
public function promo() { $message = $this->get_promo_message(); if ( $message ) { echo '<div id="i18n_promo_box" style="border:1px solid #ccc;background-color:#fff;padding:10px;max-width:650px; overflow: hidden;">'; echo '<a href="' . esc_url( add_query_arg( array( 'remove_i18n_promo' => '1' ) ) ) . '" style="color:#333;text-decoration:none;font-weight:bold;font-size:16px;border:1px solid #ccc;padding:1px 4px;" class="alignright">X</a>'; echo '<div>'; /* translators: %s: plugin name. */ echo '<h2>' . sprintf( esc_html__( 'Translation of %s', $this->textdomain ), esc_html( $this->plugin_name ) ) . '</h2>'; if ( isset( $this->glotpress_logo ) && is_string( $this->glotpress_logo ) && '' !== $this->glotpress_logo ) { echo '<a href="' . esc_url( $this->register_url ) . '"><img class="alignright" style="margin:0 5px 5px 5px;max-width:200px;" src="' . esc_url( $this->glotpress_logo ) . '" alt="' . esc_attr( $this->glotpress_name ) . '"/></a>'; } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- correctly escaped in promo_message() method. echo $message; echo '</div>'; echo '</div>'; } }
php
public function promo() { $message = $this->get_promo_message(); if ( $message ) { echo '<div id="i18n_promo_box" style="border:1px solid #ccc;background-color:#fff;padding:10px;max-width:650px; overflow: hidden;">'; echo '<a href="' . esc_url( add_query_arg( array( 'remove_i18n_promo' => '1' ) ) ) . '" style="color:#333;text-decoration:none;font-weight:bold;font-size:16px;border:1px solid #ccc;padding:1px 4px;" class="alignright">X</a>'; echo '<div>'; /* translators: %s: plugin name. */ echo '<h2>' . sprintf( esc_html__( 'Translation of %s', $this->textdomain ), esc_html( $this->plugin_name ) ) . '</h2>'; if ( isset( $this->glotpress_logo ) && is_string( $this->glotpress_logo ) && '' !== $this->glotpress_logo ) { echo '<a href="' . esc_url( $this->register_url ) . '"><img class="alignright" style="margin:0 5px 5px 5px;max-width:200px;" src="' . esc_url( $this->glotpress_logo ) . '" alt="' . esc_attr( $this->glotpress_name ) . '"/></a>'; } // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- correctly escaped in promo_message() method. echo $message; echo '</div>'; echo '</div>'; } }
[ "public", "function", "promo", "(", ")", "{", "$", "message", "=", "$", "this", "->", "get_promo_message", "(", ")", ";", "if", "(", "$", "message", ")", "{", "echo", "'<div id=\"i18n_promo_box\" style=\"border:1px solid #ccc;background-color:#fff;padding:10px;max-width:650px; overflow: hidden;\">'", ";", "echo", "'<a href=\"'", ".", "esc_url", "(", "add_query_arg", "(", "array", "(", "'remove_i18n_promo'", "=>", "'1'", ")", ")", ")", ".", "'\" style=\"color:#333;text-decoration:none;font-weight:bold;font-size:16px;border:1px solid #ccc;padding:1px 4px;\" class=\"alignright\">X</a>'", ";", "echo", "'<div>'", ";", "/* translators: %s: plugin name. */", "echo", "'<h2>'", ".", "sprintf", "(", "esc_html__", "(", "'Translation of %s'", ",", "$", "this", "->", "textdomain", ")", ",", "esc_html", "(", "$", "this", "->", "plugin_name", ")", ")", ".", "'</h2>'", ";", "if", "(", "isset", "(", "$", "this", "->", "glotpress_logo", ")", "&&", "is_string", "(", "$", "this", "->", "glotpress_logo", ")", "&&", "''", "!==", "$", "this", "->", "glotpress_logo", ")", "{", "echo", "'<a href=\"'", ".", "esc_url", "(", "$", "this", "->", "register_url", ")", ".", "'\"><img class=\"alignright\" style=\"margin:0 5px 5px 5px;max-width:200px;\" src=\"'", ".", "esc_url", "(", "$", "this", "->", "glotpress_logo", ")", ".", "'\" alt=\"'", ".", "esc_attr", "(", "$", "this", "->", "glotpress_name", ")", ".", "'\"/></a>'", ";", "}", "// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- correctly escaped in promo_message() method.", "echo", "$", "message", ";", "echo", "'</div>'", ";", "echo", "'</div>'", ";", "}", "}" ]
Outputs a promo box. @access public
[ "Outputs", "a", "promo", "box", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L286-L304
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.find_or_initialize_translation_details
private function find_or_initialize_translation_details() { $set = get_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale ); if ( ! $set ) { $set = $this->retrieve_translation_details(); set_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale, $set, DAY_IN_SECONDS ); } return $set; }
php
private function find_or_initialize_translation_details() { $set = get_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale ); if ( ! $set ) { $set = $this->retrieve_translation_details(); set_transient( 'yoast_i18n_' . $this->project_slug . '_' . $this->locale, $set, DAY_IN_SECONDS ); } return $set; }
[ "private", "function", "find_or_initialize_translation_details", "(", ")", "{", "$", "set", "=", "get_transient", "(", "'yoast_i18n_'", ".", "$", "this", "->", "project_slug", ".", "'_'", ".", "$", "this", "->", "locale", ")", ";", "if", "(", "!", "$", "set", ")", "{", "$", "set", "=", "$", "this", "->", "retrieve_translation_details", "(", ")", ";", "set_transient", "(", "'yoast_i18n_'", ".", "$", "this", "->", "project_slug", ".", "'_'", ".", "$", "this", "->", "locale", ",", "$", "set", ",", "DAY_IN_SECONDS", ")", ";", "}", "return", "$", "set", ";", "}" ]
Try to find the transient for the translation set or retrieve them. @access private @return object|null
[ "Try", "to", "find", "the", "transient", "for", "the", "translation", "set", "or", "retrieve", "them", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L313-L322
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.translation_details
private function translation_details() { $set = $this->find_or_initialize_translation_details(); $this->translation_exists = ! is_null( $set ); $this->translation_loaded = is_textdomain_loaded( $this->textdomain ); $this->parse_translation_set( $set ); }
php
private function translation_details() { $set = $this->find_or_initialize_translation_details(); $this->translation_exists = ! is_null( $set ); $this->translation_loaded = is_textdomain_loaded( $this->textdomain ); $this->parse_translation_set( $set ); }
[ "private", "function", "translation_details", "(", ")", "{", "$", "set", "=", "$", "this", "->", "find_or_initialize_translation_details", "(", ")", ";", "$", "this", "->", "translation_exists", "=", "!", "is_null", "(", "$", "set", ")", ";", "$", "this", "->", "translation_loaded", "=", "is_textdomain_loaded", "(", "$", "this", "->", "textdomain", ")", ";", "$", "this", "->", "parse_translation_set", "(", "$", "set", ")", ";", "}" ]
Try to get translation details from cache, otherwise retrieve them, then parse them. @access private
[ "Try", "to", "get", "translation", "details", "from", "cache", "otherwise", "retrieve", "them", "then", "parse", "them", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L329-L336
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.get_api_url
private function get_api_url() { if ( empty( $this->api_url ) ) { $this->api_url = trailingslashit( $this->glotpress_url ) . 'api/projects/' . $this->project_slug; } return $this->api_url; }
php
private function get_api_url() { if ( empty( $this->api_url ) ) { $this->api_url = trailingslashit( $this->glotpress_url ) . 'api/projects/' . $this->project_slug; } return $this->api_url; }
[ "private", "function", "get_api_url", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "api_url", ")", ")", "{", "$", "this", "->", "api_url", "=", "trailingslashit", "(", "$", "this", "->", "glotpress_url", ")", ".", "'api/projects/'", ".", "$", "this", "->", "project_slug", ";", "}", "return", "$", "this", "->", "api_url", ";", "}" ]
Returns the API URL to use when requesting translation information. @return string
[ "Returns", "the", "API", "URL", "to", "use", "when", "requesting", "translation", "information", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L352-L358
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.retrieve_translation_details
private function retrieve_translation_details() { $api_url = $this->get_api_url(); $resp = wp_remote_get( $api_url ); if ( is_wp_error( $resp ) || wp_remote_retrieve_response_code( $resp ) !== 200 ) { return null; } $body = wp_remote_retrieve_body( $resp ); unset( $resp ); if ( $body ) { $body = json_decode( $body ); if ( empty( $body->translation_sets ) ) { return null; } foreach ( $body->translation_sets as $set ) { if ( ! property_exists( $set, 'wp_locale' ) ) { continue; } // For informal and formal locales, we have to complete the locale code by concatenating the slug ('formal' or 'informal') to the xx_XX part. if ( $set->slug !== 'default' && strtolower( $this->locale ) === strtolower( $set->wp_locale . '_' . $set->slug ) ) { return $set; } if ( $this->locale === $set->wp_locale ) { return $set; } } } return null; }
php
private function retrieve_translation_details() { $api_url = $this->get_api_url(); $resp = wp_remote_get( $api_url ); if ( is_wp_error( $resp ) || wp_remote_retrieve_response_code( $resp ) !== 200 ) { return null; } $body = wp_remote_retrieve_body( $resp ); unset( $resp ); if ( $body ) { $body = json_decode( $body ); if ( empty( $body->translation_sets ) ) { return null; } foreach ( $body->translation_sets as $set ) { if ( ! property_exists( $set, 'wp_locale' ) ) { continue; } // For informal and formal locales, we have to complete the locale code by concatenating the slug ('formal' or 'informal') to the xx_XX part. if ( $set->slug !== 'default' && strtolower( $this->locale ) === strtolower( $set->wp_locale . '_' . $set->slug ) ) { return $set; } if ( $this->locale === $set->wp_locale ) { return $set; } } } return null; }
[ "private", "function", "retrieve_translation_details", "(", ")", "{", "$", "api_url", "=", "$", "this", "->", "get_api_url", "(", ")", ";", "$", "resp", "=", "wp_remote_get", "(", "$", "api_url", ")", ";", "if", "(", "is_wp_error", "(", "$", "resp", ")", "||", "wp_remote_retrieve_response_code", "(", "$", "resp", ")", "!==", "200", ")", "{", "return", "null", ";", "}", "$", "body", "=", "wp_remote_retrieve_body", "(", "$", "resp", ")", ";", "unset", "(", "$", "resp", ")", ";", "if", "(", "$", "body", ")", "{", "$", "body", "=", "json_decode", "(", "$", "body", ")", ";", "if", "(", "empty", "(", "$", "body", "->", "translation_sets", ")", ")", "{", "return", "null", ";", "}", "foreach", "(", "$", "body", "->", "translation_sets", "as", "$", "set", ")", "{", "if", "(", "!", "property_exists", "(", "$", "set", ",", "'wp_locale'", ")", ")", "{", "continue", ";", "}", "// For informal and formal locales, we have to complete the locale code by concatenating the slug ('formal' or 'informal') to the xx_XX part.", "if", "(", "$", "set", "->", "slug", "!==", "'default'", "&&", "strtolower", "(", "$", "this", "->", "locale", ")", "===", "strtolower", "(", "$", "set", "->", "wp_locale", ".", "'_'", ".", "$", "set", "->", "slug", ")", ")", "{", "return", "$", "set", ";", "}", "if", "(", "$", "this", "->", "locale", "===", "$", "set", "->", "wp_locale", ")", "{", "return", "$", "set", ";", "}", "}", "}", "return", "null", ";", "}" ]
Retrieve the translation details from Yoast Translate. @access private @return object|null
[ "Retrieve", "the", "translation", "details", "from", "Yoast", "Translate", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L367-L399
train
Yoast/i18n-module
src/i18n-v3.php
Yoast_I18n_V3.parse_translation_set
private function parse_translation_set( $set ) { if ( $this->translation_exists && is_object( $set ) ) { $this->locale_name = $set->name; $this->percent_translated = $set->percent_translated; } else { $this->locale_name = ''; $this->percent_translated = ''; } }
php
private function parse_translation_set( $set ) { if ( $this->translation_exists && is_object( $set ) ) { $this->locale_name = $set->name; $this->percent_translated = $set->percent_translated; } else { $this->locale_name = ''; $this->percent_translated = ''; } }
[ "private", "function", "parse_translation_set", "(", "$", "set", ")", "{", "if", "(", "$", "this", "->", "translation_exists", "&&", "is_object", "(", "$", "set", ")", ")", "{", "$", "this", "->", "locale_name", "=", "$", "set", "->", "name", ";", "$", "this", "->", "percent_translated", "=", "$", "set", "->", "percent_translated", ";", "}", "else", "{", "$", "this", "->", "locale_name", "=", "''", ";", "$", "this", "->", "percent_translated", "=", "''", ";", "}", "}" ]
Set the needed private variables based on the results from Yoast Translate. @param object $set The translation set. @access private
[ "Set", "the", "needed", "private", "variables", "based", "on", "the", "results", "from", "Yoast", "Translate", "." ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-v3.php#L408-L417
train
Yoast/i18n-module
src/i18n-wordpressorg-v3.php
Yoast_I18n_WordPressOrg_V3.set_defaults
private function set_defaults( $args ) { if ( ! isset( $args['glotpress_logo'] ) ) { $args['glotpress_logo'] = 'https://plugins.svn.wordpress.org/' . $args['textdomain'] . '/assets/icon-128x128.png'; } if ( ! isset( $args['register_url'] ) ) { $args['register_url'] = 'https://translate.wordpress.org/projects/wp-plugins/' . $args['textdomain'] . '/'; } if ( ! isset( $args['glotpress_name'] ) ) { $args['glotpress_name'] = 'Translating WordPress'; } if ( ! isset( $args['project_slug'] ) ) { $args['project_slug'] = $args['textdomain']; } return $args; }
php
private function set_defaults( $args ) { if ( ! isset( $args['glotpress_logo'] ) ) { $args['glotpress_logo'] = 'https://plugins.svn.wordpress.org/' . $args['textdomain'] . '/assets/icon-128x128.png'; } if ( ! isset( $args['register_url'] ) ) { $args['register_url'] = 'https://translate.wordpress.org/projects/wp-plugins/' . $args['textdomain'] . '/'; } if ( ! isset( $args['glotpress_name'] ) ) { $args['glotpress_name'] = 'Translating WordPress'; } if ( ! isset( $args['project_slug'] ) ) { $args['project_slug'] = $args['textdomain']; } return $args; }
[ "private", "function", "set_defaults", "(", "$", "args", ")", "{", "if", "(", "!", "isset", "(", "$", "args", "[", "'glotpress_logo'", "]", ")", ")", "{", "$", "args", "[", "'glotpress_logo'", "]", "=", "'https://plugins.svn.wordpress.org/'", ".", "$", "args", "[", "'textdomain'", "]", ".", "'/assets/icon-128x128.png'", ";", "}", "if", "(", "!", "isset", "(", "$", "args", "[", "'register_url'", "]", ")", ")", "{", "$", "args", "[", "'register_url'", "]", "=", "'https://translate.wordpress.org/projects/wp-plugins/'", ".", "$", "args", "[", "'textdomain'", "]", ".", "'/'", ";", "}", "if", "(", "!", "isset", "(", "$", "args", "[", "'glotpress_name'", "]", ")", ")", "{", "$", "args", "[", "'glotpress_name'", "]", "=", "'Translating WordPress'", ";", "}", "if", "(", "!", "isset", "(", "$", "args", "[", "'project_slug'", "]", ")", ")", "{", "$", "args", "[", "'project_slug'", "]", "=", "$", "args", "[", "'textdomain'", "]", ";", "}", "return", "$", "args", ";", "}" ]
Sets the default values for wordpress.org @param array $args The arguments to set defaults for. @return array The arguments with the arguments set.
[ "Sets", "the", "default", "values", "for", "wordpress", ".", "org" ]
36f0a12aa18e20bee6d89f0618bdc03941e1f299
https://github.com/Yoast/i18n-module/blob/36f0a12aa18e20bee6d89f0618bdc03941e1f299/src/i18n-wordpressorg-v3.php#L64-L83
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php
SocialNetworksAwareTrait.socialNetworks
public function socialNetworks() { if ($this->socialNetworks) { return $this->socialNetworks; } $socials = json_decode($this->cmsConfig()['social_medias'], true); $configMeta = $this->configModel()->p('social_medias')->structureMetadata(); foreach ($socials as $ident => $account) { $prefix = $configMeta->property($ident)['input_prefix']; $socials[$ident] = [ 'account' => $account, 'prefix' => $prefix, 'fullUrl' => $prefix.$account ]; } $this->socialNetworks = $socials; return $this->socialNetworks; }
php
public function socialNetworks() { if ($this->socialNetworks) { return $this->socialNetworks; } $socials = json_decode($this->cmsConfig()['social_medias'], true); $configMeta = $this->configModel()->p('social_medias')->structureMetadata(); foreach ($socials as $ident => $account) { $prefix = $configMeta->property($ident)['input_prefix']; $socials[$ident] = [ 'account' => $account, 'prefix' => $prefix, 'fullUrl' => $prefix.$account ]; } $this->socialNetworks = $socials; return $this->socialNetworks; }
[ "public", "function", "socialNetworks", "(", ")", "{", "if", "(", "$", "this", "->", "socialNetworks", ")", "{", "return", "$", "this", "->", "socialNetworks", ";", "}", "$", "socials", "=", "json_decode", "(", "$", "this", "->", "cmsConfig", "(", ")", "[", "'social_medias'", "]", ",", "true", ")", ";", "$", "configMeta", "=", "$", "this", "->", "configModel", "(", ")", "->", "p", "(", "'social_medias'", ")", "->", "structureMetadata", "(", ")", ";", "foreach", "(", "$", "socials", "as", "$", "ident", "=>", "$", "account", ")", "{", "$", "prefix", "=", "$", "configMeta", "->", "property", "(", "$", "ident", ")", "[", "'input_prefix'", "]", ";", "$", "socials", "[", "$", "ident", "]", "=", "[", "'account'", "=>", "$", "account", ",", "'prefix'", "=>", "$", "prefix", ",", "'fullUrl'", "=>", "$", "prefix", ".", "$", "account", "]", ";", "}", "$", "this", "->", "socialNetworks", "=", "$", "socials", ";", "return", "$", "this", "->", "socialNetworks", ";", "}" ]
Retrieve the websites's social presence. @throws \Exception If the given context does not have access to config. @return array
[ "Retrieve", "the", "websites", "s", "social", "presence", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/SocialNetworksAwareTrait.php#L39-L60
train
locomotivemtl/charcoal-cms
src/Charcoal/Admin/Widget/GroupAttachmentWidget.php
GroupAttachmentWidget.addAttachmentGroupFromMetadata
protected function addAttachmentGroupFromMetadata($reload = false) { if ($this->obj() instanceof TemplateableInterface) { $this->setControllerIdent($this->obj()->templateIdentClass()); } if ($reload || !$this->isAttachmentMetadataFinalized) { $obj = $this->obj(); $controllerInterface = $this->controllerIdent(); $interfaces = [$this->objType()]; if ($controllerInterface) { array_push($interfaces, $controllerInterface); } $structureMetadata = $this->createMetadata(); if (count($interfaces)) { $controllerMetadataIdent = sprintf('widget/metadata/%s/%s', $obj->objType(), $obj->id()); $structureMetadata = $this->metadataLoader()->load( $controllerMetadataIdent, $structureMetadata, $interfaces ); } $attachmentWidgets = $structureMetadata->get('attachments.widgets'); foreach ((array)$attachmentWidgets as $ident => $metadata) { $this->addGroup($ident, $metadata); } $this->isAttachmentMetadataFinalized = true; } }
php
protected function addAttachmentGroupFromMetadata($reload = false) { if ($this->obj() instanceof TemplateableInterface) { $this->setControllerIdent($this->obj()->templateIdentClass()); } if ($reload || !$this->isAttachmentMetadataFinalized) { $obj = $this->obj(); $controllerInterface = $this->controllerIdent(); $interfaces = [$this->objType()]; if ($controllerInterface) { array_push($interfaces, $controllerInterface); } $structureMetadata = $this->createMetadata(); if (count($interfaces)) { $controllerMetadataIdent = sprintf('widget/metadata/%s/%s', $obj->objType(), $obj->id()); $structureMetadata = $this->metadataLoader()->load( $controllerMetadataIdent, $structureMetadata, $interfaces ); } $attachmentWidgets = $structureMetadata->get('attachments.widgets'); foreach ((array)$attachmentWidgets as $ident => $metadata) { $this->addGroup($ident, $metadata); } $this->isAttachmentMetadataFinalized = true; } }
[ "protected", "function", "addAttachmentGroupFromMetadata", "(", "$", "reload", "=", "false", ")", "{", "if", "(", "$", "this", "->", "obj", "(", ")", "instanceof", "TemplateableInterface", ")", "{", "$", "this", "->", "setControllerIdent", "(", "$", "this", "->", "obj", "(", ")", "->", "templateIdentClass", "(", ")", ")", ";", "}", "if", "(", "$", "reload", "||", "!", "$", "this", "->", "isAttachmentMetadataFinalized", ")", "{", "$", "obj", "=", "$", "this", "->", "obj", "(", ")", ";", "$", "controllerInterface", "=", "$", "this", "->", "controllerIdent", "(", ")", ";", "$", "interfaces", "=", "[", "$", "this", "->", "objType", "(", ")", "]", ";", "if", "(", "$", "controllerInterface", ")", "{", "array_push", "(", "$", "interfaces", ",", "$", "controllerInterface", ")", ";", "}", "$", "structureMetadata", "=", "$", "this", "->", "createMetadata", "(", ")", ";", "if", "(", "count", "(", "$", "interfaces", ")", ")", "{", "$", "controllerMetadataIdent", "=", "sprintf", "(", "'widget/metadata/%s/%s'", ",", "$", "obj", "->", "objType", "(", ")", ",", "$", "obj", "->", "id", "(", ")", ")", ";", "$", "structureMetadata", "=", "$", "this", "->", "metadataLoader", "(", ")", "->", "load", "(", "$", "controllerMetadataIdent", ",", "$", "structureMetadata", ",", "$", "interfaces", ")", ";", "}", "$", "attachmentWidgets", "=", "$", "structureMetadata", "->", "get", "(", "'attachments.widgets'", ")", ";", "foreach", "(", "(", "array", ")", "$", "attachmentWidgets", "as", "$", "ident", "=>", "$", "metadata", ")", "{", "$", "this", "->", "addGroup", "(", "$", "ident", ",", "$", "metadata", ")", ";", "}", "$", "this", "->", "isAttachmentMetadataFinalized", "=", "true", ";", "}", "}" ]
Load attachments group widget and them as form groups. @param boolean $reload Allows to reload the data. @throws InvalidArgumentException If structureMetadata $data is note defined. @throws RuntimeException If the metadataLoader is not defined. @return void
[ "Load", "attachments", "group", "widget", "and", "them", "as", "form", "groups", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php#L182-L216
train
locomotivemtl/charcoal-cms
src/Charcoal/Admin/Widget/GroupAttachmentWidget.php
GroupAttachmentWidget.setControllerIdent
public function setControllerIdent($ident) { if (class_exists($ident)) { $this->controllerIdent = $ident; return $this; } if (substr($ident, -9) !== '-template') { $ident .= '-template'; } $this->controllerIdent = $ident; return $this; }
php
public function setControllerIdent($ident) { if (class_exists($ident)) { $this->controllerIdent = $ident; return $this; } if (substr($ident, -9) !== '-template') { $ident .= '-template'; } $this->controllerIdent = $ident; return $this; }
[ "public", "function", "setControllerIdent", "(", "$", "ident", ")", "{", "if", "(", "class_exists", "(", "$", "ident", ")", ")", "{", "$", "this", "->", "controllerIdent", "=", "$", "ident", ";", "return", "$", "this", ";", "}", "if", "(", "substr", "(", "$", "ident", ",", "-", "9", ")", "!==", "'-template'", ")", "{", "$", "ident", ".=", "'-template'", ";", "}", "$", "this", "->", "controllerIdent", "=", "$", "ident", ";", "return", "$", "this", ";", "}" ]
Set the form object's template controller identifier. @param mixed $ident The template controller identifier. @return self
[ "Set", "the", "form", "object", "s", "template", "controller", "identifier", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Admin/Widget/GroupAttachmentWidget.php#L224-L239
train
mollie/reseller-api
php/src/mollie/autoloader.php
Mollie_Autoloader.load
public static function load ($class_name) { $file_name = str_replace(self::MOLLIE_PREFIX, '', strtolower($class_name), $count); if (empty($count)) { return; } if (file_exists($file_name = __DIR__ . DIRECTORY_SEPARATOR . "$file_name.php")) { require $file_name; } }
php
public static function load ($class_name) { $file_name = str_replace(self::MOLLIE_PREFIX, '', strtolower($class_name), $count); if (empty($count)) { return; } if (file_exists($file_name = __DIR__ . DIRECTORY_SEPARATOR . "$file_name.php")) { require $file_name; } }
[ "public", "static", "function", "load", "(", "$", "class_name", ")", "{", "$", "file_name", "=", "str_replace", "(", "self", "::", "MOLLIE_PREFIX", ",", "''", ",", "strtolower", "(", "$", "class_name", ")", ",", "$", "count", ")", ";", "if", "(", "empty", "(", "$", "count", ")", ")", "{", "return", ";", "}", "if", "(", "file_exists", "(", "$", "file_name", "=", "__DIR__", ".", "DIRECTORY_SEPARATOR", ".", "\"$file_name.php\"", ")", ")", "{", "require", "$", "file_name", ";", "}", "}" ]
Uses require_once to load the Mollie class. @param string $class_name
[ "Uses", "require_once", "to", "load", "the", "Mollie", "class", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/autoloader.php#L51-L61
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/NewsManager.php
NewsManager.entries
public function entries() { $page = $this->page(); $cat = $this->category(); if (isset($this->entries[$cat])) { if (isset($this->entries[$cat][$page])) { return $this->entries[$cat][$page]; } } $loader = $this->entriesLoader(); $this->entries[$cat][$page] = $loader->load(); return $this->entries[$cat][$page]; }
php
public function entries() { $page = $this->page(); $cat = $this->category(); if (isset($this->entries[$cat])) { if (isset($this->entries[$cat][$page])) { return $this->entries[$cat][$page]; } } $loader = $this->entriesLoader(); $this->entries[$cat][$page] = $loader->load(); return $this->entries[$cat][$page]; }
[ "public", "function", "entries", "(", ")", "{", "$", "page", "=", "$", "this", "->", "page", "(", ")", ";", "$", "cat", "=", "$", "this", "->", "category", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "entries", "[", "$", "cat", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "entries", "[", "$", "cat", "]", "[", "$", "page", "]", ")", ")", "{", "return", "$", "this", "->", "entries", "[", "$", "cat", "]", "[", "$", "page", "]", ";", "}", "}", "$", "loader", "=", "$", "this", "->", "entriesLoader", "(", ")", ";", "$", "this", "->", "entries", "[", "$", "cat", "]", "[", "$", "page", "]", "=", "$", "loader", "->", "load", "(", ")", ";", "return", "$", "this", "->", "entries", "[", "$", "cat", "]", "[", "$", "page", "]", ";", "}" ]
To be displayed news list. @return mixed The news collection.
[ "To", "be", "displayed", "news", "list", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/NewsManager.php#L111-L126
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/NewsManager.php
NewsManager.all
public function all() { if ($this->all) { return $this->all; } $this->all = $this->loader()->all()->addOrder('news_date', 'desc')->load(); return $this->all; }
php
public function all() { if ($this->all) { return $this->all; } $this->all = $this->loader()->all()->addOrder('news_date', 'desc')->load(); return $this->all; }
[ "public", "function", "all", "(", ")", "{", "if", "(", "$", "this", "->", "all", ")", "{", "return", "$", "this", "->", "all", ";", "}", "$", "this", "->", "all", "=", "$", "this", "->", "loader", "(", ")", "->", "all", "(", ")", "->", "addOrder", "(", "'news_date'", ",", "'desc'", ")", "->", "load", "(", ")", ";", "return", "$", "this", "->", "all", ";", "}" ]
All available news. @return NewsInterface[]|Collection The news collection.
[ "All", "available", "news", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/NewsManager.php#L171-L180
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/NewsManager.php
NewsManager.setPrevNext
public function setPrevNext() { if ($this->nextNews && $this->prevNews) { return $this; } $entries = $this->entries(); $isPrev = false; $isNext = false; $firstNews = false; $lastNews = false; /** @var NewsInterface $news */ foreach ($entries as $news) { // Obtain th first news. if (!$firstNews) { $firstNews = $news; } $lastNews = $news; // Find the current news if ($news->id() == $this->currentNews()['id']) { $isNext = true; $isPrev = true; continue; } if (!$isPrev) { $this->prevNews = $news; } // Store the next news if ($isNext) { $this->nextNews = $news; $isNext = false; } } if ($this->entryCycle()) { if (!$this->nextNews) { $this->nextNews = $firstNews; } if (!$this->prevNews) { $this->prevNews = $lastNews; } } return $this; }
php
public function setPrevNext() { if ($this->nextNews && $this->prevNews) { return $this; } $entries = $this->entries(); $isPrev = false; $isNext = false; $firstNews = false; $lastNews = false; /** @var NewsInterface $news */ foreach ($entries as $news) { // Obtain th first news. if (!$firstNews) { $firstNews = $news; } $lastNews = $news; // Find the current news if ($news->id() == $this->currentNews()['id']) { $isNext = true; $isPrev = true; continue; } if (!$isPrev) { $this->prevNews = $news; } // Store the next news if ($isNext) { $this->nextNews = $news; $isNext = false; } } if ($this->entryCycle()) { if (!$this->nextNews) { $this->nextNews = $firstNews; } if (!$this->prevNews) { $this->prevNews = $lastNews; } } return $this; }
[ "public", "function", "setPrevNext", "(", ")", "{", "if", "(", "$", "this", "->", "nextNews", "&&", "$", "this", "->", "prevNews", ")", "{", "return", "$", "this", ";", "}", "$", "entries", "=", "$", "this", "->", "entries", "(", ")", ";", "$", "isPrev", "=", "false", ";", "$", "isNext", "=", "false", ";", "$", "firstNews", "=", "false", ";", "$", "lastNews", "=", "false", ";", "/** @var NewsInterface $news */", "foreach", "(", "$", "entries", "as", "$", "news", ")", "{", "// Obtain th first news.", "if", "(", "!", "$", "firstNews", ")", "{", "$", "firstNews", "=", "$", "news", ";", "}", "$", "lastNews", "=", "$", "news", ";", "// Find the current news", "if", "(", "$", "news", "->", "id", "(", ")", "==", "$", "this", "->", "currentNews", "(", ")", "[", "'id'", "]", ")", "{", "$", "isNext", "=", "true", ";", "$", "isPrev", "=", "true", ";", "continue", ";", "}", "if", "(", "!", "$", "isPrev", ")", "{", "$", "this", "->", "prevNews", "=", "$", "news", ";", "}", "// Store the next news", "if", "(", "$", "isNext", ")", "{", "$", "this", "->", "nextNews", "=", "$", "news", ";", "$", "isNext", "=", "false", ";", "}", "}", "if", "(", "$", "this", "->", "entryCycle", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "nextNews", ")", "{", "$", "this", "->", "nextNews", "=", "$", "firstNews", ";", "}", "if", "(", "!", "$", "this", "->", "prevNews", ")", "{", "$", "this", "->", "prevNews", "=", "$", "lastNews", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set the Prev and Next news @return $this
[ "Set", "the", "Prev", "and", "Next", "news" ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/NewsManager.php#L555-L603
train
vanilla/garden-schema
src/ValidationField.php
ValidationField.addTypeError
public function addTypeError($value, $type = '') { $type = $type ?: $this->getType(); $this->validation->addError( $this->getName(), 'type', [ 'type' => $type, 'value' => is_scalar($value) ? $value : null, 'messageCode' => is_scalar($value) ? "{value} is not a valid $type." : "The value is not a valid $type." ] ); return $this; }
php
public function addTypeError($value, $type = '') { $type = $type ?: $this->getType(); $this->validation->addError( $this->getName(), 'type', [ 'type' => $type, 'value' => is_scalar($value) ? $value : null, 'messageCode' => is_scalar($value) ? "{value} is not a valid $type." : "The value is not a valid $type." ] ); return $this; }
[ "public", "function", "addTypeError", "(", "$", "value", ",", "$", "type", "=", "''", ")", "{", "$", "type", "=", "$", "type", "?", ":", "$", "this", "->", "getType", "(", ")", ";", "$", "this", "->", "validation", "->", "addError", "(", "$", "this", "->", "getName", "(", ")", ",", "'type'", ",", "[", "'type'", "=>", "$", "type", ",", "'value'", "=>", "is_scalar", "(", "$", "value", ")", "?", "$", "value", ":", "null", ",", "'messageCode'", "=>", "is_scalar", "(", "$", "value", ")", "?", "\"{value} is not a valid $type.\"", ":", "\"The value is not a valid $type.\"", "]", ")", ";", "return", "$", "this", ";", "}" ]
Add an invalid type error. @param mixed $value The erroneous value. @param string $type The type that was checked. @return $this
[ "Add", "an", "invalid", "type", "error", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/ValidationField.php#L80-L94
train
vanilla/garden-schema
src/ValidationField.php
ValidationField.merge
public function merge(Validation $validation) { $this->getValidation()->merge($validation, $this->getName()); return $this; }
php
public function merge(Validation $validation) { $this->getValidation()->merge($validation, $this->getName()); return $this; }
[ "public", "function", "merge", "(", "Validation", "$", "validation", ")", "{", "$", "this", "->", "getValidation", "(", ")", "->", "merge", "(", "$", "validation", ",", "$", "this", "->", "getName", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Merge a validation object to this one. @param Validation $validation The validation object to merge. @return $this
[ "Merge", "a", "validation", "object", "to", "this", "one", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/ValidationField.php#L111-L114
train
vanilla/garden-schema
src/ValidationField.php
ValidationField.hasVal
public function hasVal($key) { return isset($this->field[$key]) || (is_array($this->field) && array_key_exists($key, $this->field)); }
php
public function hasVal($key) { return isset($this->field[$key]) || (is_array($this->field) && array_key_exists($key, $this->field)); }
[ "public", "function", "hasVal", "(", "$", "key", ")", "{", "return", "isset", "(", "$", "this", "->", "field", "[", "$", "key", "]", ")", "||", "(", "is_array", "(", "$", "this", "->", "field", ")", "&&", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "field", ")", ")", ";", "}" ]
Whether or not the field has a value. @param string $key The key to look at. @return bool Returns **true** if the field has a key or **false** otherwise.
[ "Whether", "or", "not", "the", "field", "has", "a", "value", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/ValidationField.php#L223-L225
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Loader/SectionLoader.php
SectionLoader.sectionRoutes
public function sectionRoutes() { if ($this->sectionRoutes) { return $this->sectionRoutes; } $proto = $this->modelFactory()->create(ObjectRoute::class); $sectionTypes = $this->sectionTypes(); if (empty($sectionTypes)) { $sectionTypes = [ 'base' => $this->objType() ]; } $loader = $this->collectionLoader()->reset(); $loader->setModel($proto); $filters = []; foreach ($sectionTypes as $key => $val) { $filters[] = 'route_obj_type = \''.$val.'\''; } $q = 'SELECT * FROM `'.$proto->source()->table().'` WHERE active = 1 AND ('.implode(' OR ', $filters).') AND `route_options_ident` IS NULL ORDER BY creation_date ASC'; $objectRoutes = $loader->loadFromQuery($q); // $loader->addFilter('route_obj_type', $this->objType()) // // This is important. This is why it all works // // Loading it from the first created to the last created // // makes the following foreach override previous data. // ->addOrder('creation_date', 'asc'); // $objectRoutes = $loader->load(); $sections = []; $routes = []; // The current language $lang = $this->translator()->getLocale(); foreach ($objectRoutes as $o) { if ($o->lang() === $lang) { // Will automatically override previous slug set $sections[$o->routeObjId()] = $o->slug(); } // Keep track of EVERY slug. $routes[$o->slug()] = $o->routeObjId(); } $this->sectionRoutes = [ 'sections' => $sections, 'routes' => $routes ]; return $this->sectionRoutes; }
php
public function sectionRoutes() { if ($this->sectionRoutes) { return $this->sectionRoutes; } $proto = $this->modelFactory()->create(ObjectRoute::class); $sectionTypes = $this->sectionTypes(); if (empty($sectionTypes)) { $sectionTypes = [ 'base' => $this->objType() ]; } $loader = $this->collectionLoader()->reset(); $loader->setModel($proto); $filters = []; foreach ($sectionTypes as $key => $val) { $filters[] = 'route_obj_type = \''.$val.'\''; } $q = 'SELECT * FROM `'.$proto->source()->table().'` WHERE active = 1 AND ('.implode(' OR ', $filters).') AND `route_options_ident` IS NULL ORDER BY creation_date ASC'; $objectRoutes = $loader->loadFromQuery($q); // $loader->addFilter('route_obj_type', $this->objType()) // // This is important. This is why it all works // // Loading it from the first created to the last created // // makes the following foreach override previous data. // ->addOrder('creation_date', 'asc'); // $objectRoutes = $loader->load(); $sections = []; $routes = []; // The current language $lang = $this->translator()->getLocale(); foreach ($objectRoutes as $o) { if ($o->lang() === $lang) { // Will automatically override previous slug set $sections[$o->routeObjId()] = $o->slug(); } // Keep track of EVERY slug. $routes[$o->slug()] = $o->routeObjId(); } $this->sectionRoutes = [ 'sections' => $sections, 'routes' => $routes ]; return $this->sectionRoutes; }
[ "public", "function", "sectionRoutes", "(", ")", "{", "if", "(", "$", "this", "->", "sectionRoutes", ")", "{", "return", "$", "this", "->", "sectionRoutes", ";", "}", "$", "proto", "=", "$", "this", "->", "modelFactory", "(", ")", "->", "create", "(", "ObjectRoute", "::", "class", ")", ";", "$", "sectionTypes", "=", "$", "this", "->", "sectionTypes", "(", ")", ";", "if", "(", "empty", "(", "$", "sectionTypes", ")", ")", "{", "$", "sectionTypes", "=", "[", "'base'", "=>", "$", "this", "->", "objType", "(", ")", "]", ";", "}", "$", "loader", "=", "$", "this", "->", "collectionLoader", "(", ")", "->", "reset", "(", ")", ";", "$", "loader", "->", "setModel", "(", "$", "proto", ")", ";", "$", "filters", "=", "[", "]", ";", "foreach", "(", "$", "sectionTypes", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "filters", "[", "]", "=", "'route_obj_type = \\''", ".", "$", "val", ".", "'\\''", ";", "}", "$", "q", "=", "'SELECT * FROM `'", ".", "$", "proto", "->", "source", "(", ")", "->", "table", "(", ")", ".", "'`\n WHERE active = 1 AND ('", ".", "implode", "(", "' OR '", ",", "$", "filters", ")", ".", "')\n AND `route_options_ident` IS NULL\n ORDER BY creation_date ASC'", ";", "$", "objectRoutes", "=", "$", "loader", "->", "loadFromQuery", "(", "$", "q", ")", ";", "// $loader->addFilter('route_obj_type', $this->objType())", "// // This is important. This is why it all works", "// // Loading it from the first created to the last created", "// // makes the following foreach override previous data.", "// ->addOrder('creation_date', 'asc');", "// $objectRoutes = $loader->load();", "$", "sections", "=", "[", "]", ";", "$", "routes", "=", "[", "]", ";", "// The current language", "$", "lang", "=", "$", "this", "->", "translator", "(", ")", "->", "getLocale", "(", ")", ";", "foreach", "(", "$", "objectRoutes", "as", "$", "o", ")", "{", "if", "(", "$", "o", "->", "lang", "(", ")", "===", "$", "lang", ")", "{", "// Will automatically override previous slug set", "$", "sections", "[", "$", "o", "->", "routeObjId", "(", ")", "]", "=", "$", "o", "->", "slug", "(", ")", ";", "}", "// Keep track of EVERY slug.", "$", "routes", "[", "$", "o", "->", "slug", "(", ")", "]", "=", "$", "o", "->", "routeObjId", "(", ")", ";", "}", "$", "this", "->", "sectionRoutes", "=", "[", "'sections'", "=>", "$", "sections", ",", "'routes'", "=>", "$", "routes", "]", ";", "return", "$", "this", "->", "sectionRoutes", ";", "}" ]
Pair routes slug to sections ID @return array
[ "Pair", "routes", "slug", "to", "sections", "ID" ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Loader/SectionLoader.php#L131-L187
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Loader/SectionLoader.php
SectionLoader.resolveRoute
public function resolveRoute($route) { $routes = $this->sectionRoutes(); $sId = $this->resolveSectionId($route); if (!isset($routes['sections'][$sId])) { return ''; } return $routes['sections'][$sId]; }
php
public function resolveRoute($route) { $routes = $this->sectionRoutes(); $sId = $this->resolveSectionId($route); if (!isset($routes['sections'][$sId])) { return ''; } return $routes['sections'][$sId]; }
[ "public", "function", "resolveRoute", "(", "$", "route", ")", "{", "$", "routes", "=", "$", "this", "->", "sectionRoutes", "(", ")", ";", "$", "sId", "=", "$", "this", "->", "resolveSectionId", "(", "$", "route", ")", ";", "if", "(", "!", "isset", "(", "$", "routes", "[", "'sections'", "]", "[", "$", "sId", "]", ")", ")", "{", "return", "''", ";", "}", "return", "$", "routes", "[", "'sections'", "]", "[", "$", "sId", "]", ";", "}" ]
Resolve latest route from route slug. @param string $route The route to resolve. @return string
[ "Resolve", "latest", "route", "from", "route", "slug", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Loader/SectionLoader.php#L194-L204
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/MetatagTrait.php
MetatagTrait.generateDefaultMetaTags
public function generateDefaultMetaTags() { if ($this->isEmptyMeta($this->metaTitle)) { $this->setMetaTitle($this->defaultMetaTitle()); } if ($this->isEmptyMeta($this->metaDescription)) { $this->setMetaDescription($this->defaultMetaDescription()); } if ($this->isEmptyMeta($this->metaImage)) { $this->setMetaImage($this->defaultMetaImage()); } return $this; }
php
public function generateDefaultMetaTags() { if ($this->isEmptyMeta($this->metaTitle)) { $this->setMetaTitle($this->defaultMetaTitle()); } if ($this->isEmptyMeta($this->metaDescription)) { $this->setMetaDescription($this->defaultMetaDescription()); } if ($this->isEmptyMeta($this->metaImage)) { $this->setMetaImage($this->defaultMetaImage()); } return $this; }
[ "public", "function", "generateDefaultMetaTags", "(", ")", "{", "if", "(", "$", "this", "->", "isEmptyMeta", "(", "$", "this", "->", "metaTitle", ")", ")", "{", "$", "this", "->", "setMetaTitle", "(", "$", "this", "->", "defaultMetaTitle", "(", ")", ")", ";", "}", "if", "(", "$", "this", "->", "isEmptyMeta", "(", "$", "this", "->", "metaDescription", ")", ")", "{", "$", "this", "->", "setMetaDescription", "(", "$", "this", "->", "defaultMetaDescription", "(", ")", ")", ";", "}", "if", "(", "$", "this", "->", "isEmptyMeta", "(", "$", "this", "->", "metaImage", ")", ")", "{", "$", "this", "->", "setMetaImage", "(", "$", "this", "->", "defaultMetaImage", "(", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Generates the default metatags for the current object. Prevents some problem where the defaultMetaTag method content isn't set at the moment of setting the meta. Should be called on preSave and preUpdate of the object. @return self $this.
[ "Generates", "the", "default", "metatags", "for", "the", "current", "object", ".", "Prevents", "some", "problem", "where", "the", "defaultMetaTag", "method", "content", "isn", "t", "set", "at", "the", "moment", "of", "setting", "the", "meta", ".", "Should", "be", "called", "on", "preSave", "and", "preUpdate", "of", "the", "object", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/MetatagTrait.php#L354-L366
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Route/GenericRoute.php
GenericRoute.getContextObject
protected function getContextObject() { if ($this->contextObject === null) { $this->contextObject = $this->loadContextObject(); } return $this->contextObject; }
php
protected function getContextObject() { if ($this->contextObject === null) { $this->contextObject = $this->loadContextObject(); } return $this->contextObject; }
[ "protected", "function", "getContextObject", "(", ")", "{", "if", "(", "$", "this", "->", "contextObject", "===", "null", ")", "{", "$", "this", "->", "contextObject", "=", "$", "this", "->", "loadContextObject", "(", ")", ";", "}", "return", "$", "this", "->", "contextObject", ";", "}" ]
Get the object associated with the matching object route. @return RoutableInterface
[ "Get", "the", "object", "associated", "with", "the", "matching", "object", "route", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Route/GenericRoute.php#L353-L360
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Route/GenericRoute.php
GenericRoute.loadContextObject
protected function loadContextObject() { $route = $this->getObjectRouteFromPath(); $obj = $this->modelFactory()->create($route->routeObjType()); $obj->load($route->routeObjId()); return $obj; }
php
protected function loadContextObject() { $route = $this->getObjectRouteFromPath(); $obj = $this->modelFactory()->create($route->routeObjType()); $obj->load($route->routeObjId()); return $obj; }
[ "protected", "function", "loadContextObject", "(", ")", "{", "$", "route", "=", "$", "this", "->", "getObjectRouteFromPath", "(", ")", ";", "$", "obj", "=", "$", "this", "->", "modelFactory", "(", ")", "->", "create", "(", "$", "route", "->", "routeObjType", "(", ")", ")", ";", "$", "obj", "->", "load", "(", "$", "route", "->", "routeObjId", "(", ")", ")", ";", "return", "$", "obj", ";", "}" ]
Load the object associated with the matching object route. Validating if the object ID exists is delegated to the {@see GenericRoute Chainable::pathResolvable()} method. @return RoutableInterface
[ "Load", "the", "object", "associated", "with", "the", "matching", "object", "route", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Route/GenericRoute.php#L370-L378
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Route/GenericRoute.php
GenericRoute.getObjectRouteFromPath
protected function getObjectRouteFromPath() { if ($this->objectRoute === null) { $this->objectRoute = $this->loadObjectRouteFromPath(); } return $this->objectRoute; }
php
protected function getObjectRouteFromPath() { if ($this->objectRoute === null) { $this->objectRoute = $this->loadObjectRouteFromPath(); } return $this->objectRoute; }
[ "protected", "function", "getObjectRouteFromPath", "(", ")", "{", "if", "(", "$", "this", "->", "objectRoute", "===", "null", ")", "{", "$", "this", "->", "objectRoute", "=", "$", "this", "->", "loadObjectRouteFromPath", "(", ")", ";", "}", "return", "$", "this", "->", "objectRoute", ";", "}" ]
Get the object route matching the URI path. @return \Charcoal\Object\ObjectRouteInterface
[ "Get", "the", "object", "route", "matching", "the", "URI", "path", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Route/GenericRoute.php#L385-L392
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Route/GenericRoute.php
GenericRoute.loadObjectRouteFromPath
protected function loadObjectRouteFromPath() { // Load current slug // Slugs are unique // Slug can be duplicated by adding the front "/" to it hence the order by last_modification_date $route = $this->createRouteObject(); $route->loadFromQuery( 'SELECT * FROM `'.$route->source()->table().'` WHERE (`slug` = :route1 OR `slug` = :route2) AND `lang` = :lang ORDER BY last_modification_date DESC LIMIT 1', [ 'route1' => '/'.$this->path(), 'route2' => $this->path(), 'lang' => $this->translator()->getLocale() ] ); return $route; }
php
protected function loadObjectRouteFromPath() { // Load current slug // Slugs are unique // Slug can be duplicated by adding the front "/" to it hence the order by last_modification_date $route = $this->createRouteObject(); $route->loadFromQuery( 'SELECT * FROM `'.$route->source()->table().'` WHERE (`slug` = :route1 OR `slug` = :route2) AND `lang` = :lang ORDER BY last_modification_date DESC LIMIT 1', [ 'route1' => '/'.$this->path(), 'route2' => $this->path(), 'lang' => $this->translator()->getLocale() ] ); return $route; }
[ "protected", "function", "loadObjectRouteFromPath", "(", ")", "{", "// Load current slug", "// Slugs are unique", "// Slug can be duplicated by adding the front \"/\" to it hence the order by last_modification_date", "$", "route", "=", "$", "this", "->", "createRouteObject", "(", ")", ";", "$", "route", "->", "loadFromQuery", "(", "'SELECT * FROM `'", ".", "$", "route", "->", "source", "(", ")", "->", "table", "(", ")", ".", "'` WHERE (`slug` = :route1 OR `slug` = :route2) AND `lang` = :lang ORDER BY last_modification_date DESC LIMIT 1'", ",", "[", "'route1'", "=>", "'/'", ".", "$", "this", "->", "path", "(", ")", ",", "'route2'", "=>", "$", "this", "->", "path", "(", ")", ",", "'lang'", "=>", "$", "this", "->", "translator", "(", ")", "->", "getLocale", "(", ")", "]", ")", ";", "return", "$", "route", ";", "}" ]
Load the object route matching the URI path. @return \Charcoal\Object\ObjectRouteInterface
[ "Load", "the", "object", "route", "matching", "the", "URI", "path", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Route/GenericRoute.php#L399-L415
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Route/GenericRoute.php
GenericRoute.setLocale
protected function setLocale($langCode) { $translator = $this->translator(); $translator->setLocale($langCode); $available = $translator->locales(); $fallbacks = $translator->getFallbackLocales(); array_unshift($fallbacks, $langCode); $fallbacks = array_unique($fallbacks); $locales = []; foreach ($fallbacks as $code) { if (isset($available[$code])) { $locale = $available[$code]; if (isset($locale['locales'])) { $choices = (array)$locale['locales']; array_push($locales, ...$choices); } elseif (isset($locale['locale'])) { array_push($locales, $locale['locale']); } } } $locales = array_unique($locales); if ($locales) { setlocale(LC_ALL, $locales); } }
php
protected function setLocale($langCode) { $translator = $this->translator(); $translator->setLocale($langCode); $available = $translator->locales(); $fallbacks = $translator->getFallbackLocales(); array_unshift($fallbacks, $langCode); $fallbacks = array_unique($fallbacks); $locales = []; foreach ($fallbacks as $code) { if (isset($available[$code])) { $locale = $available[$code]; if (isset($locale['locales'])) { $choices = (array)$locale['locales']; array_push($locales, ...$choices); } elseif (isset($locale['locale'])) { array_push($locales, $locale['locale']); } } } $locales = array_unique($locales); if ($locales) { setlocale(LC_ALL, $locales); } }
[ "protected", "function", "setLocale", "(", "$", "langCode", ")", "{", "$", "translator", "=", "$", "this", "->", "translator", "(", ")", ";", "$", "translator", "->", "setLocale", "(", "$", "langCode", ")", ";", "$", "available", "=", "$", "translator", "->", "locales", "(", ")", ";", "$", "fallbacks", "=", "$", "translator", "->", "getFallbackLocales", "(", ")", ";", "array_unshift", "(", "$", "fallbacks", ",", "$", "langCode", ")", ";", "$", "fallbacks", "=", "array_unique", "(", "$", "fallbacks", ")", ";", "$", "locales", "=", "[", "]", ";", "foreach", "(", "$", "fallbacks", "as", "$", "code", ")", "{", "if", "(", "isset", "(", "$", "available", "[", "$", "code", "]", ")", ")", "{", "$", "locale", "=", "$", "available", "[", "$", "code", "]", ";", "if", "(", "isset", "(", "$", "locale", "[", "'locales'", "]", ")", ")", "{", "$", "choices", "=", "(", "array", ")", "$", "locale", "[", "'locales'", "]", ";", "array_push", "(", "$", "locales", ",", "...", "$", "choices", ")", ";", "}", "elseif", "(", "isset", "(", "$", "locale", "[", "'locale'", "]", ")", ")", "{", "array_push", "(", "$", "locales", ",", "$", "locale", "[", "'locale'", "]", ")", ";", "}", "}", "}", "$", "locales", "=", "array_unique", "(", "$", "locales", ")", ";", "if", "(", "$", "locales", ")", "{", "setlocale", "(", "LC_ALL", ",", "$", "locales", ")", ";", "}", "}" ]
Sets the environment's current locale. @param string $langCode The locale's language code. @return void
[ "Sets", "the", "environment", "s", "current", "locale", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Route/GenericRoute.php#L503-L532
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
NewsManagerAwareTrait.newsList
public function newsList() { $entries = $this->newsManager()->entries(); foreach ($entries as $news) { yield $this->newsFormatShort($news); } }
php
public function newsList() { $entries = $this->newsManager()->entries(); foreach ($entries as $news) { yield $this->newsFormatShort($news); } }
[ "public", "function", "newsList", "(", ")", "{", "$", "entries", "=", "$", "this", "->", "newsManager", "(", ")", "->", "entries", "(", ")", ";", "foreach", "(", "$", "entries", "as", "$", "news", ")", "{", "yield", "$", "this", "->", "newsFormatShort", "(", "$", "news", ")", ";", "}", "}" ]
Formatted news list Returns the entries for the current page. @return \Generator|void
[ "Formatted", "news", "list", "Returns", "the", "entries", "for", "the", "current", "page", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php#L40-L46
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
NewsManagerAwareTrait.newsArchiveList
public function newsArchiveList() { $entries = $this->newsManager()->archive(); foreach ($entries as $entry) { yield $this->newsFormatShort($entry); } }
php
public function newsArchiveList() { $entries = $this->newsManager()->archive(); foreach ($entries as $entry) { yield $this->newsFormatShort($entry); } }
[ "public", "function", "newsArchiveList", "(", ")", "{", "$", "entries", "=", "$", "this", "->", "newsManager", "(", ")", "->", "archive", "(", ")", ";", "foreach", "(", "$", "entries", "as", "$", "entry", ")", "{", "yield", "$", "this", "->", "newsFormatShort", "(", "$", "entry", ")", ";", "}", "}" ]
Formatted news archive list Returns the entries for the current page. @return \Generator|void
[ "Formatted", "news", "archive", "list", "Returns", "the", "entries", "for", "the", "current", "page", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php#L53-L59
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php
NewsManagerAwareTrait.currentNews
public function currentNews() { if ($this->currentNews) { return $this->currentNews; } // The the current news $news = $this->newsManager()->entry(); // Format the news if there's any if ($news) { $this->currentNews = $this->newsFormatFull($news); } return $this->currentNews; }
php
public function currentNews() { if ($this->currentNews) { return $this->currentNews; } // The the current news $news = $this->newsManager()->entry(); // Format the news if there's any if ($news) { $this->currentNews = $this->newsFormatFull($news); } return $this->currentNews; }
[ "public", "function", "currentNews", "(", ")", "{", "if", "(", "$", "this", "->", "currentNews", ")", "{", "return", "$", "this", "->", "currentNews", ";", "}", "// The the current news", "$", "news", "=", "$", "this", "->", "newsManager", "(", ")", "->", "entry", "(", ")", ";", "// Format the news if there's any", "if", "(", "$", "news", ")", "{", "$", "this", "->", "currentNews", "=", "$", "this", "->", "newsFormatFull", "(", "$", "news", ")", ";", "}", "return", "$", "this", "->", "currentNews", ";", "}" ]
Current news. @return array The properties of the current news
[ "Current", "news", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Support/Traits/NewsManagerAwareTrait.php#L65-L80
train
mollie/reseller-api
php/src/mollie/api.php
Mollie_API.checkResultErrors
protected function checkResultErrors(Mollie_Response $object) { if (!$object->isSuccess()) { throw new Mollie_Exception(strval($object->resultmessage), intval($object->resultcode)); } }
php
protected function checkResultErrors(Mollie_Response $object) { if (!$object->isSuccess()) { throw new Mollie_Exception(strval($object->resultmessage), intval($object->resultcode)); } }
[ "protected", "function", "checkResultErrors", "(", "Mollie_Response", "$", "object", ")", "{", "if", "(", "!", "$", "object", "->", "isSuccess", "(", ")", ")", "{", "throw", "new", "Mollie_Exception", "(", "strval", "(", "$", "object", "->", "resultmessage", ")", ",", "intval", "(", "$", "object", "->", "resultcode", ")", ")", ";", "}", "}" ]
Check if the response received from the Mollie service is an error. If it is an error, then it will throw a Mollie_Exception, else it will do nothing. @param Mollie_Response $object @throws Mollie_Exception @return void
[ "Check", "if", "the", "response", "received", "from", "the", "Mollie", "service", "is", "an", "error", ".", "If", "it", "is", "an", "error", "then", "it", "will", "throw", "a", "Mollie_Exception", "else", "it", "will", "do", "nothing", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/api.php#L128-L133
train
mollie/reseller-api
php/src/mollie/api.php
Mollie_API.signRequest
protected function signRequest($path, array $params, $secret, $timestamp = null) { /* If there is no secret, don't sign the request. */ if (empty($secret)) { return $params; } /* Remove any existing signature, update timestamp and alphabetically sort parameters. */ unset($params['signature']); $params['timestamp'] = $timestamp !== null ? $timestamp : time(); ksort($params); /* Calculate signature */ $queryString = http_build_query($params, '', '&'); $params['signature'] = hash_hmac( 'sha1', '/' . trim($path, '/') . '?' . $queryString, strtoupper($secret) ); return $params; }
php
protected function signRequest($path, array $params, $secret, $timestamp = null) { /* If there is no secret, don't sign the request. */ if (empty($secret)) { return $params; } /* Remove any existing signature, update timestamp and alphabetically sort parameters. */ unset($params['signature']); $params['timestamp'] = $timestamp !== null ? $timestamp : time(); ksort($params); /* Calculate signature */ $queryString = http_build_query($params, '', '&'); $params['signature'] = hash_hmac( 'sha1', '/' . trim($path, '/') . '?' . $queryString, strtoupper($secret) ); return $params; }
[ "protected", "function", "signRequest", "(", "$", "path", ",", "array", "$", "params", ",", "$", "secret", ",", "$", "timestamp", "=", "null", ")", "{", "/* If there is no secret, don't sign the request. */", "if", "(", "empty", "(", "$", "secret", ")", ")", "{", "return", "$", "params", ";", "}", "/* Remove any existing signature, update timestamp and alphabetically sort parameters. */", "unset", "(", "$", "params", "[", "'signature'", "]", ")", ";", "$", "params", "[", "'timestamp'", "]", "=", "$", "timestamp", "!==", "null", "?", "$", "timestamp", ":", "time", "(", ")", ";", "ksort", "(", "$", "params", ")", ";", "/* Calculate signature */", "$", "queryString", "=", "http_build_query", "(", "$", "params", ",", "''", ",", "'&'", ")", ";", "$", "params", "[", "'signature'", "]", "=", "hash_hmac", "(", "'sha1'", ",", "'/'", ".", "trim", "(", "$", "path", ",", "'/'", ")", ".", "'?'", ".", "$", "queryString", ",", "strtoupper", "(", "$", "secret", ")", ")", ";", "return", "$", "params", ";", "}" ]
Calculate an MD5-signature based on request path, parameters and key. Signature will be added to input parameters array. @param string $path Current request path without query string @param array $params Parameters to use as HMAC data @param string $secret Secret to use as HMAC key @param int $timestamp (Optional) Override timestamp @return array
[ "Calculate", "an", "MD5", "-", "signature", "based", "on", "request", "path", "parameters", "and", "key", ".", "Signature", "will", "be", "added", "to", "input", "parameters", "array", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/api.php#L189-L210
train
mollie/reseller-api
php/src/mollie/api.php
Mollie_API.doRequest
protected function doRequest($method, $path, array $params) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 20); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::STRICT_SSL); curl_setopt($ch, CURLOPT_ENCODING, ''); // Signal that we support gzip $api_endpoint = trim($this->api_base_url, '/').'/'.trim($path, '/'); if ($method == self::METHOD_GET) { curl_setopt($ch, CURLOPT_URL, $api_endpoint.'?'.http_build_query($params, '', '&')); } else { curl_setopt($ch, CURLOPT_URL, $api_endpoint); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } $body = curl_exec($ch); /* 77 = CURLE_SSL_CACERT_BADFILE (constant not defined in PHP though). */ if (curl_errno($ch) == CURLE_SSL_CACERT || curl_errno($ch) == CURLE_SSL_PEER_CERTIFICATE || curl_errno($ch) == 77) { /* * On some servers, the list of installed certificates is outdated or not present at all (the ca-bundle.crt * is not installed). So we tell cURL which certificates we trust. Then we retry the requests. */ curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . DIRECTORY_SEPARATOR . "cacert.pem"); $body = curl_exec($ch); } if (strpos(curl_error($ch), "certificate subject name 'mollie.nl' does not match target host") !== false) { /* * On some servers, the wildcard SSL certificate is not processed correctly. This happens with OpenSSL 0.9.7 * from 2003. */ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $body = curl_exec($ch); } $results = [ 'body' => $body, 'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), 'content_type' => curl_getinfo($ch, CURLINFO_CONTENT_TYPE), 'code' => curl_errno($ch), 'message' => curl_error($ch), ]; curl_close($ch); return $results; }
php
protected function doRequest($method, $path, array $params) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 20); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, self::STRICT_SSL); curl_setopt($ch, CURLOPT_ENCODING, ''); // Signal that we support gzip $api_endpoint = trim($this->api_base_url, '/').'/'.trim($path, '/'); if ($method == self::METHOD_GET) { curl_setopt($ch, CURLOPT_URL, $api_endpoint.'?'.http_build_query($params, '', '&')); } else { curl_setopt($ch, CURLOPT_URL, $api_endpoint); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $params); } $body = curl_exec($ch); /* 77 = CURLE_SSL_CACERT_BADFILE (constant not defined in PHP though). */ if (curl_errno($ch) == CURLE_SSL_CACERT || curl_errno($ch) == CURLE_SSL_PEER_CERTIFICATE || curl_errno($ch) == 77) { /* * On some servers, the list of installed certificates is outdated or not present at all (the ca-bundle.crt * is not installed). So we tell cURL which certificates we trust. Then we retry the requests. */ curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . DIRECTORY_SEPARATOR . "cacert.pem"); $body = curl_exec($ch); } if (strpos(curl_error($ch), "certificate subject name 'mollie.nl' does not match target host") !== false) { /* * On some servers, the wildcard SSL certificate is not processed correctly. This happens with OpenSSL 0.9.7 * from 2003. */ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $body = curl_exec($ch); } $results = [ 'body' => $body, 'http_code' => curl_getinfo($ch, CURLINFO_HTTP_CODE), 'content_type' => curl_getinfo($ch, CURLINFO_CONTENT_TYPE), 'code' => curl_errno($ch), 'message' => curl_error($ch), ]; curl_close($ch); return $results; }
[ "protected", "function", "doRequest", "(", "$", "method", ",", "$", "path", ",", "array", "$", "params", ")", "{", "$", "ch", "=", "curl_init", "(", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "false", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "20", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYPEER", ",", "self", "::", "STRICT_SSL", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_ENCODING", ",", "''", ")", ";", "// Signal that we support gzip", "$", "api_endpoint", "=", "trim", "(", "$", "this", "->", "api_base_url", ",", "'/'", ")", ".", "'/'", ".", "trim", "(", "$", "path", ",", "'/'", ")", ";", "if", "(", "$", "method", "==", "self", "::", "METHOD_GET", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "api_endpoint", ".", "'?'", ".", "http_build_query", "(", "$", "params", ",", "''", ",", "'&'", ")", ")", ";", "}", "else", "{", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "api_endpoint", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_POSTFIELDS", ",", "$", "params", ")", ";", "}", "$", "body", "=", "curl_exec", "(", "$", "ch", ")", ";", "/* 77 = CURLE_SSL_CACERT_BADFILE (constant not defined in PHP though). */", "if", "(", "curl_errno", "(", "$", "ch", ")", "==", "CURLE_SSL_CACERT", "||", "curl_errno", "(", "$", "ch", ")", "==", "CURLE_SSL_PEER_CERTIFICATE", "||", "curl_errno", "(", "$", "ch", ")", "==", "77", ")", "{", "/*\n\t\t\t * On some servers, the list of installed certificates is outdated or not present at all (the ca-bundle.crt\n\t\t\t * is not installed). So we tell cURL which certificates we trust. Then we retry the requests.\n\t\t\t */", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CAINFO", ",", "dirname", "(", "__FILE__", ")", ".", "DIRECTORY_SEPARATOR", ".", "\"cacert.pem\"", ")", ";", "$", "body", "=", "curl_exec", "(", "$", "ch", ")", ";", "}", "if", "(", "strpos", "(", "curl_error", "(", "$", "ch", ")", ",", "\"certificate subject name 'mollie.nl' does not match target host\"", ")", "!==", "false", ")", "{", "/*\n\t\t\t * On some servers, the wildcard SSL certificate is not processed correctly. This happens with OpenSSL 0.9.7\n\t\t\t * from 2003.\n\t\t\t */", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_SSL_VERIFYHOST", ",", "false", ")", ";", "$", "body", "=", "curl_exec", "(", "$", "ch", ")", ";", "}", "$", "results", "=", "[", "'body'", "=>", "$", "body", ",", "'http_code'", "=>", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ",", "'content_type'", "=>", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_CONTENT_TYPE", ")", ",", "'code'", "=>", "curl_errno", "(", "$", "ch", ")", ",", "'message'", "=>", "curl_error", "(", "$", "ch", ")", ",", "]", ";", "curl_close", "(", "$", "ch", ")", ";", "return", "$", "results", ";", "}" ]
Do the actual HTTP request. @param string $method HTTP request method @param string $path Request path without query string @param array $params Parameters including profile_key, timestamp and signature @return array @codeCoverageIgnore
[ "Do", "the", "actual", "HTTP", "request", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/api.php#L234-L286
train
mollie/reseller-api
php/src/mollie/api.php
Mollie_API.logRequest
final private function logRequest($method, $path, array $params, $result) { $date = gmdate('Y-m-d\TH:i:s\Z ').substr(microtime(),0,5); $this->requestLog[$date] = [ "method" => $method, "path" => $path, "params" => $params, "result" => $result ]; }
php
final private function logRequest($method, $path, array $params, $result) { $date = gmdate('Y-m-d\TH:i:s\Z ').substr(microtime(),0,5); $this->requestLog[$date] = [ "method" => $method, "path" => $path, "params" => $params, "result" => $result ]; }
[ "final", "private", "function", "logRequest", "(", "$", "method", ",", "$", "path", ",", "array", "$", "params", ",", "$", "result", ")", "{", "$", "date", "=", "gmdate", "(", "'Y-m-d\\TH:i:s\\Z '", ")", ".", "substr", "(", "microtime", "(", ")", ",", "0", ",", "5", ")", ";", "$", "this", "->", "requestLog", "[", "$", "date", "]", "=", "[", "\"method\"", "=>", "$", "method", ",", "\"path\"", "=>", "$", "path", ",", "\"params\"", "=>", "$", "params", ",", "\"result\"", "=>", "$", "result", "]", ";", "}" ]
Log a request. @param string $method HTTP request method @param string $path Request path without query string @param array $params All used HTTP parameters @param mixed $result cURL result
[ "Log", "a", "request", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/api.php#L296-L305
train
mollie/reseller-api
php/src/mollie/api.php
Mollie_API.convertResponseBodyToObject
final private function convertResponseBodyToObject($body, $content_type) { /* No body to convert */ if (empty($body)) { return null; } /* Convert to Mollie_Response object or return as string. */ if (preg_match('/(application|text)\/xml/i', $content_type)) { return simplexml_load_string($body, "Mollie_Response"); } return $body; }
php
final private function convertResponseBodyToObject($body, $content_type) { /* No body to convert */ if (empty($body)) { return null; } /* Convert to Mollie_Response object or return as string. */ if (preg_match('/(application|text)\/xml/i', $content_type)) { return simplexml_load_string($body, "Mollie_Response"); } return $body; }
[ "final", "private", "function", "convertResponseBodyToObject", "(", "$", "body", ",", "$", "content_type", ")", "{", "/* No body to convert */", "if", "(", "empty", "(", "$", "body", ")", ")", "{", "return", "null", ";", "}", "/* Convert to Mollie_Response object or return as string. */", "if", "(", "preg_match", "(", "'/(application|text)\\/xml/i'", ",", "$", "content_type", ")", ")", "{", "return", "simplexml_load_string", "(", "$", "body", ",", "\"Mollie_Response\"", ")", ";", "}", "return", "$", "body", ";", "}" ]
Convert result body to an object based on Content-Type. @param string $body @param string $content_type @return mixed
[ "Convert", "result", "body", "to", "an", "object", "based", "on", "Content", "-", "Type", "." ]
d573d418ceebd54705d6069cb0adad4a10220395
https://github.com/mollie/reseller-api/blob/d573d418ceebd54705d6069cb0adad4a10220395/php/src/mollie/api.php#L314-L326
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Mixin/Traits/HasContentBlocksTrait.php
HasContentBlocksTrait.metaDescFromAttachments
private function metaDescFromAttachments() { $attachments = $this->getAttachments(); if (!$attachments) { return null; } foreach ($attachments as $attachment) { if ($attachment->isText()) { $content = $attachment->description(); $content = $this->ellipsis($content); return $content; } } return null; }
php
private function metaDescFromAttachments() { $attachments = $this->getAttachments(); if (!$attachments) { return null; } foreach ($attachments as $attachment) { if ($attachment->isText()) { $content = $attachment->description(); $content = $this->ellipsis($content); return $content; } } return null; }
[ "private", "function", "metaDescFromAttachments", "(", ")", "{", "$", "attachments", "=", "$", "this", "->", "getAttachments", "(", ")", ";", "if", "(", "!", "$", "attachments", ")", "{", "return", "null", ";", "}", "foreach", "(", "$", "attachments", "as", "$", "attachment", ")", "{", "if", "(", "$", "attachment", "->", "isText", "(", ")", ")", "{", "$", "content", "=", "$", "attachment", "->", "description", "(", ")", ";", "$", "content", "=", "$", "this", "->", "ellipsis", "(", "$", "content", ")", ";", "return", "$", "content", ";", "}", "}", "return", "null", ";", "}" ]
Gets the content excerpt from attachments if a text attachment is found, otherwise it return null. @return Translation|null|string|\string[] The content from attachment
[ "Gets", "the", "content", "excerpt", "from", "attachments", "if", "a", "text", "attachment", "is", "found", "otherwise", "it", "return", "null", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Mixin/Traits/HasContentBlocksTrait.php#L69-L88
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/EventManager.php
EventManager.numPages
public function numPages() { if ($this->numPage) { $this->numPage; }; $entries = $this->entries(); $count = count($entries); if ($this->numPerPage()) { $this->numPage = ceil($count / $this->numPerPage()); } else { $this->numPage = 1; } return $this->numPage; }
php
public function numPages() { if ($this->numPage) { $this->numPage; }; $entries = $this->entries(); $count = count($entries); if ($this->numPerPage()) { $this->numPage = ceil($count / $this->numPerPage()); } else { $this->numPage = 1; } return $this->numPage; }
[ "public", "function", "numPages", "(", ")", "{", "if", "(", "$", "this", "->", "numPage", ")", "{", "$", "this", "->", "numPage", ";", "}", ";", "$", "entries", "=", "$", "this", "->", "entries", "(", ")", ";", "$", "count", "=", "count", "(", "$", "entries", ")", ";", "if", "(", "$", "this", "->", "numPerPage", "(", ")", ")", "{", "$", "this", "->", "numPage", "=", "ceil", "(", "$", "count", "/", "$", "this", "->", "numPerPage", "(", ")", ")", ";", "}", "else", "{", "$", "this", "->", "numPage", "=", "1", ";", "}", "return", "$", "this", "->", "numPage", ";", "}" ]
The total amount of pages. @return float
[ "The", "total", "amount", "of", "pages", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/EventManager.php#L513-L529
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/EventManager.php
EventManager.setYear
public function setYear($year) { if (!is_scalar($year)) { throw new Exception('Year must be a string or an integer in EventManager setYear method.'); } $this->year = $year; return $this->year; }
php
public function setYear($year) { if (!is_scalar($year)) { throw new Exception('Year must be a string or an integer in EventManager setYear method.'); } $this->year = $year; return $this->year; }
[ "public", "function", "setYear", "(", "$", "year", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "year", ")", ")", "{", "throw", "new", "Exception", "(", "'Year must be a string or an integer in EventManager setYear method.'", ")", ";", "}", "$", "this", "->", "year", "=", "$", "year", ";", "return", "$", "this", "->", "year", ";", "}" ]
Full year. @param mixed $year Full year. @throws Exception If argument is not scalar. @return EventManager
[ "Full", "year", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/EventManager.php#L722-L730
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/EventManager.php
EventManager.setPrevNext
public function setPrevNext() { if ($this->prevEvent && $this->nextEvent) { return $this; } $entries = $this->entries(); $isPrev = false; $isNext = false; $firstEvent = false; $lastEvent = false; foreach ($entries as $event) { // Obtain th first event. if (!$firstEvent) { $firstEvent = $event; } $lastEvent = $event; // Find the current event if ($event->id() == $this->currentEvent()['id']) { $isNext = true; $isPrev = true; continue; } if (!$isPrev) { $this->prevEvent = $event; } // Store the next event if ($isNext) { $this->nextEvent = $event; $isNext = false; } } if ($this->entryCycle()) { if (!$this->nextEvent) { $this->nextEvent = $firstEvent; } if (!$this->prevEvent) { $this->prevEvent = $lastEvent; } } return $this; }
php
public function setPrevNext() { if ($this->prevEvent && $this->nextEvent) { return $this; } $entries = $this->entries(); $isPrev = false; $isNext = false; $firstEvent = false; $lastEvent = false; foreach ($entries as $event) { // Obtain th first event. if (!$firstEvent) { $firstEvent = $event; } $lastEvent = $event; // Find the current event if ($event->id() == $this->currentEvent()['id']) { $isNext = true; $isPrev = true; continue; } if (!$isPrev) { $this->prevEvent = $event; } // Store the next event if ($isNext) { $this->nextEvent = $event; $isNext = false; } } if ($this->entryCycle()) { if (!$this->nextEvent) { $this->nextEvent = $firstEvent; } if (!$this->prevEvent) { $this->prevEvent = $lastEvent; } } return $this; }
[ "public", "function", "setPrevNext", "(", ")", "{", "if", "(", "$", "this", "->", "prevEvent", "&&", "$", "this", "->", "nextEvent", ")", "{", "return", "$", "this", ";", "}", "$", "entries", "=", "$", "this", "->", "entries", "(", ")", ";", "$", "isPrev", "=", "false", ";", "$", "isNext", "=", "false", ";", "$", "firstEvent", "=", "false", ";", "$", "lastEvent", "=", "false", ";", "foreach", "(", "$", "entries", "as", "$", "event", ")", "{", "// Obtain th first event.", "if", "(", "!", "$", "firstEvent", ")", "{", "$", "firstEvent", "=", "$", "event", ";", "}", "$", "lastEvent", "=", "$", "event", ";", "// Find the current event", "if", "(", "$", "event", "->", "id", "(", ")", "==", "$", "this", "->", "currentEvent", "(", ")", "[", "'id'", "]", ")", "{", "$", "isNext", "=", "true", ";", "$", "isPrev", "=", "true", ";", "continue", ";", "}", "if", "(", "!", "$", "isPrev", ")", "{", "$", "this", "->", "prevEvent", "=", "$", "event", ";", "}", "// Store the next event", "if", "(", "$", "isNext", ")", "{", "$", "this", "->", "nextEvent", "=", "$", "event", ";", "$", "isNext", "=", "false", ";", "}", "}", "if", "(", "$", "this", "->", "entryCycle", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "nextEvent", ")", "{", "$", "this", "->", "nextEvent", "=", "$", "firstEvent", ";", "}", "if", "(", "!", "$", "this", "->", "prevEvent", ")", "{", "$", "this", "->", "prevEvent", "=", "$", "lastEvent", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set the Prev and Next event @return $this
[ "Set", "the", "Prev", "and", "Next", "event" ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/EventManager.php#L768-L815
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/Service/Manager/EventManager.php
EventManager.mapEvents
public function mapEvents() { if ($this->mapEvents) { return $this->mapEvents; } $events = $this->all(); $out = []; foreach ($events as $ev) { $firstDate = $ev->startDate(); $lastDate = $ev->endDate(); $current = new DateTime(); $current->setTimestamp($firstDate->getTimestamp()); while ($current <= $lastDate) { $year = $current->format('Y'); $month = $current->format('m'); $day = $current->format('d'); if (!isset($out[$year])) { $out[$year] = []; } if (!isset($out[$year][$month])) { $out[$year][$month] = []; } if (!isset($out[$year][$month][$day])) { $out[$year][$month][$day] = []; } $out[$year][$month][$day][] = $ev; $current->modify('+1 day'); } } $this->mapEvents = $out; return $this->mapEvents; }
php
public function mapEvents() { if ($this->mapEvents) { return $this->mapEvents; } $events = $this->all(); $out = []; foreach ($events as $ev) { $firstDate = $ev->startDate(); $lastDate = $ev->endDate(); $current = new DateTime(); $current->setTimestamp($firstDate->getTimestamp()); while ($current <= $lastDate) { $year = $current->format('Y'); $month = $current->format('m'); $day = $current->format('d'); if (!isset($out[$year])) { $out[$year] = []; } if (!isset($out[$year][$month])) { $out[$year][$month] = []; } if (!isset($out[$year][$month][$day])) { $out[$year][$month][$day] = []; } $out[$year][$month][$day][] = $ev; $current->modify('+1 day'); } } $this->mapEvents = $out; return $this->mapEvents; }
[ "public", "function", "mapEvents", "(", ")", "{", "if", "(", "$", "this", "->", "mapEvents", ")", "{", "return", "$", "this", "->", "mapEvents", ";", "}", "$", "events", "=", "$", "this", "->", "all", "(", ")", ";", "$", "out", "=", "[", "]", ";", "foreach", "(", "$", "events", "as", "$", "ev", ")", "{", "$", "firstDate", "=", "$", "ev", "->", "startDate", "(", ")", ";", "$", "lastDate", "=", "$", "ev", "->", "endDate", "(", ")", ";", "$", "current", "=", "new", "DateTime", "(", ")", ";", "$", "current", "->", "setTimestamp", "(", "$", "firstDate", "->", "getTimestamp", "(", ")", ")", ";", "while", "(", "$", "current", "<=", "$", "lastDate", ")", "{", "$", "year", "=", "$", "current", "->", "format", "(", "'Y'", ")", ";", "$", "month", "=", "$", "current", "->", "format", "(", "'m'", ")", ";", "$", "day", "=", "$", "current", "->", "format", "(", "'d'", ")", ";", "if", "(", "!", "isset", "(", "$", "out", "[", "$", "year", "]", ")", ")", "{", "$", "out", "[", "$", "year", "]", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "out", "[", "$", "year", "]", "[", "$", "month", "]", ")", ")", "{", "$", "out", "[", "$", "year", "]", "[", "$", "month", "]", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "out", "[", "$", "year", "]", "[", "$", "month", "]", "[", "$", "day", "]", ")", ")", "{", "$", "out", "[", "$", "year", "]", "[", "$", "month", "]", "[", "$", "day", "]", "=", "[", "]", ";", "}", "$", "out", "[", "$", "year", "]", "[", "$", "month", "]", "[", "$", "day", "]", "[", "]", "=", "$", "ev", ";", "$", "current", "->", "modify", "(", "'+1 day'", ")", ";", "}", "}", "$", "this", "->", "mapEvents", "=", "$", "out", ";", "return", "$", "this", "->", "mapEvents", ";", "}" ]
Mapping between events and dates @return array The array containing events stored as [$year][$month][$day][event]
[ "Mapping", "between", "events", "and", "dates" ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/Service/Manager/EventManager.php#L821-L863
train
locomotivemtl/charcoal-cms
src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php
MultiGroupFormGroup.formWidget
protected function formWidget() { if (!key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources()))) { return $this->form(); } return $this; }
php
protected function formWidget() { if (!key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources()))) { return $this->form(); } return $this; }
[ "protected", "function", "formWidget", "(", ")", "{", "if", "(", "!", "key_exists", "(", "self", "::", "DATA_SOURCE_METADATA", ",", "array_flip", "(", "$", "this", "->", "dataSources", "(", ")", ")", ")", ")", "{", "return", "$", "this", "->", "form", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
So that the formTrait can access the current From widget. @return FormInterface|self
[ "So", "that", "the", "formTrait", "can", "access", "the", "current", "From", "widget", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Admin/Widget/FormGroup/MultiGroupFormGroup.php#L174-L181
train
vanilla/garden-schema
src/Schema.php
Schema.parse
public static function parse(array $arr, ...$args) { $schema = new static([], ...$args); $schema->schema = $schema->parseInternal($arr); return $schema; }
php
public static function parse(array $arr, ...$args) { $schema = new static([], ...$args); $schema->schema = $schema->parseInternal($arr); return $schema; }
[ "public", "static", "function", "parse", "(", "array", "$", "arr", ",", "...", "$", "args", ")", "{", "$", "schema", "=", "new", "static", "(", "[", "]", ",", "...", "$", "args", ")", ";", "$", "schema", "->", "schema", "=", "$", "schema", "->", "parseInternal", "(", "$", "arr", ")", ";", "return", "$", "schema", ";", "}" ]
Parse a short schema and return the associated schema. @param array $arr The schema array. @param mixed[] $args Constructor arguments for the schema instance. @return static Returns a new schema.
[ "Parse", "a", "short", "schema", "and", "return", "the", "associated", "schema", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L105-L109
train
vanilla/garden-schema
src/Schema.php
Schema.parseInternal
protected function parseInternal(array $arr): array { if (empty($arr)) { // An empty schema validates to anything. return []; } elseif (isset($arr['type'])) { // This is a long form schema and can be parsed as the root. return $this->parseNode($arr); } else { // Check for a root schema. $value = reset($arr); $key = key($arr); if (is_int($key)) { $key = $value; $value = null; } list ($name, $param) = $this->parseShortParam($key, $value); if (empty($name)) { return $this->parseNode($param, $value); } } // If we are here then this is n object schema. list($properties, $required) = $this->parseProperties($arr); $result = [ 'type' => 'object', 'properties' => $properties, 'required' => $required ]; return array_filter($result); }
php
protected function parseInternal(array $arr): array { if (empty($arr)) { // An empty schema validates to anything. return []; } elseif (isset($arr['type'])) { // This is a long form schema and can be parsed as the root. return $this->parseNode($arr); } else { // Check for a root schema. $value = reset($arr); $key = key($arr); if (is_int($key)) { $key = $value; $value = null; } list ($name, $param) = $this->parseShortParam($key, $value); if (empty($name)) { return $this->parseNode($param, $value); } } // If we are here then this is n object schema. list($properties, $required) = $this->parseProperties($arr); $result = [ 'type' => 'object', 'properties' => $properties, 'required' => $required ]; return array_filter($result); }
[ "protected", "function", "parseInternal", "(", "array", "$", "arr", ")", ":", "array", "{", "if", "(", "empty", "(", "$", "arr", ")", ")", "{", "// An empty schema validates to anything.", "return", "[", "]", ";", "}", "elseif", "(", "isset", "(", "$", "arr", "[", "'type'", "]", ")", ")", "{", "// This is a long form schema and can be parsed as the root.", "return", "$", "this", "->", "parseNode", "(", "$", "arr", ")", ";", "}", "else", "{", "// Check for a root schema.", "$", "value", "=", "reset", "(", "$", "arr", ")", ";", "$", "key", "=", "key", "(", "$", "arr", ")", ";", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "key", "=", "$", "value", ";", "$", "value", "=", "null", ";", "}", "list", "(", "$", "name", ",", "$", "param", ")", "=", "$", "this", "->", "parseShortParam", "(", "$", "key", ",", "$", "value", ")", ";", "if", "(", "empty", "(", "$", "name", ")", ")", "{", "return", "$", "this", "->", "parseNode", "(", "$", "param", ",", "$", "value", ")", ";", "}", "}", "// If we are here then this is n object schema.", "list", "(", "$", "properties", ",", "$", "required", ")", "=", "$", "this", "->", "parseProperties", "(", "$", "arr", ")", ";", "$", "result", "=", "[", "'type'", "=>", "'object'", ",", "'properties'", "=>", "$", "properties", ",", "'required'", "=>", "$", "required", "]", ";", "return", "array_filter", "(", "$", "result", ")", ";", "}" ]
Parse a schema in short form into a full schema array. @param array $arr The array to parse into a schema. @return array The full schema array. @throws ParseException Throws an exception when an item in the schema is invalid.
[ "Parse", "a", "schema", "in", "short", "form", "into", "a", "full", "schema", "array", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L118-L149
train
vanilla/garden-schema
src/Schema.php
Schema.parseNode
private function parseNode($node, $value = null) { if (is_array($value)) { if (is_array($node['type'])) { trigger_error('Schemas with multiple types are deprecated.', E_USER_DEPRECATED); } // The value describes a bit more about the schema. switch ($node['type']) { case 'array': if (isset($value['items'])) { // The value includes array schema information. $node = array_replace($node, $value); } else { $node['items'] = $this->parseInternal($value); } break; case 'object': // The value is a schema of the object. if (isset($value['properties'])) { list($node['properties']) = $this->parseProperties($value['properties']); } else { list($node['properties'], $required) = $this->parseProperties($value); if (!empty($required)) { $node['required'] = $required; } } break; default: $node = array_replace($node, $value); break; } } elseif (is_string($value)) { if ($node['type'] === 'array' && $arrType = $this->getType($value)) { $node['items'] = ['type' => $arrType]; } elseif (!empty($value)) { $node['description'] = $value; } } elseif ($value === null) { // Parse child elements. if ($node['type'] === 'array' && isset($node['items'])) { // The value includes array schema information. $node['items'] = $this->parseInternal($node['items']); } elseif ($node['type'] === 'object' && isset($node['properties'])) { list($node['properties']) = $this->parseProperties($node['properties']); } } if (is_array($node)) { if (!empty($node['allowNull'])) { $node['nullable'] = true; } unset($node['allowNull']); if ($node['type'] === null || $node['type'] === []) { unset($node['type']); } } return $node; }
php
private function parseNode($node, $value = null) { if (is_array($value)) { if (is_array($node['type'])) { trigger_error('Schemas with multiple types are deprecated.', E_USER_DEPRECATED); } // The value describes a bit more about the schema. switch ($node['type']) { case 'array': if (isset($value['items'])) { // The value includes array schema information. $node = array_replace($node, $value); } else { $node['items'] = $this->parseInternal($value); } break; case 'object': // The value is a schema of the object. if (isset($value['properties'])) { list($node['properties']) = $this->parseProperties($value['properties']); } else { list($node['properties'], $required) = $this->parseProperties($value); if (!empty($required)) { $node['required'] = $required; } } break; default: $node = array_replace($node, $value); break; } } elseif (is_string($value)) { if ($node['type'] === 'array' && $arrType = $this->getType($value)) { $node['items'] = ['type' => $arrType]; } elseif (!empty($value)) { $node['description'] = $value; } } elseif ($value === null) { // Parse child elements. if ($node['type'] === 'array' && isset($node['items'])) { // The value includes array schema information. $node['items'] = $this->parseInternal($node['items']); } elseif ($node['type'] === 'object' && isset($node['properties'])) { list($node['properties']) = $this->parseProperties($node['properties']); } } if (is_array($node)) { if (!empty($node['allowNull'])) { $node['nullable'] = true; } unset($node['allowNull']); if ($node['type'] === null || $node['type'] === []) { unset($node['type']); } } return $node; }
[ "private", "function", "parseNode", "(", "$", "node", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "if", "(", "is_array", "(", "$", "node", "[", "'type'", "]", ")", ")", "{", "trigger_error", "(", "'Schemas with multiple types are deprecated.'", ",", "E_USER_DEPRECATED", ")", ";", "}", "// The value describes a bit more about the schema.", "switch", "(", "$", "node", "[", "'type'", "]", ")", "{", "case", "'array'", ":", "if", "(", "isset", "(", "$", "value", "[", "'items'", "]", ")", ")", "{", "// The value includes array schema information.", "$", "node", "=", "array_replace", "(", "$", "node", ",", "$", "value", ")", ";", "}", "else", "{", "$", "node", "[", "'items'", "]", "=", "$", "this", "->", "parseInternal", "(", "$", "value", ")", ";", "}", "break", ";", "case", "'object'", ":", "// The value is a schema of the object.", "if", "(", "isset", "(", "$", "value", "[", "'properties'", "]", ")", ")", "{", "list", "(", "$", "node", "[", "'properties'", "]", ")", "=", "$", "this", "->", "parseProperties", "(", "$", "value", "[", "'properties'", "]", ")", ";", "}", "else", "{", "list", "(", "$", "node", "[", "'properties'", "]", ",", "$", "required", ")", "=", "$", "this", "->", "parseProperties", "(", "$", "value", ")", ";", "if", "(", "!", "empty", "(", "$", "required", ")", ")", "{", "$", "node", "[", "'required'", "]", "=", "$", "required", ";", "}", "}", "break", ";", "default", ":", "$", "node", "=", "array_replace", "(", "$", "node", ",", "$", "value", ")", ";", "break", ";", "}", "}", "elseif", "(", "is_string", "(", "$", "value", ")", ")", "{", "if", "(", "$", "node", "[", "'type'", "]", "===", "'array'", "&&", "$", "arrType", "=", "$", "this", "->", "getType", "(", "$", "value", ")", ")", "{", "$", "node", "[", "'items'", "]", "=", "[", "'type'", "=>", "$", "arrType", "]", ";", "}", "elseif", "(", "!", "empty", "(", "$", "value", ")", ")", "{", "$", "node", "[", "'description'", "]", "=", "$", "value", ";", "}", "}", "elseif", "(", "$", "value", "===", "null", ")", "{", "// Parse child elements.", "if", "(", "$", "node", "[", "'type'", "]", "===", "'array'", "&&", "isset", "(", "$", "node", "[", "'items'", "]", ")", ")", "{", "// The value includes array schema information.", "$", "node", "[", "'items'", "]", "=", "$", "this", "->", "parseInternal", "(", "$", "node", "[", "'items'", "]", ")", ";", "}", "elseif", "(", "$", "node", "[", "'type'", "]", "===", "'object'", "&&", "isset", "(", "$", "node", "[", "'properties'", "]", ")", ")", "{", "list", "(", "$", "node", "[", "'properties'", "]", ")", "=", "$", "this", "->", "parseProperties", "(", "$", "node", "[", "'properties'", "]", ")", ";", "}", "}", "if", "(", "is_array", "(", "$", "node", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "node", "[", "'allowNull'", "]", ")", ")", "{", "$", "node", "[", "'nullable'", "]", "=", "true", ";", "}", "unset", "(", "$", "node", "[", "'allowNull'", "]", ")", ";", "if", "(", "$", "node", "[", "'type'", "]", "===", "null", "||", "$", "node", "[", "'type'", "]", "===", "[", "]", ")", "{", "unset", "(", "$", "node", "[", "'type'", "]", ")", ";", "}", "}", "return", "$", "node", ";", "}" ]
Parse a schema node. @param array|Schema $node The node to parse. @param mixed $value Additional information from the node. @return array|\ArrayAccess Returns a JSON schema compatible node. @throws ParseException Throws an exception if there was a problem parsing the schema node.
[ "Parse", "a", "schema", "node", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L159-L218
train
vanilla/garden-schema
src/Schema.php
Schema.parseProperties
private function parseProperties(array $arr): array { $properties = []; $requiredProperties = []; foreach ($arr as $key => $value) { // Fix a schema specified as just a value. if (is_int($key)) { if (is_string($value)) { $key = $value; $value = ''; } else { throw new ParseException("Schema at position $key is not a valid parameter.", 500); } } // The parameter is defined in the key. list($name, $param, $required) = $this->parseShortParam($key, $value); $node = $this->parseNode($param, $value); $properties[$name] = $node; if ($required) { $requiredProperties[] = $name; } } return [$properties, $requiredProperties]; }
php
private function parseProperties(array $arr): array { $properties = []; $requiredProperties = []; foreach ($arr as $key => $value) { // Fix a schema specified as just a value. if (is_int($key)) { if (is_string($value)) { $key = $value; $value = ''; } else { throw new ParseException("Schema at position $key is not a valid parameter.", 500); } } // The parameter is defined in the key. list($name, $param, $required) = $this->parseShortParam($key, $value); $node = $this->parseNode($param, $value); $properties[$name] = $node; if ($required) { $requiredProperties[] = $name; } } return [$properties, $requiredProperties]; }
[ "private", "function", "parseProperties", "(", "array", "$", "arr", ")", ":", "array", "{", "$", "properties", "=", "[", "]", ";", "$", "requiredProperties", "=", "[", "]", ";", "foreach", "(", "$", "arr", "as", "$", "key", "=>", "$", "value", ")", "{", "// Fix a schema specified as just a value.", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "key", "=", "$", "value", ";", "$", "value", "=", "''", ";", "}", "else", "{", "throw", "new", "ParseException", "(", "\"Schema at position $key is not a valid parameter.\"", ",", "500", ")", ";", "}", "}", "// The parameter is defined in the key.", "list", "(", "$", "name", ",", "$", "param", ",", "$", "required", ")", "=", "$", "this", "->", "parseShortParam", "(", "$", "key", ",", "$", "value", ")", ";", "$", "node", "=", "$", "this", "->", "parseNode", "(", "$", "param", ",", "$", "value", ")", ";", "$", "properties", "[", "$", "name", "]", "=", "$", "node", ";", "if", "(", "$", "required", ")", "{", "$", "requiredProperties", "[", "]", "=", "$", "name", ";", "}", "}", "return", "[", "$", "properties", ",", "$", "requiredProperties", "]", ";", "}" ]
Parse the schema for an object's properties. @param array $arr An object property schema. @return array Returns a schema array suitable to be placed in the **properties** key of a schema. @throws ParseException Throws an exception if a property name cannot be determined for an array item.
[ "Parse", "the", "schema", "for", "an", "object", "s", "properties", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L227-L252
train
vanilla/garden-schema
src/Schema.php
Schema.getType
private function getType($alias) { if (isset(self::$types[$alias])) { return $alias; } foreach (self::$types as $type => $aliases) { if (in_array($alias, $aliases, true)) { return $type; } } return null; }
php
private function getType($alias) { if (isset(self::$types[$alias])) { return $alias; } foreach (self::$types as $type => $aliases) { if (in_array($alias, $aliases, true)) { return $type; } } return null; }
[ "private", "function", "getType", "(", "$", "alias", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "types", "[", "$", "alias", "]", ")", ")", "{", "return", "$", "alias", ";", "}", "foreach", "(", "self", "::", "$", "types", "as", "$", "type", "=>", "$", "aliases", ")", "{", "if", "(", "in_array", "(", "$", "alias", ",", "$", "aliases", ",", "true", ")", ")", "{", "return", "$", "type", ";", "}", "}", "return", "null", ";", "}" ]
Look up a type based on its alias. @param string $alias The type alias or type name to lookup. @return mixed
[ "Look", "up", "a", "type", "based", "on", "its", "alias", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L356-L366
train
vanilla/garden-schema
src/Schema.php
Schema.getField
public function getField($path, $default = null) { if (is_string($path)) { if (strpos($path, '.') !== false && strpos($path, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $path = explode('.', $path); } else { $path = explode('/', $path); } } $value = $this->schema; foreach ($path as $i => $subKey) { if (is_array($value) && isset($value[$subKey])) { $value = $value[$subKey]; } elseif ($value instanceof Schema) { return $value->getField(array_slice($path, $i), $default); } else { return $default; } } return $value; }
php
public function getField($path, $default = null) { if (is_string($path)) { if (strpos($path, '.') !== false && strpos($path, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $path = explode('.', $path); } else { $path = explode('/', $path); } } $value = $this->schema; foreach ($path as $i => $subKey) { if (is_array($value) && isset($value[$subKey])) { $value = $value[$subKey]; } elseif ($value instanceof Schema) { return $value->getField(array_slice($path, $i), $default); } else { return $default; } } return $value; }
[ "public", "function", "getField", "(", "$", "path", ",", "$", "default", "=", "null", ")", "{", "if", "(", "is_string", "(", "$", "path", ")", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "'.'", ")", "!==", "false", "&&", "strpos", "(", "$", "path", ",", "'/'", ")", "===", "false", ")", "{", "trigger_error", "(", "'Field selectors must be separated by \"/\" instead of \".\"'", ",", "E_USER_DEPRECATED", ")", ";", "$", "path", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "}", "else", "{", "$", "path", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "}", "}", "$", "value", "=", "$", "this", "->", "schema", ";", "foreach", "(", "$", "path", "as", "$", "i", "=>", "$", "subKey", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "&&", "isset", "(", "$", "value", "[", "$", "subKey", "]", ")", ")", "{", "$", "value", "=", "$", "value", "[", "$", "subKey", "]", ";", "}", "elseif", "(", "$", "value", "instanceof", "Schema", ")", "{", "return", "$", "value", "->", "getField", "(", "array_slice", "(", "$", "path", ",", "$", "i", ")", ",", "$", "default", ")", ";", "}", "else", "{", "return", "$", "default", ";", "}", "}", "return", "$", "value", ";", "}" ]
Get a schema field. @param string|array $path The JSON schema path of the field with parts separated by dots. @param mixed $default The value to return if the field isn't found. @return mixed Returns the field value or `$default`.
[ "Get", "a", "schema", "field", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L433-L454
train
vanilla/garden-schema
src/Schema.php
Schema.setField
public function setField($path, $value) { if (is_string($path)) { if (strpos($path, '.') !== false && strpos($path, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $path = explode('.', $path); } else { $path = explode('/', $path); } } $selection = &$this->schema; foreach ($path as $i => $subSelector) { if (is_array($selection)) { if (!isset($selection[$subSelector])) { $selection[$subSelector] = []; } } elseif ($selection instanceof Schema) { $selection->setField(array_slice($path, $i), $value); return $this; } else { $selection = [$subSelector => []]; } $selection = &$selection[$subSelector]; } $selection = $value; return $this; }
php
public function setField($path, $value) { if (is_string($path)) { if (strpos($path, '.') !== false && strpos($path, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $path = explode('.', $path); } else { $path = explode('/', $path); } } $selection = &$this->schema; foreach ($path as $i => $subSelector) { if (is_array($selection)) { if (!isset($selection[$subSelector])) { $selection[$subSelector] = []; } } elseif ($selection instanceof Schema) { $selection->setField(array_slice($path, $i), $value); return $this; } else { $selection = [$subSelector => []]; } $selection = &$selection[$subSelector]; } $selection = $value; return $this; }
[ "public", "function", "setField", "(", "$", "path", ",", "$", "value", ")", "{", "if", "(", "is_string", "(", "$", "path", ")", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "'.'", ")", "!==", "false", "&&", "strpos", "(", "$", "path", ",", "'/'", ")", "===", "false", ")", "{", "trigger_error", "(", "'Field selectors must be separated by \"/\" instead of \".\"'", ",", "E_USER_DEPRECATED", ")", ";", "$", "path", "=", "explode", "(", "'.'", ",", "$", "path", ")", ";", "}", "else", "{", "$", "path", "=", "explode", "(", "'/'", ",", "$", "path", ")", ";", "}", "}", "$", "selection", "=", "&", "$", "this", "->", "schema", ";", "foreach", "(", "$", "path", "as", "$", "i", "=>", "$", "subSelector", ")", "{", "if", "(", "is_array", "(", "$", "selection", ")", ")", "{", "if", "(", "!", "isset", "(", "$", "selection", "[", "$", "subSelector", "]", ")", ")", "{", "$", "selection", "[", "$", "subSelector", "]", "=", "[", "]", ";", "}", "}", "elseif", "(", "$", "selection", "instanceof", "Schema", ")", "{", "$", "selection", "->", "setField", "(", "array_slice", "(", "$", "path", ",", "$", "i", ")", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}", "else", "{", "$", "selection", "=", "[", "$", "subSelector", "=>", "[", "]", "]", ";", "}", "$", "selection", "=", "&", "$", "selection", "[", "$", "subSelector", "]", ";", "}", "$", "selection", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Set a schema field. @param string|array $path The JSON schema path of the field with parts separated by slashes. @param mixed $value The new value. @return $this
[ "Set", "a", "schema", "field", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L463-L490
train
vanilla/garden-schema
src/Schema.php
Schema.setFlag
public function setFlag(int $flag, bool $value) { if ($value) { $this->flags = $this->flags | $flag; } else { $this->flags = $this->flags & ~$flag; } return $this; }
php
public function setFlag(int $flag, bool $value) { if ($value) { $this->flags = $this->flags | $flag; } else { $this->flags = $this->flags & ~$flag; } return $this; }
[ "public", "function", "setFlag", "(", "int", "$", "flag", ",", "bool", "$", "value", ")", "{", "if", "(", "$", "value", ")", "{", "$", "this", "->", "flags", "=", "$", "this", "->", "flags", "|", "$", "flag", ";", "}", "else", "{", "$", "this", "->", "flags", "=", "$", "this", "->", "flags", "&", "~", "$", "flag", ";", "}", "return", "$", "this", ";", "}" ]
Set a flag. @param int $flag One or more of the **Schema::VALIDATE_*** constants. @param bool $value Either true or false. @return $this
[ "Set", "a", "flag", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L520-L527
train
vanilla/garden-schema
src/Schema.php
Schema.merge
public function merge(Schema $schema) { $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true); return $this; }
php
public function merge(Schema $schema) { $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true); return $this; }
[ "public", "function", "merge", "(", "Schema", "$", "schema", ")", "{", "$", "this", "->", "mergeInternal", "(", "$", "this", "->", "schema", ",", "$", "schema", "->", "getSchemaArray", "(", ")", ",", "true", ",", "true", ")", ";", "return", "$", "this", ";", "}" ]
Merge a schema with this one. @param Schema $schema A scheme instance. Its parameters will be merged into the current instance. @return $this
[ "Merge", "a", "schema", "with", "this", "one", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L535-L538
train
vanilla/garden-schema
src/Schema.php
Schema.add
public function add(Schema $schema, $addProperties = false) { $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties); return $this; }
php
public function add(Schema $schema, $addProperties = false) { $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties); return $this; }
[ "public", "function", "add", "(", "Schema", "$", "schema", ",", "$", "addProperties", "=", "false", ")", "{", "$", "this", "->", "mergeInternal", "(", "$", "this", "->", "schema", ",", "$", "schema", "->", "getSchemaArray", "(", ")", ",", "false", ",", "$", "addProperties", ")", ";", "return", "$", "this", ";", "}" ]
Add another schema to this one. Adding schemas together is analogous to array addition. When you add a schema it will only add missing information. @param Schema $schema The schema to add. @param bool $addProperties Whether to add properties that don't exist in this schema. @return $this
[ "Add", "another", "schema", "to", "this", "one", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L629-L632
train
vanilla/garden-schema
src/Schema.php
Schema.addFilter
public function addFilter(string $fieldname, callable $callback, bool $validate = false) { $fieldname = $this->parseFieldSelector($fieldname); $this->filters[$fieldname][] = [$callback, $validate]; return $this; }
php
public function addFilter(string $fieldname, callable $callback, bool $validate = false) { $fieldname = $this->parseFieldSelector($fieldname); $this->filters[$fieldname][] = [$callback, $validate]; return $this; }
[ "public", "function", "addFilter", "(", "string", "$", "fieldname", ",", "callable", "$", "callback", ",", "bool", "$", "validate", "=", "false", ")", "{", "$", "fieldname", "=", "$", "this", "->", "parseFieldSelector", "(", "$", "fieldname", ")", ";", "$", "this", "->", "filters", "[", "$", "fieldname", "]", "[", "]", "=", "[", "$", "callback", ",", "$", "validate", "]", ";", "return", "$", "this", ";", "}" ]
Add a custom filter to change data before validation. @param string $fieldname The name of the field to filter, if any. If you are adding a filter to a deeply nested field then separate the path with dots. @param callable $callback The callback to filter the field. @param bool $validate Whether or not the filter should also validate. If true default validation is skipped. @return $this
[ "Add", "a", "custom", "filter", "to", "change", "data", "before", "validation", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L644-L648
train
vanilla/garden-schema
src/Schema.php
Schema.parseFieldSelector
private function parseFieldSelector(string $field): string { if (strlen($field) === 0) { return $field; } if (strpos($field, '.') !== false) { if (strpos($field, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $parts = explode('.', $field); $parts = @array_map([$this, 'parseFieldSelector'], $parts); // silence because error triggered already. $field = implode('/', $parts); } } elseif ($field === '[]') { trigger_error('Field selectors with item selector "[]" must be converted to "items".', E_USER_DEPRECATED); $field = 'items'; } elseif (strpos($field, '/') === false && !in_array($field, ['items', 'additionalProperties'], true)) { trigger_error("Field selectors must specify full schema paths. ($field)", E_USER_DEPRECATED); $field = "/properties/$field"; } if (strpos($field, '[]') !== false) { trigger_error('Field selectors with item selector "[]" must be converted to "/items".', E_USER_DEPRECATED); $field = str_replace('[]', '/items', $field); } return ltrim($field, '/'); }
php
private function parseFieldSelector(string $field): string { if (strlen($field) === 0) { return $field; } if (strpos($field, '.') !== false) { if (strpos($field, '/') === false) { trigger_error('Field selectors must be separated by "/" instead of "."', E_USER_DEPRECATED); $parts = explode('.', $field); $parts = @array_map([$this, 'parseFieldSelector'], $parts); // silence because error triggered already. $field = implode('/', $parts); } } elseif ($field === '[]') { trigger_error('Field selectors with item selector "[]" must be converted to "items".', E_USER_DEPRECATED); $field = 'items'; } elseif (strpos($field, '/') === false && !in_array($field, ['items', 'additionalProperties'], true)) { trigger_error("Field selectors must specify full schema paths. ($field)", E_USER_DEPRECATED); $field = "/properties/$field"; } if (strpos($field, '[]') !== false) { trigger_error('Field selectors with item selector "[]" must be converted to "/items".', E_USER_DEPRECATED); $field = str_replace('[]', '/items', $field); } return ltrim($field, '/'); }
[ "private", "function", "parseFieldSelector", "(", "string", "$", "field", ")", ":", "string", "{", "if", "(", "strlen", "(", "$", "field", ")", "===", "0", ")", "{", "return", "$", "field", ";", "}", "if", "(", "strpos", "(", "$", "field", ",", "'.'", ")", "!==", "false", ")", "{", "if", "(", "strpos", "(", "$", "field", ",", "'/'", ")", "===", "false", ")", "{", "trigger_error", "(", "'Field selectors must be separated by \"/\" instead of \".\"'", ",", "E_USER_DEPRECATED", ")", ";", "$", "parts", "=", "explode", "(", "'.'", ",", "$", "field", ")", ";", "$", "parts", "=", "@", "array_map", "(", "[", "$", "this", ",", "'parseFieldSelector'", "]", ",", "$", "parts", ")", ";", "// silence because error triggered already.", "$", "field", "=", "implode", "(", "'/'", ",", "$", "parts", ")", ";", "}", "}", "elseif", "(", "$", "field", "===", "'[]'", ")", "{", "trigger_error", "(", "'Field selectors with item selector \"[]\" must be converted to \"items\".'", ",", "E_USER_DEPRECATED", ")", ";", "$", "field", "=", "'items'", ";", "}", "elseif", "(", "strpos", "(", "$", "field", ",", "'/'", ")", "===", "false", "&&", "!", "in_array", "(", "$", "field", ",", "[", "'items'", ",", "'additionalProperties'", "]", ",", "true", ")", ")", "{", "trigger_error", "(", "\"Field selectors must specify full schema paths. ($field)\"", ",", "E_USER_DEPRECATED", ")", ";", "$", "field", "=", "\"/properties/$field\"", ";", "}", "if", "(", "strpos", "(", "$", "field", ",", "'[]'", ")", "!==", "false", ")", "{", "trigger_error", "(", "'Field selectors with item selector \"[]\" must be converted to \"/items\".'", ",", "E_USER_DEPRECATED", ")", ";", "$", "field", "=", "str_replace", "(", "'[]'", ",", "'/items'", ",", "$", "field", ")", ";", "}", "return", "ltrim", "(", "$", "field", ",", "'/'", ")", ";", "}" ]
Parse a nested field name selector. Field selectors should be separated by "/" characters, but may currently be separated by "." characters which triggers a deprecated error. @param string $field The field selector. @return string Returns the field selector in the correct format.
[ "Parse", "a", "nested", "field", "name", "selector", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L659-L687
train
vanilla/garden-schema
src/Schema.php
Schema.addFormatFilter
public function addFormatFilter(string $format, callable $callback, bool $validate = false) { if (empty($format)) { throw new \InvalidArgumentException('The filter format cannot be empty.', 500); } $filter = "/format/$format"; $this->filters[$filter][] = [$callback, $validate]; return $this; }
php
public function addFormatFilter(string $format, callable $callback, bool $validate = false) { if (empty($format)) { throw new \InvalidArgumentException('The filter format cannot be empty.', 500); } $filter = "/format/$format"; $this->filters[$filter][] = [$callback, $validate]; return $this; }
[ "public", "function", "addFormatFilter", "(", "string", "$", "format", ",", "callable", "$", "callback", ",", "bool", "$", "validate", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "format", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The filter format cannot be empty.'", ",", "500", ")", ";", "}", "$", "filter", "=", "\"/format/$format\"", ";", "$", "this", "->", "filters", "[", "$", "filter", "]", "[", "]", "=", "[", "$", "callback", ",", "$", "validate", "]", ";", "return", "$", "this", ";", "}" ]
Add a custom filter for a schema format. Schemas can use the `format` property to specify a specific format on a field. Adding a filter for a format allows you to customize the behavior of that format. @param string $format The format to filter. @param callable $callback The callback used to filter values. @param bool $validate Whether or not the filter should also validate. If true default validation is skipped. @return $this
[ "Add", "a", "custom", "filter", "for", "a", "schema", "format", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L700-L709
train
vanilla/garden-schema
src/Schema.php
Schema.requireOneOf
public function requireOneOf(array $required, string $fieldname = '', int $count = 1) { $result = $this->addValidator( $fieldname, function ($data, ValidationField $field) use ($required, $count) { // This validator does not apply to sparse validation. if ($field->isSparse()) { return true; } $hasCount = 0; $flattened = []; foreach ($required as $name) { $flattened = array_merge($flattened, (array)$name); if (is_array($name)) { // This is an array of required names. They all must match. $hasCountInner = 0; foreach ($name as $nameInner) { if (array_key_exists($nameInner, $data)) { $hasCountInner++; } else { break; } } if ($hasCountInner >= count($name)) { $hasCount++; } } elseif (array_key_exists($name, $data)) { $hasCount++; } if ($hasCount >= $count) { return true; } } if ($count === 1) { $message = 'One of {properties} are required.'; } else { $message = '{count} of {properties} are required.'; } $field->addError('oneOfRequired', [ 'messageCode' => $message, 'properties' => $required, 'count' => $count ]); return false; } ); return $result; }
php
public function requireOneOf(array $required, string $fieldname = '', int $count = 1) { $result = $this->addValidator( $fieldname, function ($data, ValidationField $field) use ($required, $count) { // This validator does not apply to sparse validation. if ($field->isSparse()) { return true; } $hasCount = 0; $flattened = []; foreach ($required as $name) { $flattened = array_merge($flattened, (array)$name); if (is_array($name)) { // This is an array of required names. They all must match. $hasCountInner = 0; foreach ($name as $nameInner) { if (array_key_exists($nameInner, $data)) { $hasCountInner++; } else { break; } } if ($hasCountInner >= count($name)) { $hasCount++; } } elseif (array_key_exists($name, $data)) { $hasCount++; } if ($hasCount >= $count) { return true; } } if ($count === 1) { $message = 'One of {properties} are required.'; } else { $message = '{count} of {properties} are required.'; } $field->addError('oneOfRequired', [ 'messageCode' => $message, 'properties' => $required, 'count' => $count ]); return false; } ); return $result; }
[ "public", "function", "requireOneOf", "(", "array", "$", "required", ",", "string", "$", "fieldname", "=", "''", ",", "int", "$", "count", "=", "1", ")", "{", "$", "result", "=", "$", "this", "->", "addValidator", "(", "$", "fieldname", ",", "function", "(", "$", "data", ",", "ValidationField", "$", "field", ")", "use", "(", "$", "required", ",", "$", "count", ")", "{", "// This validator does not apply to sparse validation.", "if", "(", "$", "field", "->", "isSparse", "(", ")", ")", "{", "return", "true", ";", "}", "$", "hasCount", "=", "0", ";", "$", "flattened", "=", "[", "]", ";", "foreach", "(", "$", "required", "as", "$", "name", ")", "{", "$", "flattened", "=", "array_merge", "(", "$", "flattened", ",", "(", "array", ")", "$", "name", ")", ";", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "// This is an array of required names. They all must match.", "$", "hasCountInner", "=", "0", ";", "foreach", "(", "$", "name", "as", "$", "nameInner", ")", "{", "if", "(", "array_key_exists", "(", "$", "nameInner", ",", "$", "data", ")", ")", "{", "$", "hasCountInner", "++", ";", "}", "else", "{", "break", ";", "}", "}", "if", "(", "$", "hasCountInner", ">=", "count", "(", "$", "name", ")", ")", "{", "$", "hasCount", "++", ";", "}", "}", "elseif", "(", "array_key_exists", "(", "$", "name", ",", "$", "data", ")", ")", "{", "$", "hasCount", "++", ";", "}", "if", "(", "$", "hasCount", ">=", "$", "count", ")", "{", "return", "true", ";", "}", "}", "if", "(", "$", "count", "===", "1", ")", "{", "$", "message", "=", "'One of {properties} are required.'", ";", "}", "else", "{", "$", "message", "=", "'{count} of {properties} are required.'", ";", "}", "$", "field", "->", "addError", "(", "'oneOfRequired'", ",", "[", "'messageCode'", "=>", "$", "message", ",", "'properties'", "=>", "$", "required", ",", "'count'", "=>", "$", "count", "]", ")", ";", "return", "false", ";", "}", ")", ";", "return", "$", "result", ";", "}" ]
Require one of a given set of fields in the schema. @param array $required The field names to require. @param string $fieldname The name of the field to attach to. @param int $count The count of required items. @return Schema Returns `$this` for fluent calls.
[ "Require", "one", "of", "a", "given", "set", "of", "fields", "in", "the", "schema", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L719-L772
train
vanilla/garden-schema
src/Schema.php
Schema.addValidator
public function addValidator(string $fieldname, callable $callback) { $fieldname = $this->parseFieldSelector($fieldname); $this->validators[$fieldname][] = $callback; return $this; }
php
public function addValidator(string $fieldname, callable $callback) { $fieldname = $this->parseFieldSelector($fieldname); $this->validators[$fieldname][] = $callback; return $this; }
[ "public", "function", "addValidator", "(", "string", "$", "fieldname", ",", "callable", "$", "callback", ")", "{", "$", "fieldname", "=", "$", "this", "->", "parseFieldSelector", "(", "$", "fieldname", ")", ";", "$", "this", "->", "validators", "[", "$", "fieldname", "]", "[", "]", "=", "$", "callback", ";", "return", "$", "this", ";", "}" ]
Add a custom validator to to validate the schema. @param string $fieldname The name of the field to validate, if any. If you are adding a validator to a deeply nested field then separate the path with dots. @param callable $callback The callback to validate with. @return Schema Returns `$this` for fluent calls.
[ "Add", "a", "custom", "validator", "to", "to", "validate", "the", "schema", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L783-L787
train
vanilla/garden-schema
src/Schema.php
Schema.validate
public function validate($data, $options = []) { if (is_bool($options)) { trigger_error('The $sparse parameter is deprecated. Use [\'sparse\' => true] instead.', E_USER_DEPRECATED); $options = ['sparse' => true]; } $options += ['sparse' => false]; list($schema, $schemaPath) = $this->lookupSchema($this->schema, ''); $field = new ValidationField($this->createValidation(), $schema, '', $schemaPath, $options); $clean = $this->validateField($data, $field); if (Invalid::isInvalid($clean) && $field->isValid()) { // This really shouldn't happen, but we want to protect against seeing the invalid object. $field->addError('invalid', ['messageCode' => 'The value is invalid.']); } if (!$field->getValidation()->isValid()) { throw new ValidationException($field->getValidation()); } return $clean; }
php
public function validate($data, $options = []) { if (is_bool($options)) { trigger_error('The $sparse parameter is deprecated. Use [\'sparse\' => true] instead.', E_USER_DEPRECATED); $options = ['sparse' => true]; } $options += ['sparse' => false]; list($schema, $schemaPath) = $this->lookupSchema($this->schema, ''); $field = new ValidationField($this->createValidation(), $schema, '', $schemaPath, $options); $clean = $this->validateField($data, $field); if (Invalid::isInvalid($clean) && $field->isValid()) { // This really shouldn't happen, but we want to protect against seeing the invalid object. $field->addError('invalid', ['messageCode' => 'The value is invalid.']); } if (!$field->getValidation()->isValid()) { throw new ValidationException($field->getValidation()); } return $clean; }
[ "public", "function", "validate", "(", "$", "data", ",", "$", "options", "=", "[", "]", ")", "{", "if", "(", "is_bool", "(", "$", "options", ")", ")", "{", "trigger_error", "(", "'The $sparse parameter is deprecated. Use [\\'sparse\\' => true] instead.'", ",", "E_USER_DEPRECATED", ")", ";", "$", "options", "=", "[", "'sparse'", "=>", "true", "]", ";", "}", "$", "options", "+=", "[", "'sparse'", "=>", "false", "]", ";", "list", "(", "$", "schema", ",", "$", "schemaPath", ")", "=", "$", "this", "->", "lookupSchema", "(", "$", "this", "->", "schema", ",", "''", ")", ";", "$", "field", "=", "new", "ValidationField", "(", "$", "this", "->", "createValidation", "(", ")", ",", "$", "schema", ",", "''", ",", "$", "schemaPath", ",", "$", "options", ")", ";", "$", "clean", "=", "$", "this", "->", "validateField", "(", "$", "data", ",", "$", "field", ")", ";", "if", "(", "Invalid", "::", "isInvalid", "(", "$", "clean", ")", "&&", "$", "field", "->", "isValid", "(", ")", ")", "{", "// This really shouldn't happen, but we want to protect against seeing the invalid object.", "$", "field", "->", "addError", "(", "'invalid'", ",", "[", "'messageCode'", "=>", "'The value is invalid.'", "]", ")", ";", "}", "if", "(", "!", "$", "field", "->", "getValidation", "(", ")", "->", "isValid", "(", ")", ")", "{", "throw", "new", "ValidationException", "(", "$", "field", "->", "getValidation", "(", ")", ")", ";", "}", "return", "$", "clean", ";", "}" ]
Validate data against the schema. @param mixed $data The data to validate. @param array $options Validation options. - **sparse**: Whether or not this is a sparse validation. @return mixed Returns a cleaned version of the data. @throws ValidationException Throws an exception when the data does not validate against the schema. @throws RefNotFoundException Throws an exception when a schema `$ref` is not found.
[ "Validate", "data", "against", "the", "schema", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L817-L840
train
vanilla/garden-schema
src/Schema.php
Schema.lookupSchema
private function lookupSchema($schema, string $schemaPath) { if ($schema instanceof Schema) { return [$schema, $schemaPath]; } else { $lookup = $this->getRefLookup(); $visited = []; // Resolve any references first. while (!empty($schema['$ref'])) { $schemaPath = $schema['$ref']; if (isset($visited[$schemaPath])) { throw new RefNotFoundException("Cyclical reference cannot be resolved. ($schemaPath)", 508); } $visited[$schemaPath] = true; try { $schema = call_user_func($lookup, $schemaPath); } catch (\Exception $ex) { throw new RefNotFoundException($ex->getMessage(), $ex->getCode(), $ex); } if ($schema === null) { throw new RefNotFoundException("Schema reference could not be found. ($schemaPath)"); } } return [$schema, $schemaPath]; } }
php
private function lookupSchema($schema, string $schemaPath) { if ($schema instanceof Schema) { return [$schema, $schemaPath]; } else { $lookup = $this->getRefLookup(); $visited = []; // Resolve any references first. while (!empty($schema['$ref'])) { $schemaPath = $schema['$ref']; if (isset($visited[$schemaPath])) { throw new RefNotFoundException("Cyclical reference cannot be resolved. ($schemaPath)", 508); } $visited[$schemaPath] = true; try { $schema = call_user_func($lookup, $schemaPath); } catch (\Exception $ex) { throw new RefNotFoundException($ex->getMessage(), $ex->getCode(), $ex); } if ($schema === null) { throw new RefNotFoundException("Schema reference could not be found. ($schemaPath)"); } } return [$schema, $schemaPath]; } }
[ "private", "function", "lookupSchema", "(", "$", "schema", ",", "string", "$", "schemaPath", ")", "{", "if", "(", "$", "schema", "instanceof", "Schema", ")", "{", "return", "[", "$", "schema", ",", "$", "schemaPath", "]", ";", "}", "else", "{", "$", "lookup", "=", "$", "this", "->", "getRefLookup", "(", ")", ";", "$", "visited", "=", "[", "]", ";", "// Resolve any references first.", "while", "(", "!", "empty", "(", "$", "schema", "[", "'$ref'", "]", ")", ")", "{", "$", "schemaPath", "=", "$", "schema", "[", "'$ref'", "]", ";", "if", "(", "isset", "(", "$", "visited", "[", "$", "schemaPath", "]", ")", ")", "{", "throw", "new", "RefNotFoundException", "(", "\"Cyclical reference cannot be resolved. ($schemaPath)\"", ",", "508", ")", ";", "}", "$", "visited", "[", "$", "schemaPath", "]", "=", "true", ";", "try", "{", "$", "schema", "=", "call_user_func", "(", "$", "lookup", ",", "$", "schemaPath", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "throw", "new", "RefNotFoundException", "(", "$", "ex", "->", "getMessage", "(", ")", ",", "$", "ex", "->", "getCode", "(", ")", ",", "$", "ex", ")", ";", "}", "if", "(", "$", "schema", "===", "null", ")", "{", "throw", "new", "RefNotFoundException", "(", "\"Schema reference could not be found. ($schemaPath)\"", ")", ";", "}", "}", "return", "[", "$", "schema", ",", "$", "schemaPath", "]", ";", "}", "}" ]
Lookup a schema based on a schema node. The node could be a schema array, `Schema` object, or a schema reference. @param mixed $schema The schema node to lookup with. @param string $schemaPath The current path of the schema. @return array Returns an array with two elements: - Schema|array|\ArrayAccess The schema that was found. - string The path of the schema. This is either the reference or the `$path` parameter for inline schemas. @throws RefNotFoundException Throws an exception when a reference could not be found.
[ "Lookup", "a", "schema", "based", "on", "a", "schema", "node", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L854-L882
train
vanilla/garden-schema
src/Schema.php
Schema.validateField
protected function validateField($value, ValidationField $field) { $validated = false; $result = $value = $this->filterField($value, $field, $validated); if ($validated) { return $result; } elseif ($field->getField() instanceof Schema) { try { $result = $field->getField()->validate($value, $field->getOptions()); } catch (ValidationException $ex) { // The validation failed, so merge the validations together. $field->getValidation()->merge($ex->getValidation(), $field->getName()); } } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && ($field->val('nullable') || $field->hasType('null'))) { $result = null; } else { // Look for a discriminator. if (!empty($field->val('discriminator'))) { $field = $this->resolveDiscriminator($value, $field); } if ($field !== null) { if($field->hasAllOf()) { $result = $this->validateAllOf($value, $field); } else { // Validate the field's type. $type = $field->getType(); if (is_array($type)) { $result = $this->validateMultipleTypes($value, $type, $field); } else { $result = $this->validateSingleType($value, $type, $field); } if (Invalid::isValid($result)) { $result = $this->validateEnum($result, $field); } } } else { $result = Invalid::value(); } } // Validate a custom field validator. if (Invalid::isValid($result)) { $this->callValidators($result, $field); } return $result; }
php
protected function validateField($value, ValidationField $field) { $validated = false; $result = $value = $this->filterField($value, $field, $validated); if ($validated) { return $result; } elseif ($field->getField() instanceof Schema) { try { $result = $field->getField()->validate($value, $field->getOptions()); } catch (ValidationException $ex) { // The validation failed, so merge the validations together. $field->getValidation()->merge($ex->getValidation(), $field->getName()); } } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && ($field->val('nullable') || $field->hasType('null'))) { $result = null; } else { // Look for a discriminator. if (!empty($field->val('discriminator'))) { $field = $this->resolveDiscriminator($value, $field); } if ($field !== null) { if($field->hasAllOf()) { $result = $this->validateAllOf($value, $field); } else { // Validate the field's type. $type = $field->getType(); if (is_array($type)) { $result = $this->validateMultipleTypes($value, $type, $field); } else { $result = $this->validateSingleType($value, $type, $field); } if (Invalid::isValid($result)) { $result = $this->validateEnum($result, $field); } } } else { $result = Invalid::value(); } } // Validate a custom field validator. if (Invalid::isValid($result)) { $this->callValidators($result, $field); } return $result; }
[ "protected", "function", "validateField", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "validated", "=", "false", ";", "$", "result", "=", "$", "value", "=", "$", "this", "->", "filterField", "(", "$", "value", ",", "$", "field", ",", "$", "validated", ")", ";", "if", "(", "$", "validated", ")", "{", "return", "$", "result", ";", "}", "elseif", "(", "$", "field", "->", "getField", "(", ")", "instanceof", "Schema", ")", "{", "try", "{", "$", "result", "=", "$", "field", "->", "getField", "(", ")", "->", "validate", "(", "$", "value", ",", "$", "field", "->", "getOptions", "(", ")", ")", ";", "}", "catch", "(", "ValidationException", "$", "ex", ")", "{", "// The validation failed, so merge the validations together.", "$", "field", "->", "getValidation", "(", ")", "->", "merge", "(", "$", "ex", "->", "getValidation", "(", ")", ",", "$", "field", "->", "getName", "(", ")", ")", ";", "}", "}", "elseif", "(", "(", "$", "value", "===", "null", "||", "(", "$", "value", "===", "''", "&&", "!", "$", "field", "->", "hasType", "(", "'string'", ")", ")", ")", "&&", "(", "$", "field", "->", "val", "(", "'nullable'", ")", "||", "$", "field", "->", "hasType", "(", "'null'", ")", ")", ")", "{", "$", "result", "=", "null", ";", "}", "else", "{", "// Look for a discriminator.", "if", "(", "!", "empty", "(", "$", "field", "->", "val", "(", "'discriminator'", ")", ")", ")", "{", "$", "field", "=", "$", "this", "->", "resolveDiscriminator", "(", "$", "value", ",", "$", "field", ")", ";", "}", "if", "(", "$", "field", "!==", "null", ")", "{", "if", "(", "$", "field", "->", "hasAllOf", "(", ")", ")", "{", "$", "result", "=", "$", "this", "->", "validateAllOf", "(", "$", "value", ",", "$", "field", ")", ";", "}", "else", "{", "// Validate the field's type.", "$", "type", "=", "$", "field", "->", "getType", "(", ")", ";", "if", "(", "is_array", "(", "$", "type", ")", ")", "{", "$", "result", "=", "$", "this", "->", "validateMultipleTypes", "(", "$", "value", ",", "$", "type", ",", "$", "field", ")", ";", "}", "else", "{", "$", "result", "=", "$", "this", "->", "validateSingleType", "(", "$", "value", ",", "$", "type", ",", "$", "field", ")", ";", "}", "if", "(", "Invalid", "::", "isValid", "(", "$", "result", ")", ")", "{", "$", "result", "=", "$", "this", "->", "validateEnum", "(", "$", "result", ",", "$", "field", ")", ";", "}", "}", "}", "else", "{", "$", "result", "=", "Invalid", "::", "value", "(", ")", ";", "}", "}", "// Validate a custom field validator.", "if", "(", "Invalid", "::", "isValid", "(", "$", "result", ")", ")", "{", "$", "this", "->", "callValidators", "(", "$", "result", ",", "$", "field", ")", ";", "}", "return", "$", "result", ";", "}" ]
Validate a field. @param mixed $value The value to validate. @param ValidationField $field A validation object to add errors to. @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value is completely invalid. @throws RefNotFoundException Throws an exception when a schema `$ref` is not found.
[ "Validate", "a", "field", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L952-L1000
train
vanilla/garden-schema
src/Schema.php
Schema.filterField
private function filterField($value, ValidationField $field, bool &$validated = false) { // Check for limited support for Open API style. if (!empty($field->val('style')) && is_string($value)) { $doFilter = true; if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) { $doFilter = false; } elseif (($field->hasType('integer') || $field->hasType('number')) && is_numeric($value)) { $doFilter = false; } if ($doFilter) { switch ($field->val('style')) { case 'form': $value = explode(',', $value); break; case 'spaceDelimited': $value = explode(' ', $value); break; case 'pipeDelimited': $value = explode('|', $value); break; } } } $value = $this->callFilters($value, $field, $validated); return $value; }
php
private function filterField($value, ValidationField $field, bool &$validated = false) { // Check for limited support for Open API style. if (!empty($field->val('style')) && is_string($value)) { $doFilter = true; if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) { $doFilter = false; } elseif (($field->hasType('integer') || $field->hasType('number')) && is_numeric($value)) { $doFilter = false; } if ($doFilter) { switch ($field->val('style')) { case 'form': $value = explode(',', $value); break; case 'spaceDelimited': $value = explode(' ', $value); break; case 'pipeDelimited': $value = explode('|', $value); break; } } } $value = $this->callFilters($value, $field, $validated); return $value; }
[ "private", "function", "filterField", "(", "$", "value", ",", "ValidationField", "$", "field", ",", "bool", "&", "$", "validated", "=", "false", ")", "{", "// Check for limited support for Open API style.", "if", "(", "!", "empty", "(", "$", "field", "->", "val", "(", "'style'", ")", ")", "&&", "is_string", "(", "$", "value", ")", ")", "{", "$", "doFilter", "=", "true", ";", "if", "(", "$", "field", "->", "hasType", "(", "'boolean'", ")", "&&", "in_array", "(", "$", "value", ",", "[", "'true'", ",", "'false'", ",", "'0'", ",", "'1'", "]", ",", "true", ")", ")", "{", "$", "doFilter", "=", "false", ";", "}", "elseif", "(", "(", "$", "field", "->", "hasType", "(", "'integer'", ")", "||", "$", "field", "->", "hasType", "(", "'number'", ")", ")", "&&", "is_numeric", "(", "$", "value", ")", ")", "{", "$", "doFilter", "=", "false", ";", "}", "if", "(", "$", "doFilter", ")", "{", "switch", "(", "$", "field", "->", "val", "(", "'style'", ")", ")", "{", "case", "'form'", ":", "$", "value", "=", "explode", "(", "','", ",", "$", "value", ")", ";", "break", ";", "case", "'spaceDelimited'", ":", "$", "value", "=", "explode", "(", "' '", ",", "$", "value", ")", ";", "break", ";", "case", "'pipeDelimited'", ":", "$", "value", "=", "explode", "(", "'|'", ",", "$", "value", ")", ";", "break", ";", "}", "}", "}", "$", "value", "=", "$", "this", "->", "callFilters", "(", "$", "value", ",", "$", "field", ",", "$", "validated", ")", ";", "return", "$", "value", ";", "}" ]
Filter a field's value using built in and custom filters. @param mixed $value The original value of the field. @param ValidationField $field The field information for the field. @param bool $validated Whether or not a filter validated the value. @return mixed Returns the filtered field or the original field value if there are no filters.
[ "Filter", "a", "field", "s", "value", "using", "built", "in", "and", "custom", "filters", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1010-L1038
train
vanilla/garden-schema
src/Schema.php
Schema.callFilters
private function callFilters($value, ValidationField $field, bool &$validated = false) { // Strip array references in the name except for the last one. $key = $field->getSchemaPath(); if (!empty($this->filters[$key])) { foreach ($this->filters[$key] as list($filter, $validate)) { $value = call_user_func($filter, $value, $field); $validated |= $validate; if (Invalid::isInvalid($value)) { return $value; } } } $key = '/format/'.$field->val('format'); if (!empty($this->filters[$key])) { foreach ($this->filters[$key] as list($filter, $validate)) { $value = call_user_func($filter, $value, $field); $validated |= $validate; if (Invalid::isInvalid($value)) { return $value; } } } return $value; }
php
private function callFilters($value, ValidationField $field, bool &$validated = false) { // Strip array references in the name except for the last one. $key = $field->getSchemaPath(); if (!empty($this->filters[$key])) { foreach ($this->filters[$key] as list($filter, $validate)) { $value = call_user_func($filter, $value, $field); $validated |= $validate; if (Invalid::isInvalid($value)) { return $value; } } } $key = '/format/'.$field->val('format'); if (!empty($this->filters[$key])) { foreach ($this->filters[$key] as list($filter, $validate)) { $value = call_user_func($filter, $value, $field); $validated |= $validate; if (Invalid::isInvalid($value)) { return $value; } } } return $value; }
[ "private", "function", "callFilters", "(", "$", "value", ",", "ValidationField", "$", "field", ",", "bool", "&", "$", "validated", "=", "false", ")", "{", "// Strip array references in the name except for the last one.", "$", "key", "=", "$", "field", "->", "getSchemaPath", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "filters", "[", "$", "key", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "filters", "[", "$", "key", "]", "as", "list", "(", "$", "filter", ",", "$", "validate", ")", ")", "{", "$", "value", "=", "call_user_func", "(", "$", "filter", ",", "$", "value", ",", "$", "field", ")", ";", "$", "validated", "|=", "$", "validate", ";", "if", "(", "Invalid", "::", "isInvalid", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "}", "}", "$", "key", "=", "'/format/'", ".", "$", "field", "->", "val", "(", "'format'", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "filters", "[", "$", "key", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "filters", "[", "$", "key", "]", "as", "list", "(", "$", "filter", ",", "$", "validate", ")", ")", "{", "$", "value", "=", "call_user_func", "(", "$", "filter", ",", "$", "value", ",", "$", "field", ")", ";", "$", "validated", "|=", "$", "validate", ";", "if", "(", "Invalid", "::", "isInvalid", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "}", "}", "return", "$", "value", ";", "}" ]
Call all of the filters attached to a field. @param mixed $value The field value being filtered. @param ValidationField $field The validation object. @param bool $validated Whether or not a filter validated the field. @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
[ "Call", "all", "of", "the", "filters", "attached", "to", "a", "field", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1048-L1074
train
vanilla/garden-schema
src/Schema.php
Schema.validateMultipleTypes
private function validateMultipleTypes($value, array $types, ValidationField $field) { trigger_error('Multiple schema types are deprecated.', E_USER_DEPRECATED); // First check for an exact type match. switch (gettype($value)) { case 'boolean': if (in_array('boolean', $types)) { $singleType = 'boolean'; } break; case 'integer': if (in_array('integer', $types)) { $singleType = 'integer'; } elseif (in_array('number', $types)) { $singleType = 'number'; } break; case 'double': if (in_array('number', $types)) { $singleType = 'number'; } elseif (in_array('integer', $types)) { $singleType = 'integer'; } break; case 'string': if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) { $singleType = 'datetime'; } elseif (in_array('string', $types)) { $singleType = 'string'; } break; case 'array': if (in_array('array', $types) && in_array('object', $types)) { $singleType = isset($value[0]) || empty($value) ? 'array' : 'object'; } elseif (in_array('object', $types)) { $singleType = 'object'; } elseif (in_array('array', $types)) { $singleType = 'array'; } break; case 'NULL': if (in_array('null', $types)) { $singleType = $this->validateSingleType($value, 'null', $field); } break; } if (!empty($singleType)) { return $this->validateSingleType($value, $singleType, $field); } // Clone the validation field to collect errors. $typeValidation = new ValidationField(new Validation(), $field->getField(), '', '', $field->getOptions()); // Try and validate against each type. foreach ($types as $type) { $result = $this->validateSingleType($value, $type, $typeValidation); if (Invalid::isValid($result)) { return $result; } } // Since we got here the value is invalid. $field->merge($typeValidation->getValidation()); return Invalid::value(); }
php
private function validateMultipleTypes($value, array $types, ValidationField $field) { trigger_error('Multiple schema types are deprecated.', E_USER_DEPRECATED); // First check for an exact type match. switch (gettype($value)) { case 'boolean': if (in_array('boolean', $types)) { $singleType = 'boolean'; } break; case 'integer': if (in_array('integer', $types)) { $singleType = 'integer'; } elseif (in_array('number', $types)) { $singleType = 'number'; } break; case 'double': if (in_array('number', $types)) { $singleType = 'number'; } elseif (in_array('integer', $types)) { $singleType = 'integer'; } break; case 'string': if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) { $singleType = 'datetime'; } elseif (in_array('string', $types)) { $singleType = 'string'; } break; case 'array': if (in_array('array', $types) && in_array('object', $types)) { $singleType = isset($value[0]) || empty($value) ? 'array' : 'object'; } elseif (in_array('object', $types)) { $singleType = 'object'; } elseif (in_array('array', $types)) { $singleType = 'array'; } break; case 'NULL': if (in_array('null', $types)) { $singleType = $this->validateSingleType($value, 'null', $field); } break; } if (!empty($singleType)) { return $this->validateSingleType($value, $singleType, $field); } // Clone the validation field to collect errors. $typeValidation = new ValidationField(new Validation(), $field->getField(), '', '', $field->getOptions()); // Try and validate against each type. foreach ($types as $type) { $result = $this->validateSingleType($value, $type, $typeValidation); if (Invalid::isValid($result)) { return $result; } } // Since we got here the value is invalid. $field->merge($typeValidation->getValidation()); return Invalid::value(); }
[ "private", "function", "validateMultipleTypes", "(", "$", "value", ",", "array", "$", "types", ",", "ValidationField", "$", "field", ")", "{", "trigger_error", "(", "'Multiple schema types are deprecated.'", ",", "E_USER_DEPRECATED", ")", ";", "// First check for an exact type match.", "switch", "(", "gettype", "(", "$", "value", ")", ")", "{", "case", "'boolean'", ":", "if", "(", "in_array", "(", "'boolean'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'boolean'", ";", "}", "break", ";", "case", "'integer'", ":", "if", "(", "in_array", "(", "'integer'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'integer'", ";", "}", "elseif", "(", "in_array", "(", "'number'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'number'", ";", "}", "break", ";", "case", "'double'", ":", "if", "(", "in_array", "(", "'number'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'number'", ";", "}", "elseif", "(", "in_array", "(", "'integer'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'integer'", ";", "}", "break", ";", "case", "'string'", ":", "if", "(", "in_array", "(", "'datetime'", ",", "$", "types", ")", "&&", "preg_match", "(", "self", "::", "$", "DATE_REGEX", ",", "$", "value", ")", ")", "{", "$", "singleType", "=", "'datetime'", ";", "}", "elseif", "(", "in_array", "(", "'string'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'string'", ";", "}", "break", ";", "case", "'array'", ":", "if", "(", "in_array", "(", "'array'", ",", "$", "types", ")", "&&", "in_array", "(", "'object'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "isset", "(", "$", "value", "[", "0", "]", ")", "||", "empty", "(", "$", "value", ")", "?", "'array'", ":", "'object'", ";", "}", "elseif", "(", "in_array", "(", "'object'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'object'", ";", "}", "elseif", "(", "in_array", "(", "'array'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "'array'", ";", "}", "break", ";", "case", "'NULL'", ":", "if", "(", "in_array", "(", "'null'", ",", "$", "types", ")", ")", "{", "$", "singleType", "=", "$", "this", "->", "validateSingleType", "(", "$", "value", ",", "'null'", ",", "$", "field", ")", ";", "}", "break", ";", "}", "if", "(", "!", "empty", "(", "$", "singleType", ")", ")", "{", "return", "$", "this", "->", "validateSingleType", "(", "$", "value", ",", "$", "singleType", ",", "$", "field", ")", ";", "}", "// Clone the validation field to collect errors.", "$", "typeValidation", "=", "new", "ValidationField", "(", "new", "Validation", "(", ")", ",", "$", "field", "->", "getField", "(", ")", ",", "''", ",", "''", ",", "$", "field", "->", "getOptions", "(", ")", ")", ";", "// Try and validate against each type.", "foreach", "(", "$", "types", "as", "$", "type", ")", "{", "$", "result", "=", "$", "this", "->", "validateSingleType", "(", "$", "value", ",", "$", "type", ",", "$", "typeValidation", ")", ";", "if", "(", "Invalid", "::", "isValid", "(", "$", "result", ")", ")", "{", "return", "$", "result", ";", "}", "}", "// Since we got here the value is invalid.", "$", "field", "->", "merge", "(", "$", "typeValidation", "->", "getValidation", "(", ")", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}" ]
Validate a field against multiple basic types. The first validation that passes will be returned. If no type can be validated against then validation will fail. @param mixed $value The value to validate. @param string[] $types The types to validate against. @param ValidationField $field Contains field and validation information. @return mixed Returns the valid value or `Invalid`. @throws RefNotFoundException Throws an exception when a schema `$ref` is not found. @deprecated Multiple types are being removed next version.
[ "Validate", "a", "field", "against", "multiple", "basic", "types", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1088-L1152
train
vanilla/garden-schema
src/Schema.php
Schema.validateSingleType
protected function validateSingleType($value, string $type, ValidationField $field) { switch ($type) { case 'boolean': $result = $this->validateBoolean($value, $field); break; case 'integer': $result = $this->validateInteger($value, $field); break; case 'number': $result = $this->validateNumber($value, $field); break; case 'string': $result = $this->validateString($value, $field); break; case 'timestamp': trigger_error('The timestamp type is deprecated. Use an integer with a format of timestamp instead.', E_USER_DEPRECATED); $result = $this->validateTimestamp($value, $field); break; case 'datetime': trigger_error('The datetime type is deprecated. Use a string with a format of date-time instead.', E_USER_DEPRECATED); $result = $this->validateDatetime($value, $field); break; case 'array': $result = $this->validateArray($value, $field); break; case 'object': $result = $this->validateObject($value, $field); break; case 'null': $result = $this->validateNull($value, $field); break; case '': // No type was specified so we are valid. $result = $value; break; default: throw new \InvalidArgumentException("Unrecognized type $type.", 500); } return $result; }
php
protected function validateSingleType($value, string $type, ValidationField $field) { switch ($type) { case 'boolean': $result = $this->validateBoolean($value, $field); break; case 'integer': $result = $this->validateInteger($value, $field); break; case 'number': $result = $this->validateNumber($value, $field); break; case 'string': $result = $this->validateString($value, $field); break; case 'timestamp': trigger_error('The timestamp type is deprecated. Use an integer with a format of timestamp instead.', E_USER_DEPRECATED); $result = $this->validateTimestamp($value, $field); break; case 'datetime': trigger_error('The datetime type is deprecated. Use a string with a format of date-time instead.', E_USER_DEPRECATED); $result = $this->validateDatetime($value, $field); break; case 'array': $result = $this->validateArray($value, $field); break; case 'object': $result = $this->validateObject($value, $field); break; case 'null': $result = $this->validateNull($value, $field); break; case '': // No type was specified so we are valid. $result = $value; break; default: throw new \InvalidArgumentException("Unrecognized type $type.", 500); } return $result; }
[ "protected", "function", "validateSingleType", "(", "$", "value", ",", "string", "$", "type", ",", "ValidationField", "$", "field", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "'boolean'", ":", "$", "result", "=", "$", "this", "->", "validateBoolean", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'integer'", ":", "$", "result", "=", "$", "this", "->", "validateInteger", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'number'", ":", "$", "result", "=", "$", "this", "->", "validateNumber", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'string'", ":", "$", "result", "=", "$", "this", "->", "validateString", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'timestamp'", ":", "trigger_error", "(", "'The timestamp type is deprecated. Use an integer with a format of timestamp instead.'", ",", "E_USER_DEPRECATED", ")", ";", "$", "result", "=", "$", "this", "->", "validateTimestamp", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'datetime'", ":", "trigger_error", "(", "'The datetime type is deprecated. Use a string with a format of date-time instead.'", ",", "E_USER_DEPRECATED", ")", ";", "$", "result", "=", "$", "this", "->", "validateDatetime", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'array'", ":", "$", "result", "=", "$", "this", "->", "validateArray", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'object'", ":", "$", "result", "=", "$", "this", "->", "validateObject", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "'null'", ":", "$", "result", "=", "$", "this", "->", "validateNull", "(", "$", "value", ",", "$", "field", ")", ";", "break", ";", "case", "''", ":", "// No type was specified so we are valid.", "$", "result", "=", "$", "value", ";", "break", ";", "default", ":", "throw", "new", "\\", "InvalidArgumentException", "(", "\"Unrecognized type $type.\"", ",", "500", ")", ";", "}", "return", "$", "result", ";", "}" ]
Validate a field against a single type. @param mixed $value The value to validate. @param string $type The type to validate against. @param ValidationField $field Contains field and validation information. @return mixed Returns the valid value or `Invalid`. @throws \InvalidArgumentException Throws an exception when `$type` is not recognized. @throws RefNotFoundException Throws an exception when internal validation has a reference that isn't found.
[ "Validate", "a", "field", "against", "a", "single", "type", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1164-L1203
train
vanilla/garden-schema
src/Schema.php
Schema.validateBoolean
protected function validateBoolean($value, ValidationField $field) { $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($value === null) { $field->addTypeError($value, 'boolean'); return Invalid::value(); } return $value; }
php
protected function validateBoolean($value, ValidationField $field) { $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($value === null) { $field->addTypeError($value, 'boolean'); return Invalid::value(); } return $value; }
[ "protected", "function", "validateBoolean", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "value", "=", "$", "value", "===", "null", "?", "$", "value", ":", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ";", "if", "(", "$", "value", "===", "null", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'boolean'", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "return", "$", "value", ";", "}" ]
Validate a boolean value. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return bool|Invalid Returns the cleaned value or invalid if validation fails.
[ "Validate", "a", "boolean", "value", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1212-L1220
train
vanilla/garden-schema
src/Schema.php
Schema.validateInteger
protected function validateInteger($value, ValidationField $field) { if ($field->val('format') === 'timestamp') { return $this->validateTimestamp($value, $field); } $result = filter_var($value, FILTER_VALIDATE_INT); if ($result === false) { $field->addTypeError($value, 'integer'); return Invalid::value(); } $result = $this->validateNumberProperties($result, $field); return $result; }
php
protected function validateInteger($value, ValidationField $field) { if ($field->val('format') === 'timestamp') { return $this->validateTimestamp($value, $field); } $result = filter_var($value, FILTER_VALIDATE_INT); if ($result === false) { $field->addTypeError($value, 'integer'); return Invalid::value(); } $result = $this->validateNumberProperties($result, $field); return $result; }
[ "protected", "function", "validateInteger", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "$", "field", "->", "val", "(", "'format'", ")", "===", "'timestamp'", ")", "{", "return", "$", "this", "->", "validateTimestamp", "(", "$", "value", ",", "$", "field", ")", ";", "}", "$", "result", "=", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_INT", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'integer'", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "$", "result", "=", "$", "this", "->", "validateNumberProperties", "(", "$", "result", ",", "$", "field", ")", ";", "return", "$", "result", ";", "}" ]
Validate and integer. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return int|Invalid Returns the cleaned value or **null** if validation fails.
[ "Validate", "and", "integer", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1229-L1244
train
vanilla/garden-schema
src/Schema.php
Schema.validateTimestamp
protected function validateTimestamp($value, ValidationField $field) { if (is_numeric($value) && $value > 0) { $result = (int)$value; } elseif (is_string($value) && $ts = strtotime($value)) { $result = $ts; } else { $field->addTypeError($value, 'timestamp'); $result = Invalid::value(); } return $result; }
php
protected function validateTimestamp($value, ValidationField $field) { if (is_numeric($value) && $value > 0) { $result = (int)$value; } elseif (is_string($value) && $ts = strtotime($value)) { $result = $ts; } else { $field->addTypeError($value, 'timestamp'); $result = Invalid::value(); } return $result; }
[ "protected", "function", "validateTimestamp", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "is_numeric", "(", "$", "value", ")", "&&", "$", "value", ">", "0", ")", "{", "$", "result", "=", "(", "int", ")", "$", "value", ";", "}", "elseif", "(", "is_string", "(", "$", "value", ")", "&&", "$", "ts", "=", "strtotime", "(", "$", "value", ")", ")", "{", "$", "result", "=", "$", "ts", ";", "}", "else", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'timestamp'", ")", ";", "$", "result", "=", "Invalid", "::", "value", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Validate a unix timestamp. @param mixed $value The value to validate. @param ValidationField $field The field being validated. @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
[ "Validate", "a", "unix", "timestamp", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1253-L1263
train
vanilla/garden-schema
src/Schema.php
Schema.validateNumberProperties
private function validateNumberProperties($value, ValidationField $field) { $count = $field->getErrorCount(); if ($multipleOf = $field->val('multipleOf')) { $divided = $value / $multipleOf; if ($divided != round($divided)) { $field->addError('multipleOf', ['messageCode' => 'The value must be a multiple of {multipleOf}.', 'multipleOf' => $multipleOf]); } } if ($maximum = $field->val('maximum')) { $exclusive = $field->val('exclusiveMaximum'); if ($value > $maximum || ($exclusive && $value == $maximum)) { if ($exclusive) { $field->addError('maximum', ['messageCode' => 'The value must be less than {maximum}.', 'maximum' => $maximum]); } else { $field->addError('maximum', ['messageCode' => 'The value must be less than or equal to {maximum}.', 'maximum' => $maximum]); } } } if ($minimum = $field->val('minimum')) { $exclusive = $field->val('exclusiveMinimum'); if ($value < $minimum || ($exclusive && $value == $minimum)) { if ($exclusive) { $field->addError('minimum', ['messageCode' => 'The value must be greater than {minimum}.', 'minimum' => $minimum]); } else { $field->addError('minimum', ['messageCode' => 'The value must be greater than or equal to {minimum}.', 'minimum' => $minimum]); } } } return $field->getErrorCount() === $count ? $value : Invalid::value(); }
php
private function validateNumberProperties($value, ValidationField $field) { $count = $field->getErrorCount(); if ($multipleOf = $field->val('multipleOf')) { $divided = $value / $multipleOf; if ($divided != round($divided)) { $field->addError('multipleOf', ['messageCode' => 'The value must be a multiple of {multipleOf}.', 'multipleOf' => $multipleOf]); } } if ($maximum = $field->val('maximum')) { $exclusive = $field->val('exclusiveMaximum'); if ($value > $maximum || ($exclusive && $value == $maximum)) { if ($exclusive) { $field->addError('maximum', ['messageCode' => 'The value must be less than {maximum}.', 'maximum' => $maximum]); } else { $field->addError('maximum', ['messageCode' => 'The value must be less than or equal to {maximum}.', 'maximum' => $maximum]); } } } if ($minimum = $field->val('minimum')) { $exclusive = $field->val('exclusiveMinimum'); if ($value < $minimum || ($exclusive && $value == $minimum)) { if ($exclusive) { $field->addError('minimum', ['messageCode' => 'The value must be greater than {minimum}.', 'minimum' => $minimum]); } else { $field->addError('minimum', ['messageCode' => 'The value must be greater than or equal to {minimum}.', 'minimum' => $minimum]); } } } return $field->getErrorCount() === $count ? $value : Invalid::value(); }
[ "private", "function", "validateNumberProperties", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "count", "=", "$", "field", "->", "getErrorCount", "(", ")", ";", "if", "(", "$", "multipleOf", "=", "$", "field", "->", "val", "(", "'multipleOf'", ")", ")", "{", "$", "divided", "=", "$", "value", "/", "$", "multipleOf", ";", "if", "(", "$", "divided", "!=", "round", "(", "$", "divided", ")", ")", "{", "$", "field", "->", "addError", "(", "'multipleOf'", ",", "[", "'messageCode'", "=>", "'The value must be a multiple of {multipleOf}.'", ",", "'multipleOf'", "=>", "$", "multipleOf", "]", ")", ";", "}", "}", "if", "(", "$", "maximum", "=", "$", "field", "->", "val", "(", "'maximum'", ")", ")", "{", "$", "exclusive", "=", "$", "field", "->", "val", "(", "'exclusiveMaximum'", ")", ";", "if", "(", "$", "value", ">", "$", "maximum", "||", "(", "$", "exclusive", "&&", "$", "value", "==", "$", "maximum", ")", ")", "{", "if", "(", "$", "exclusive", ")", "{", "$", "field", "->", "addError", "(", "'maximum'", ",", "[", "'messageCode'", "=>", "'The value must be less than {maximum}.'", ",", "'maximum'", "=>", "$", "maximum", "]", ")", ";", "}", "else", "{", "$", "field", "->", "addError", "(", "'maximum'", ",", "[", "'messageCode'", "=>", "'The value must be less than or equal to {maximum}.'", ",", "'maximum'", "=>", "$", "maximum", "]", ")", ";", "}", "}", "}", "if", "(", "$", "minimum", "=", "$", "field", "->", "val", "(", "'minimum'", ")", ")", "{", "$", "exclusive", "=", "$", "field", "->", "val", "(", "'exclusiveMinimum'", ")", ";", "if", "(", "$", "value", "<", "$", "minimum", "||", "(", "$", "exclusive", "&&", "$", "value", "==", "$", "minimum", ")", ")", "{", "if", "(", "$", "exclusive", ")", "{", "$", "field", "->", "addError", "(", "'minimum'", ",", "[", "'messageCode'", "=>", "'The value must be greater than {minimum}.'", ",", "'minimum'", "=>", "$", "minimum", "]", ")", ";", "}", "else", "{", "$", "field", "->", "addError", "(", "'minimum'", ",", "[", "'messageCode'", "=>", "'The value must be greater than or equal to {minimum}.'", ",", "'minimum'", "=>", "$", "minimum", "]", ")", ";", "}", "}", "}", "return", "$", "field", "->", "getErrorCount", "(", ")", "===", "$", "count", "?", "$", "value", ":", "Invalid", "::", "value", "(", ")", ";", "}" ]
Validate specific numeric validation properties. @param int|float $value The value to test. @param ValidationField $field Field information. @return int|float|Invalid Returns the number of invalid.
[ "Validate", "specific", "numeric", "validation", "properties", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1272-L1308
train
vanilla/garden-schema
src/Schema.php
Schema.validateNumber
protected function validateNumber($value, ValidationField $field) { $result = filter_var($value, FILTER_VALIDATE_FLOAT); if ($result === false) { $field->addTypeError($value, 'number'); return Invalid::value(); } $result = $this->validateNumberProperties($result, $field); return $result; }
php
protected function validateNumber($value, ValidationField $field) { $result = filter_var($value, FILTER_VALIDATE_FLOAT); if ($result === false) { $field->addTypeError($value, 'number'); return Invalid::value(); } $result = $this->validateNumberProperties($result, $field); return $result; }
[ "protected", "function", "validateNumber", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "result", "=", "filter_var", "(", "$", "value", ",", "FILTER_VALIDATE_FLOAT", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'number'", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "$", "result", "=", "$", "this", "->", "validateNumberProperties", "(", "$", "result", ",", "$", "field", ")", ";", "return", "$", "result", ";", "}" ]
Validate a float. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return float|Invalid Returns a number or **null** if validation fails.
[ "Validate", "a", "float", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1317-L1327
train
vanilla/garden-schema
src/Schema.php
Schema.validateDatetime
protected function validateDatetime($value, ValidationField $field) { if ($value instanceof \DateTimeInterface) { // do nothing, we're good } elseif (is_string($value) && $value !== '' && !is_numeric($value)) { try { $dt = new \DateTimeImmutable($value); if ($dt) { $value = $dt; } else { $value = null; } } catch (\Throwable $ex) { $value = Invalid::value(); } } elseif (is_int($value) && $value > 0) { try { $value = new \DateTimeImmutable('@'.(string)round($value)); } catch (\Throwable $ex) { $value = Invalid::value(); } } else { $value = Invalid::value(); } if (Invalid::isInvalid($value)) { $field->addTypeError($value, 'date/time'); } return $value; }
php
protected function validateDatetime($value, ValidationField $field) { if ($value instanceof \DateTimeInterface) { // do nothing, we're good } elseif (is_string($value) && $value !== '' && !is_numeric($value)) { try { $dt = new \DateTimeImmutable($value); if ($dt) { $value = $dt; } else { $value = null; } } catch (\Throwable $ex) { $value = Invalid::value(); } } elseif (is_int($value) && $value > 0) { try { $value = new \DateTimeImmutable('@'.(string)round($value)); } catch (\Throwable $ex) { $value = Invalid::value(); } } else { $value = Invalid::value(); } if (Invalid::isInvalid($value)) { $field->addTypeError($value, 'date/time'); } return $value; }
[ "protected", "function", "validateDatetime", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "$", "value", "instanceof", "\\", "DateTimeInterface", ")", "{", "// do nothing, we're good", "}", "elseif", "(", "is_string", "(", "$", "value", ")", "&&", "$", "value", "!==", "''", "&&", "!", "is_numeric", "(", "$", "value", ")", ")", "{", "try", "{", "$", "dt", "=", "new", "\\", "DateTimeImmutable", "(", "$", "value", ")", ";", "if", "(", "$", "dt", ")", "{", "$", "value", "=", "$", "dt", ";", "}", "else", "{", "$", "value", "=", "null", ";", "}", "}", "catch", "(", "\\", "Throwable", "$", "ex", ")", "{", "$", "value", "=", "Invalid", "::", "value", "(", ")", ";", "}", "}", "elseif", "(", "is_int", "(", "$", "value", ")", "&&", "$", "value", ">", "0", ")", "{", "try", "{", "$", "value", "=", "new", "\\", "DateTimeImmutable", "(", "'@'", ".", "(", "string", ")", "round", "(", "$", "value", ")", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "ex", ")", "{", "$", "value", "=", "Invalid", "::", "value", "(", ")", ";", "}", "}", "else", "{", "$", "value", "=", "Invalid", "::", "value", "(", ")", ";", "}", "if", "(", "Invalid", "::", "isInvalid", "(", "$", "value", ")", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'date/time'", ")", ";", "}", "return", "$", "value", ";", "}" ]
Validate a date time. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
[ "Validate", "a", "date", "time", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1436-L1464
train
vanilla/garden-schema
src/Schema.php
Schema.resolveAllOfTree
private function resolveAllOfTree(ValidationField $field) { $result = []; foreach($field->getAllOf() as $allof) { if (!is_array($allof) || empty($allof)) { throw new ParseException("Invalid allof member in {$field->getSchemaPath()}, array expected", 500); } list ($items, $schemaPath) = $this->lookupSchema($allof, $field->getSchemaPath()); $allOfValidation = new ValidationField( $field->getValidation(), $items, '', $schemaPath, $field->getOptions() ); if($allOfValidation->hasAllOf()) { $result = array_replace_recursive($result, $this->resolveAllOfTree($allOfValidation)); } else { $result = array_replace_recursive($result, $items); } } return $result; }
php
private function resolveAllOfTree(ValidationField $field) { $result = []; foreach($field->getAllOf() as $allof) { if (!is_array($allof) || empty($allof)) { throw new ParseException("Invalid allof member in {$field->getSchemaPath()}, array expected", 500); } list ($items, $schemaPath) = $this->lookupSchema($allof, $field->getSchemaPath()); $allOfValidation = new ValidationField( $field->getValidation(), $items, '', $schemaPath, $field->getOptions() ); if($allOfValidation->hasAllOf()) { $result = array_replace_recursive($result, $this->resolveAllOfTree($allOfValidation)); } else { $result = array_replace_recursive($result, $items); } } return $result; }
[ "private", "function", "resolveAllOfTree", "(", "ValidationField", "$", "field", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "field", "->", "getAllOf", "(", ")", "as", "$", "allof", ")", "{", "if", "(", "!", "is_array", "(", "$", "allof", ")", "||", "empty", "(", "$", "allof", ")", ")", "{", "throw", "new", "ParseException", "(", "\"Invalid allof member in {$field->getSchemaPath()}, array expected\"", ",", "500", ")", ";", "}", "list", "(", "$", "items", ",", "$", "schemaPath", ")", "=", "$", "this", "->", "lookupSchema", "(", "$", "allof", ",", "$", "field", "->", "getSchemaPath", "(", ")", ")", ";", "$", "allOfValidation", "=", "new", "ValidationField", "(", "$", "field", "->", "getValidation", "(", ")", ",", "$", "items", ",", "''", ",", "$", "schemaPath", ",", "$", "field", "->", "getOptions", "(", ")", ")", ";", "if", "(", "$", "allOfValidation", "->", "hasAllOf", "(", ")", ")", "{", "$", "result", "=", "array_replace_recursive", "(", "$", "result", ",", "$", "this", "->", "resolveAllOfTree", "(", "$", "allOfValidation", ")", ")", ";", "}", "else", "{", "$", "result", "=", "array_replace_recursive", "(", "$", "result", ",", "$", "items", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Recursively resolve allOf inheritance tree and return a merged resource specification @param ValidationField $field The validation results to add. @return array Returns an array of merged specs. @throws ParseException Throws an exception if an invalid allof member is provided @throws RefNotFoundException Throws an exception if the array has an items `$ref` that cannot be found.
[ "Recursively", "resolve", "allOf", "inheritance", "tree", "and", "return", "a", "merged", "resource", "specification" ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1474-L1500
train
vanilla/garden-schema
src/Schema.php
Schema.validateAllOf
private function validateAllOf($value, ValidationField $field) { $allOfValidation = new ValidationField( $field->getValidation(), $this->resolveAllOfTree($field), '', $field->getSchemaPath(), $field->getOptions() ); return $this->validateField($value, $allOfValidation); }
php
private function validateAllOf($value, ValidationField $field) { $allOfValidation = new ValidationField( $field->getValidation(), $this->resolveAllOfTree($field), '', $field->getSchemaPath(), $field->getOptions() ); return $this->validateField($value, $allOfValidation); }
[ "private", "function", "validateAllOf", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "allOfValidation", "=", "new", "ValidationField", "(", "$", "field", "->", "getValidation", "(", ")", ",", "$", "this", "->", "resolveAllOfTree", "(", "$", "field", ")", ",", "''", ",", "$", "field", "->", "getSchemaPath", "(", ")", ",", "$", "field", "->", "getOptions", "(", ")", ")", ";", "return", "$", "this", "->", "validateField", "(", "$", "value", ",", "$", "allOfValidation", ")", ";", "}" ]
Validate allof tree @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return array|Invalid Returns an array or invalid if validation fails. @throws RefNotFoundException Throws an exception if the array has an items `$ref` that cannot be found.
[ "Validate", "allof", "tree" ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1510-L1520
train
vanilla/garden-schema
src/Schema.php
Schema.validateArray
protected function validateArray($value, ValidationField $field) { if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) { $field->addTypeError($value, 'array'); return Invalid::value(); } else { if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) { $field->addError( 'minItems', [ 'messageCode' => 'This must contain at least {minItems} {minItems,plural,item,items}.', 'minItems' => $minItems, ] ); } if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) { $field->addError( 'maxItems', [ 'messageCode' => 'This must contain no more than {maxItems} {maxItems,plural,item,items}.', 'maxItems' => $maxItems, ] ); } if ($field->val('uniqueItems') && count($value) > count(array_unique($value))) { $field->addError( 'uniqueItems', [ 'messageCode' => 'The array must contain unique items.', ] ); } if ($field->val('items') !== null) { list ($items, $schemaPath) = $this->lookupSchema($field->val('items'), $field->getSchemaPath().'/items'); // Validate each of the types. $itemValidation = new ValidationField( $field->getValidation(), $items, '', $schemaPath, $field->getOptions() ); $result = []; $count = 0; foreach ($value as $i => $item) { $itemValidation->setName($field->getName()."/$i"); $validItem = $this->validateField($item, $itemValidation); if (Invalid::isValid($validItem)) { $result[] = $validItem; } $count++; } return empty($result) && $count > 0 ? Invalid::value() : $result; } else { // Cast the items into a proper numeric array. $result = is_array($value) ? array_values($value) : iterator_to_array($value); return $result; } } }
php
protected function validateArray($value, ValidationField $field) { if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) { $field->addTypeError($value, 'array'); return Invalid::value(); } else { if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) { $field->addError( 'minItems', [ 'messageCode' => 'This must contain at least {minItems} {minItems,plural,item,items}.', 'minItems' => $minItems, ] ); } if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) { $field->addError( 'maxItems', [ 'messageCode' => 'This must contain no more than {maxItems} {maxItems,plural,item,items}.', 'maxItems' => $maxItems, ] ); } if ($field->val('uniqueItems') && count($value) > count(array_unique($value))) { $field->addError( 'uniqueItems', [ 'messageCode' => 'The array must contain unique items.', ] ); } if ($field->val('items') !== null) { list ($items, $schemaPath) = $this->lookupSchema($field->val('items'), $field->getSchemaPath().'/items'); // Validate each of the types. $itemValidation = new ValidationField( $field->getValidation(), $items, '', $schemaPath, $field->getOptions() ); $result = []; $count = 0; foreach ($value as $i => $item) { $itemValidation->setName($field->getName()."/$i"); $validItem = $this->validateField($item, $itemValidation); if (Invalid::isValid($validItem)) { $result[] = $validItem; } $count++; } return empty($result) && $count > 0 ? Invalid::value() : $result; } else { // Cast the items into a proper numeric array. $result = is_array($value) ? array_values($value) : iterator_to_array($value); return $result; } } }
[ "protected", "function", "validateArray", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "(", "!", "is_array", "(", "$", "value", ")", "||", "(", "count", "(", "$", "value", ")", ">", "0", "&&", "!", "array_key_exists", "(", "0", ",", "$", "value", ")", ")", ")", "&&", "!", "$", "value", "instanceof", "\\", "Traversable", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'array'", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "else", "{", "if", "(", "(", "null", "!==", "$", "minItems", "=", "$", "field", "->", "val", "(", "'minItems'", ")", ")", "&&", "count", "(", "$", "value", ")", "<", "$", "minItems", ")", "{", "$", "field", "->", "addError", "(", "'minItems'", ",", "[", "'messageCode'", "=>", "'This must contain at least {minItems} {minItems,plural,item,items}.'", ",", "'minItems'", "=>", "$", "minItems", ",", "]", ")", ";", "}", "if", "(", "(", "null", "!==", "$", "maxItems", "=", "$", "field", "->", "val", "(", "'maxItems'", ")", ")", "&&", "count", "(", "$", "value", ")", ">", "$", "maxItems", ")", "{", "$", "field", "->", "addError", "(", "'maxItems'", ",", "[", "'messageCode'", "=>", "'This must contain no more than {maxItems} {maxItems,plural,item,items}.'", ",", "'maxItems'", "=>", "$", "maxItems", ",", "]", ")", ";", "}", "if", "(", "$", "field", "->", "val", "(", "'uniqueItems'", ")", "&&", "count", "(", "$", "value", ")", ">", "count", "(", "array_unique", "(", "$", "value", ")", ")", ")", "{", "$", "field", "->", "addError", "(", "'uniqueItems'", ",", "[", "'messageCode'", "=>", "'The array must contain unique items.'", ",", "]", ")", ";", "}", "if", "(", "$", "field", "->", "val", "(", "'items'", ")", "!==", "null", ")", "{", "list", "(", "$", "items", ",", "$", "schemaPath", ")", "=", "$", "this", "->", "lookupSchema", "(", "$", "field", "->", "val", "(", "'items'", ")", ",", "$", "field", "->", "getSchemaPath", "(", ")", ".", "'/items'", ")", ";", "// Validate each of the types.", "$", "itemValidation", "=", "new", "ValidationField", "(", "$", "field", "->", "getValidation", "(", ")", ",", "$", "items", ",", "''", ",", "$", "schemaPath", ",", "$", "field", "->", "getOptions", "(", ")", ")", ";", "$", "result", "=", "[", "]", ";", "$", "count", "=", "0", ";", "foreach", "(", "$", "value", "as", "$", "i", "=>", "$", "item", ")", "{", "$", "itemValidation", "->", "setName", "(", "$", "field", "->", "getName", "(", ")", ".", "\"/$i\"", ")", ";", "$", "validItem", "=", "$", "this", "->", "validateField", "(", "$", "item", ",", "$", "itemValidation", ")", ";", "if", "(", "Invalid", "::", "isValid", "(", "$", "validItem", ")", ")", "{", "$", "result", "[", "]", "=", "$", "validItem", ";", "}", "$", "count", "++", ";", "}", "return", "empty", "(", "$", "result", ")", "&&", "$", "count", ">", "0", "?", "Invalid", "::", "value", "(", ")", ":", "$", "result", ";", "}", "else", "{", "// Cast the items into a proper numeric array.", "$", "result", "=", "is_array", "(", "$", "value", ")", "?", "array_values", "(", "$", "value", ")", ":", "iterator_to_array", "(", "$", "value", ")", ";", "return", "$", "result", ";", "}", "}", "}" ]
Validate an array. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return array|Invalid Returns an array or invalid if validation fails. @throws RefNotFoundException Throws an exception if the array has an items `$ref` that cannot be found.
[ "Validate", "an", "array", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1530-L1593
train
vanilla/garden-schema
src/Schema.php
Schema.validateObject
protected function validateObject($value, ValidationField $field) { if (!$this->isArray($value) || isset($value[0])) { $field->addTypeError($value, 'object'); return Invalid::value(); } elseif (is_array($field->val('properties')) || null !== $field->val('additionalProperties')) { // Validate the data against the internal schema. $value = $this->validateProperties($value, $field); } elseif (!is_array($value)) { $value = $this->toObjectArray($value); } if (($maxProperties = $field->val('maxProperties')) && count($value) > $maxProperties) { $field->addError( 'maxProperties', [ 'messageCode' => 'This must contain no more than {maxProperties} {maxProperties,plural,item,items}.', 'maxItems' => $maxProperties, ] ); } if (($minProperties = $field->val('minProperties')) && count($value) < $minProperties) { $field->addError( 'minProperties', [ 'messageCode' => 'This must contain at least {minProperties} {minProperties,plural,item,items}.', 'minItems' => $minProperties, ] ); } return $value; }
php
protected function validateObject($value, ValidationField $field) { if (!$this->isArray($value) || isset($value[0])) { $field->addTypeError($value, 'object'); return Invalid::value(); } elseif (is_array($field->val('properties')) || null !== $field->val('additionalProperties')) { // Validate the data against the internal schema. $value = $this->validateProperties($value, $field); } elseif (!is_array($value)) { $value = $this->toObjectArray($value); } if (($maxProperties = $field->val('maxProperties')) && count($value) > $maxProperties) { $field->addError( 'maxProperties', [ 'messageCode' => 'This must contain no more than {maxProperties} {maxProperties,plural,item,items}.', 'maxItems' => $maxProperties, ] ); } if (($minProperties = $field->val('minProperties')) && count($value) < $minProperties) { $field->addError( 'minProperties', [ 'messageCode' => 'This must contain at least {minProperties} {minProperties,plural,item,items}.', 'minItems' => $minProperties, ] ); } return $value; }
[ "protected", "function", "validateObject", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "!", "$", "this", "->", "isArray", "(", "$", "value", ")", "||", "isset", "(", "$", "value", "[", "0", "]", ")", ")", "{", "$", "field", "->", "addTypeError", "(", "$", "value", ",", "'object'", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "elseif", "(", "is_array", "(", "$", "field", "->", "val", "(", "'properties'", ")", ")", "||", "null", "!==", "$", "field", "->", "val", "(", "'additionalProperties'", ")", ")", "{", "// Validate the data against the internal schema.", "$", "value", "=", "$", "this", "->", "validateProperties", "(", "$", "value", ",", "$", "field", ")", ";", "}", "elseif", "(", "!", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "$", "this", "->", "toObjectArray", "(", "$", "value", ")", ";", "}", "if", "(", "(", "$", "maxProperties", "=", "$", "field", "->", "val", "(", "'maxProperties'", ")", ")", "&&", "count", "(", "$", "value", ")", ">", "$", "maxProperties", ")", "{", "$", "field", "->", "addError", "(", "'maxProperties'", ",", "[", "'messageCode'", "=>", "'This must contain no more than {maxProperties} {maxProperties,plural,item,items}.'", ",", "'maxItems'", "=>", "$", "maxProperties", ",", "]", ")", ";", "}", "if", "(", "(", "$", "minProperties", "=", "$", "field", "->", "val", "(", "'minProperties'", ")", ")", "&&", "count", "(", "$", "value", ")", "<", "$", "minProperties", ")", "{", "$", "field", "->", "addError", "(", "'minProperties'", ",", "[", "'messageCode'", "=>", "'This must contain at least {minProperties} {minProperties,plural,item,items}.'", ",", "'minItems'", "=>", "$", "minProperties", ",", "]", ")", ";", "}", "return", "$", "value", ";", "}" ]
Validate an object. @param mixed $value The value to validate. @param ValidationField $field The validation results to add. @return object|Invalid Returns a clean object or **null** if validation fails. @throws RefNotFoundException Throws an exception when a schema `$ref` is not found.
[ "Validate", "an", "object", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1603-L1635
train
vanilla/garden-schema
src/Schema.php
Schema.toObjectArray
private function toObjectArray(\Traversable $value) { $class = get_class($value); if ($value instanceof \ArrayObject) { return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass()); } elseif ($value instanceof \ArrayAccess) { $r = new $class; foreach ($value as $k => $v) { $r[$k] = $v; } return $r; } return iterator_to_array($value); }
php
private function toObjectArray(\Traversable $value) { $class = get_class($value); if ($value instanceof \ArrayObject) { return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass()); } elseif ($value instanceof \ArrayAccess) { $r = new $class; foreach ($value as $k => $v) { $r[$k] = $v; } return $r; } return iterator_to_array($value); }
[ "private", "function", "toObjectArray", "(", "\\", "Traversable", "$", "value", ")", "{", "$", "class", "=", "get_class", "(", "$", "value", ")", ";", "if", "(", "$", "value", "instanceof", "\\", "ArrayObject", ")", "{", "return", "new", "$", "class", "(", "$", "value", "->", "getArrayCopy", "(", ")", ",", "$", "value", "->", "getFlags", "(", ")", ",", "$", "value", "->", "getIteratorClass", "(", ")", ")", ";", "}", "elseif", "(", "$", "value", "instanceof", "\\", "ArrayAccess", ")", "{", "$", "r", "=", "new", "$", "class", ";", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "r", "[", "$", "k", "]", "=", "$", "v", ";", "}", "return", "$", "r", ";", "}", "return", "iterator_to_array", "(", "$", "value", ")", ";", "}" ]
Cast a value to an array. @param \Traversable $value The value to convert. @return array Returns an array.
[ "Cast", "a", "value", "to", "an", "array", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1790-L1802
train
vanilla/garden-schema
src/Schema.php
Schema.validateNull
protected function validateNull($value, ValidationField $field) { if ($value === null) { return null; } $field->addError('type', ['messageCode' => 'The value should be null.', 'type' => 'null']); return Invalid::value(); }
php
protected function validateNull($value, ValidationField $field) { if ($value === null) { return null; } $field->addError('type', ['messageCode' => 'The value should be null.', 'type' => 'null']); return Invalid::value(); }
[ "protected", "function", "validateNull", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "null", ";", "}", "$", "field", "->", "addError", "(", "'type'", ",", "[", "'messageCode'", "=>", "'The value should be null.'", ",", "'type'", "=>", "'null'", "]", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}" ]
Validate a null value. @param mixed $value The value to validate. @param ValidationField $field The error collector for the field. @return null|Invalid Returns **null** or invalid.
[ "Validate", "a", "null", "value", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1811-L1817
train
vanilla/garden-schema
src/Schema.php
Schema.validateEnum
protected function validateEnum($value, ValidationField $field) { $enum = $field->val('enum'); if (empty($enum)) { return $value; } if (!in_array($value, $enum, true)) { $field->addError( 'enum', [ 'messageCode' => 'The value must be one of: {enum}.', 'enum' => $enum, ] ); return Invalid::value(); } return $value; }
php
protected function validateEnum($value, ValidationField $field) { $enum = $field->val('enum'); if (empty($enum)) { return $value; } if (!in_array($value, $enum, true)) { $field->addError( 'enum', [ 'messageCode' => 'The value must be one of: {enum}.', 'enum' => $enum, ] ); return Invalid::value(); } return $value; }
[ "protected", "function", "validateEnum", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "enum", "=", "$", "field", "->", "val", "(", "'enum'", ")", ";", "if", "(", "empty", "(", "$", "enum", ")", ")", "{", "return", "$", "value", ";", "}", "if", "(", "!", "in_array", "(", "$", "value", ",", "$", "enum", ",", "true", ")", ")", "{", "$", "field", "->", "addError", "(", "'enum'", ",", "[", "'messageCode'", "=>", "'The value must be one of: {enum}.'", ",", "'enum'", "=>", "$", "enum", ",", "]", ")", ";", "return", "Invalid", "::", "value", "(", ")", ";", "}", "return", "$", "value", ";", "}" ]
Validate a value against an enum. @param mixed $value The value to test. @param ValidationField $field The validation object for adding errors. @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
[ "Validate", "a", "value", "against", "an", "enum", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1826-L1843
train
vanilla/garden-schema
src/Schema.php
Schema.callValidators
private function callValidators($value, ValidationField $field) { $valid = true; // Strip array references in the name except for the last one. $key = $field->getSchemaPath(); if (!empty($this->validators[$key])) { foreach ($this->validators[$key] as $validator) { $r = call_user_func($validator, $value, $field); if ($r === false || Invalid::isInvalid($r)) { $valid = false; } } } // Add an error on the field if the validator hasn't done so. if (!$valid && $field->isValid()) { $field->addError('invalid', ['messageCode' => 'The value is invalid.']); } }
php
private function callValidators($value, ValidationField $field) { $valid = true; // Strip array references in the name except for the last one. $key = $field->getSchemaPath(); if (!empty($this->validators[$key])) { foreach ($this->validators[$key] as $validator) { $r = call_user_func($validator, $value, $field); if ($r === false || Invalid::isInvalid($r)) { $valid = false; } } } // Add an error on the field if the validator hasn't done so. if (!$valid && $field->isValid()) { $field->addError('invalid', ['messageCode' => 'The value is invalid.']); } }
[ "private", "function", "callValidators", "(", "$", "value", ",", "ValidationField", "$", "field", ")", "{", "$", "valid", "=", "true", ";", "// Strip array references in the name except for the last one.", "$", "key", "=", "$", "field", "->", "getSchemaPath", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "validators", "[", "$", "key", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "validators", "[", "$", "key", "]", "as", "$", "validator", ")", "{", "$", "r", "=", "call_user_func", "(", "$", "validator", ",", "$", "value", ",", "$", "field", ")", ";", "if", "(", "$", "r", "===", "false", "||", "Invalid", "::", "isInvalid", "(", "$", "r", ")", ")", "{", "$", "valid", "=", "false", ";", "}", "}", "}", "// Add an error on the field if the validator hasn't done so.", "if", "(", "!", "$", "valid", "&&", "$", "field", "->", "isValid", "(", ")", ")", "{", "$", "field", "->", "addError", "(", "'invalid'", ",", "[", "'messageCode'", "=>", "'The value is invalid.'", "]", ")", ";", "}", "}" ]
Call all of the validators attached to a field. @param mixed $value The field value being validated. @param ValidationField $field The validation object to add errors.
[ "Call", "all", "of", "the", "validators", "attached", "to", "a", "field", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1851-L1870
train
vanilla/garden-schema
src/Schema.php
Schema.jsonSerializeInternal
private function jsonSerializeInternal(array $seen): array { $fix = function ($schema) use (&$fix, $seen) { if ($schema instanceof Schema) { if (in_array($schema, $seen, true)) { return ['$ref' => '#/components/schemas/'.($schema->getID() ?: '$no-id')]; } else { $seen[] = $schema; return $schema->jsonSerializeInternal($seen); } } if (!empty($schema['type'])) { $types = (array)$schema['type']; foreach ($types as $i => &$type) { // Swap datetime and timestamp to other types with formats. if ($type === 'datetime') { $type = 'string'; $schema['format'] = 'date-time'; } elseif ($schema['type'] === 'timestamp') { $type = 'integer'; $schema['format'] = 'timestamp'; } } $types = array_unique($types); $schema['type'] = count($types) === 1 ? reset($types) : $types; } if (!empty($schema['items'])) { $schema['items'] = $fix($schema['items']); } if (!empty($schema['properties'])) { $properties = []; foreach ($schema['properties'] as $key => $property) { $properties[$key] = $fix($property); } $schema['properties'] = $properties; } return $schema; }; $result = $fix($this->schema); return $result; }
php
private function jsonSerializeInternal(array $seen): array { $fix = function ($schema) use (&$fix, $seen) { if ($schema instanceof Schema) { if (in_array($schema, $seen, true)) { return ['$ref' => '#/components/schemas/'.($schema->getID() ?: '$no-id')]; } else { $seen[] = $schema; return $schema->jsonSerializeInternal($seen); } } if (!empty($schema['type'])) { $types = (array)$schema['type']; foreach ($types as $i => &$type) { // Swap datetime and timestamp to other types with formats. if ($type === 'datetime') { $type = 'string'; $schema['format'] = 'date-time'; } elseif ($schema['type'] === 'timestamp') { $type = 'integer'; $schema['format'] = 'timestamp'; } } $types = array_unique($types); $schema['type'] = count($types) === 1 ? reset($types) : $types; } if (!empty($schema['items'])) { $schema['items'] = $fix($schema['items']); } if (!empty($schema['properties'])) { $properties = []; foreach ($schema['properties'] as $key => $property) { $properties[$key] = $fix($property); } $schema['properties'] = $properties; } return $schema; }; $result = $fix($this->schema); return $result; }
[ "private", "function", "jsonSerializeInternal", "(", "array", "$", "seen", ")", ":", "array", "{", "$", "fix", "=", "function", "(", "$", "schema", ")", "use", "(", "&", "$", "fix", ",", "$", "seen", ")", "{", "if", "(", "$", "schema", "instanceof", "Schema", ")", "{", "if", "(", "in_array", "(", "$", "schema", ",", "$", "seen", ",", "true", ")", ")", "{", "return", "[", "'$ref'", "=>", "'#/components/schemas/'", ".", "(", "$", "schema", "->", "getID", "(", ")", "?", ":", "'$no-id'", ")", "]", ";", "}", "else", "{", "$", "seen", "[", "]", "=", "$", "schema", ";", "return", "$", "schema", "->", "jsonSerializeInternal", "(", "$", "seen", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "schema", "[", "'type'", "]", ")", ")", "{", "$", "types", "=", "(", "array", ")", "$", "schema", "[", "'type'", "]", ";", "foreach", "(", "$", "types", "as", "$", "i", "=>", "&", "$", "type", ")", "{", "// Swap datetime and timestamp to other types with formats.", "if", "(", "$", "type", "===", "'datetime'", ")", "{", "$", "type", "=", "'string'", ";", "$", "schema", "[", "'format'", "]", "=", "'date-time'", ";", "}", "elseif", "(", "$", "schema", "[", "'type'", "]", "===", "'timestamp'", ")", "{", "$", "type", "=", "'integer'", ";", "$", "schema", "[", "'format'", "]", "=", "'timestamp'", ";", "}", "}", "$", "types", "=", "array_unique", "(", "$", "types", ")", ";", "$", "schema", "[", "'type'", "]", "=", "count", "(", "$", "types", ")", "===", "1", "?", "reset", "(", "$", "types", ")", ":", "$", "types", ";", "}", "if", "(", "!", "empty", "(", "$", "schema", "[", "'items'", "]", ")", ")", "{", "$", "schema", "[", "'items'", "]", "=", "$", "fix", "(", "$", "schema", "[", "'items'", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "schema", "[", "'properties'", "]", ")", ")", "{", "$", "properties", "=", "[", "]", ";", "foreach", "(", "$", "schema", "[", "'properties'", "]", "as", "$", "key", "=>", "$", "property", ")", "{", "$", "properties", "[", "$", "key", "]", "=", "$", "fix", "(", "$", "property", ")", ";", "}", "$", "schema", "[", "'properties'", "]", "=", "$", "properties", ";", "}", "return", "$", "schema", ";", "}", ";", "$", "result", "=", "$", "fix", "(", "$", "this", "->", "schema", ")", ";", "return", "$", "result", ";", "}" ]
Return the JSON data for serialization with massaging for Open API. - Swap data/time & timestamp types for Open API types. - Turn recursive schema pointers into references. @param Schema[] $seen Schemas that have been seen during traversal. @return array Returns an array of data that `json_encode()` will recognize.
[ "Return", "the", "JSON", "data", "for", "serialization", "with", "massaging", "for", "Open", "API", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1895-L1940
train
vanilla/garden-schema
src/Schema.php
Schema.setValidationClass
public function setValidationClass($class) { trigger_error('Schema::setValidationClass() is deprecated. Use Schema::setValidationFactory() instead.', E_USER_DEPRECATED); if (!is_a($class, Validation::class, true)) { throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500); } $this->setValidationFactory(function () use ($class) { if ($class instanceof Validation) { $result = clone $class; } else { $result = new $class; } return $result; }); $this->validationClass = $class; return $this; }
php
public function setValidationClass($class) { trigger_error('Schema::setValidationClass() is deprecated. Use Schema::setValidationFactory() instead.', E_USER_DEPRECATED); if (!is_a($class, Validation::class, true)) { throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500); } $this->setValidationFactory(function () use ($class) { if ($class instanceof Validation) { $result = clone $class; } else { $result = new $class; } return $result; }); $this->validationClass = $class; return $this; }
[ "public", "function", "setValidationClass", "(", "$", "class", ")", "{", "trigger_error", "(", "'Schema::setValidationClass() is deprecated. Use Schema::setValidationFactory() instead.'", ",", "E_USER_DEPRECATED", ")", ";", "if", "(", "!", "is_a", "(", "$", "class", ",", "Validation", "::", "class", ",", "true", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "\"$class must be a subclass of \"", ".", "Validation", "::", "class", ",", "500", ")", ";", "}", "$", "this", "->", "setValidationFactory", "(", "function", "(", ")", "use", "(", "$", "class", ")", "{", "if", "(", "$", "class", "instanceof", "Validation", ")", "{", "$", "result", "=", "clone", "$", "class", ";", "}", "else", "{", "$", "result", "=", "new", "$", "class", ";", "}", "return", "$", "result", ";", "}", ")", ";", "$", "this", "->", "validationClass", "=", "$", "class", ";", "return", "$", "this", ";", "}" ]
Set the class that's used to contain validation information. @param Validation|string $class Either the name of a class or a class that will be cloned. @return $this @deprecated
[ "Set", "the", "class", "that", "s", "used", "to", "contain", "validation", "information", "." ]
17da87a83d15d45cfedc4d27cf800618160e1cbf
https://github.com/vanilla/garden-schema/blob/17da87a83d15d45cfedc4d27cf800618160e1cbf/src/Schema.php#L1960-L1977
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/AbstractSection.php
AbstractSection.loadChildren
public function loadChildren() { $loader = new CollectionLoader([ 'logger' => $this->logger, 'factory' => $this->modelFactory() ]); $loader->setModel($this); $loader->addFilter([ 'property' => 'master', 'value' => $this->id() ]); $loader->addFilter([ 'property' => 'active', 'value' => true ]); $loader->addOrder([ 'property' => 'position', 'mode' => 'asc' ]); return $loader->load(); }
php
public function loadChildren() { $loader = new CollectionLoader([ 'logger' => $this->logger, 'factory' => $this->modelFactory() ]); $loader->setModel($this); $loader->addFilter([ 'property' => 'master', 'value' => $this->id() ]); $loader->addFilter([ 'property' => 'active', 'value' => true ]); $loader->addOrder([ 'property' => 'position', 'mode' => 'asc' ]); return $loader->load(); }
[ "public", "function", "loadChildren", "(", ")", "{", "$", "loader", "=", "new", "CollectionLoader", "(", "[", "'logger'", "=>", "$", "this", "->", "logger", ",", "'factory'", "=>", "$", "this", "->", "modelFactory", "(", ")", "]", ")", ";", "$", "loader", "->", "setModel", "(", "$", "this", ")", ";", "$", "loader", "->", "addFilter", "(", "[", "'property'", "=>", "'master'", ",", "'value'", "=>", "$", "this", "->", "id", "(", ")", "]", ")", ";", "$", "loader", "->", "addFilter", "(", "[", "'property'", "=>", "'active'", ",", "'value'", "=>", "true", "]", ")", ";", "$", "loader", "->", "addOrder", "(", "[", "'property'", "=>", "'position'", ",", "'mode'", "=>", "'asc'", "]", ")", ";", "return", "$", "loader", "->", "load", "(", ")", ";", "}" ]
HierarchicalTrait > loadChildren @return \ArrayAccess|\Traversable
[ "HierarchicalTrait", ">", "loadChildren" ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/AbstractSection.php#L143-L166
train
locomotivemtl/charcoal-cms
src/Charcoal/Cms/AbstractSection.php
AbstractSection.postUpdate
protected function postUpdate(array $properties = null) { if (!$this->locked()) { $this->generateObjectRoute($this->slug()); } return parent::postUpdate($properties); }
php
protected function postUpdate(array $properties = null) { if (!$this->locked()) { $this->generateObjectRoute($this->slug()); } return parent::postUpdate($properties); }
[ "protected", "function", "postUpdate", "(", "array", "$", "properties", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "locked", "(", ")", ")", "{", "$", "this", "->", "generateObjectRoute", "(", "$", "this", "->", "slug", "(", ")", ")", ";", "}", "return", "parent", "::", "postUpdate", "(", "$", "properties", ")", ";", "}" ]
Check whatever before the update. @param array|null $properties Properties. @return boolean
[ "Check", "whatever", "before", "the", "update", "." ]
3467caebdebdaaa226d223a905ebcc3e24fdca16
https://github.com/locomotivemtl/charcoal-cms/blob/3467caebdebdaaa226d223a905ebcc3e24fdca16/src/Charcoal/Cms/AbstractSection.php#L448-L455
train
pear/Net_Socket
Net/Socket.php
Net_Socket.disconnect
public function disconnect() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } @fclose($this->fp); $this->fp = null; return true; }
php
public function disconnect() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } @fclose($this->fp); $this->fp = null; return true; }
[ "public", "function", "disconnect", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "@", "fclose", "(", "$", "this", "->", "fp", ")", ";", "$", "this", "->", "fp", "=", "null", ";", "return", "true", ";", "}" ]
Disconnects from the peer, closes the socket. @access public @return mixed true on success or a PEAR_Error instance otherwise
[ "Disconnects", "from", "the", "peer", "closes", "the", "socket", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L225-L235
train
pear/Net_Socket
Net/Socket.php
Net_Socket.setBlocking
public function setBlocking($mode) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $this->blocking = $mode; stream_set_blocking($this->fp, (int)$this->blocking); return true; }
php
public function setBlocking($mode) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $this->blocking = $mode; stream_set_blocking($this->fp, (int)$this->blocking); return true; }
[ "public", "function", "setBlocking", "(", "$", "mode", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "this", "->", "blocking", "=", "$", "mode", ";", "stream_set_blocking", "(", "$", "this", "->", "fp", ",", "(", "int", ")", "$", "this", "->", "blocking", ")", ";", "return", "true", ";", "}" ]
Sets whether the socket connection should be blocking or not. A read call to a non-blocking socket will return immediately if there is no data available, whereas it will block until there is data for blocking sockets. @param boolean $mode True for blocking sockets, false for nonblocking. @access public @return mixed true on success or a PEAR_Error instance otherwise
[ "Sets", "whether", "the", "socket", "connection", "should", "be", "blocking", "or", "not", ".", "A", "read", "call", "to", "a", "non", "-", "blocking", "socket", "will", "return", "immediately", "if", "there", "is", "no", "data", "available", "whereas", "it", "will", "block", "until", "there", "is", "data", "for", "blocking", "sockets", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L272-L282
train
pear/Net_Socket
Net/Socket.php
Net_Socket.setTimeout
public function setTimeout($seconds = null, $microseconds = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if ($seconds === null && $microseconds === null) { $seconds = (int)$this->timeout; $microseconds = (int)(($this->timeout - $seconds) * 1000000); } else { $this->timeout = $seconds + $microseconds / 1000000; } if ($this->timeout > 0) { return stream_set_timeout($this->fp, (int)$seconds, (int)$microseconds); } else { return false; } }
php
public function setTimeout($seconds = null, $microseconds = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if ($seconds === null && $microseconds === null) { $seconds = (int)$this->timeout; $microseconds = (int)(($this->timeout - $seconds) * 1000000); } else { $this->timeout = $seconds + $microseconds / 1000000; } if ($this->timeout > 0) { return stream_set_timeout($this->fp, (int)$seconds, (int)$microseconds); } else { return false; } }
[ "public", "function", "setTimeout", "(", "$", "seconds", "=", "null", ",", "$", "microseconds", "=", "null", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "if", "(", "$", "seconds", "===", "null", "&&", "$", "microseconds", "===", "null", ")", "{", "$", "seconds", "=", "(", "int", ")", "$", "this", "->", "timeout", ";", "$", "microseconds", "=", "(", "int", ")", "(", "(", "$", "this", "->", "timeout", "-", "$", "seconds", ")", "*", "1000000", ")", ";", "}", "else", "{", "$", "this", "->", "timeout", "=", "$", "seconds", "+", "$", "microseconds", "/", "1000000", ";", "}", "if", "(", "$", "this", "->", "timeout", ">", "0", ")", "{", "return", "stream_set_timeout", "(", "$", "this", "->", "fp", ",", "(", "int", ")", "$", "seconds", ",", "(", "int", ")", "$", "microseconds", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Sets the timeout value on socket descriptor, expressed in the sum of seconds and microseconds @param integer $seconds Seconds. @param integer $microseconds Microseconds, optional. @access public @return mixed True on success or false on failure or a PEAR_Error instance when not connected
[ "Sets", "the", "timeout", "value", "on", "socket", "descriptor", "expressed", "in", "the", "sum", "of", "seconds", "and", "microseconds" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L295-L313
train
pear/Net_Socket
Net/Socket.php
Net_Socket.setWriteBuffer
public function setWriteBuffer($size) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $returned = stream_set_write_buffer($this->fp, $size); if ($returned === 0) { return true; } return $this->raiseError('Cannot set write buffer.'); }
php
public function setWriteBuffer($size) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $returned = stream_set_write_buffer($this->fp, $size); if ($returned === 0) { return true; } return $this->raiseError('Cannot set write buffer.'); }
[ "public", "function", "setWriteBuffer", "(", "$", "size", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "returned", "=", "stream_set_write_buffer", "(", "$", "this", "->", "fp", ",", "$", "size", ")", ";", "if", "(", "$", "returned", "===", "0", ")", "{", "return", "true", ";", "}", "return", "$", "this", "->", "raiseError", "(", "'Cannot set write buffer.'", ")", ";", "}" ]
Sets the file buffering size on the stream. See php's stream_set_write_buffer for more information. @param integer $size Write buffer size. @access public @return mixed on success or an PEAR_Error object otherwise
[ "Sets", "the", "file", "buffering", "size", "on", "the", "stream", ".", "See", "php", "s", "stream_set_write_buffer", "for", "more", "information", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L324-L336
train
pear/Net_Socket
Net/Socket.php
Net_Socket.gets
public function gets($size = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if (null === $size) { return @fgets($this->fp); } else { return @fgets($this->fp, $size); } }
php
public function gets($size = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if (null === $size) { return @fgets($this->fp); } else { return @fgets($this->fp, $size); } }
[ "public", "function", "gets", "(", "$", "size", "=", "null", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "if", "(", "null", "===", "$", "size", ")", "{", "return", "@", "fgets", "(", "$", "this", "->", "fp", ")", ";", "}", "else", "{", "return", "@", "fgets", "(", "$", "this", "->", "fp", ",", "$", "size", ")", ";", "}", "}" ]
Get a specified line of data @param int $size Reading ends when size - 1 bytes have been read, or a newline or an EOF (whichever comes first). If no size is specified, it will keep reading from the stream until it reaches the end of the line. @access public @return mixed $size bytes of data from the socket, or a PEAR_Error if not connected. If an error occurs, FALSE is returned.
[ "Get", "a", "specified", "line", "of", "data" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L374-L385
train
pear/Net_Socket
Net/Socket.php
Net_Socket.write
public function write($data, $blocksize = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if (null === $blocksize && !OS_WINDOWS) { $written = @fwrite($this->fp, $data); // Check for timeout or lost connection if ($written === false) { $meta_data = $this->getStatus(); if (!is_array($meta_data)) { return $meta_data; // PEAR_Error } if (!empty($meta_data['timed_out'])) { return $this->raiseError('timed out'); } } return $written; } else { if (null === $blocksize) { $blocksize = 1024; } $pos = 0; $size = strlen($data); while ($pos < $size) { $written = @fwrite($this->fp, substr($data, $pos, $blocksize)); // Check for timeout or lost connection if ($written === false) { $meta_data = $this->getStatus(); if (!is_array($meta_data)) { return $meta_data; // PEAR_Error } if (!empty($meta_data['timed_out'])) { return $this->raiseError('timed out'); } return $written; } $pos += $written; } return $pos; } }
php
public function write($data, $blocksize = null) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } if (null === $blocksize && !OS_WINDOWS) { $written = @fwrite($this->fp, $data); // Check for timeout or lost connection if ($written === false) { $meta_data = $this->getStatus(); if (!is_array($meta_data)) { return $meta_data; // PEAR_Error } if (!empty($meta_data['timed_out'])) { return $this->raiseError('timed out'); } } return $written; } else { if (null === $blocksize) { $blocksize = 1024; } $pos = 0; $size = strlen($data); while ($pos < $size) { $written = @fwrite($this->fp, substr($data, $pos, $blocksize)); // Check for timeout or lost connection if ($written === false) { $meta_data = $this->getStatus(); if (!is_array($meta_data)) { return $meta_data; // PEAR_Error } if (!empty($meta_data['timed_out'])) { return $this->raiseError('timed out'); } return $written; } $pos += $written; } return $pos; } }
[ "public", "function", "write", "(", "$", "data", ",", "$", "blocksize", "=", "null", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "if", "(", "null", "===", "$", "blocksize", "&&", "!", "OS_WINDOWS", ")", "{", "$", "written", "=", "@", "fwrite", "(", "$", "this", "->", "fp", ",", "$", "data", ")", ";", "// Check for timeout or lost connection", "if", "(", "$", "written", "===", "false", ")", "{", "$", "meta_data", "=", "$", "this", "->", "getStatus", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "meta_data", ")", ")", "{", "return", "$", "meta_data", ";", "// PEAR_Error", "}", "if", "(", "!", "empty", "(", "$", "meta_data", "[", "'timed_out'", "]", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'timed out'", ")", ";", "}", "}", "return", "$", "written", ";", "}", "else", "{", "if", "(", "null", "===", "$", "blocksize", ")", "{", "$", "blocksize", "=", "1024", ";", "}", "$", "pos", "=", "0", ";", "$", "size", "=", "strlen", "(", "$", "data", ")", ";", "while", "(", "$", "pos", "<", "$", "size", ")", "{", "$", "written", "=", "@", "fwrite", "(", "$", "this", "->", "fp", ",", "substr", "(", "$", "data", ",", "$", "pos", ",", "$", "blocksize", ")", ")", ";", "// Check for timeout or lost connection", "if", "(", "$", "written", "===", "false", ")", "{", "$", "meta_data", "=", "$", "this", "->", "getStatus", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "meta_data", ")", ")", "{", "return", "$", "meta_data", ";", "// PEAR_Error", "}", "if", "(", "!", "empty", "(", "$", "meta_data", "[", "'timed_out'", "]", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'timed out'", ")", ";", "}", "return", "$", "written", ";", "}", "$", "pos", "+=", "$", "written", ";", "}", "return", "$", "pos", ";", "}", "}" ]
Write a specified amount of data. @param string $data Data to write. @param integer $blocksize Amount of data to write at once. NULL means all at once. @access public @return mixed If the socket is not connected, returns an instance of PEAR_Error. If the write succeeds, returns the number of bytes written. If the write fails, returns false. If the socket times out, returns an instance of PEAR_Error.
[ "Write", "a", "specified", "amount", "of", "data", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L422-L475
train
pear/Net_Socket
Net/Socket.php
Net_Socket.writeLine
public function writeLine($data) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } return fwrite($this->fp, $data . $this->newline); }
php
public function writeLine($data) { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } return fwrite($this->fp, $data . $this->newline); }
[ "public", "function", "writeLine", "(", "$", "data", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "return", "fwrite", "(", "$", "this", "->", "fp", ",", "$", "data", ".", "$", "this", "->", "newline", ")", ";", "}" ]
Write a line of data to the socket, followed by a trailing newline. @param string $data Data to write @access public @return mixed fwrite() result, or PEAR_Error when not connected
[ "Write", "a", "line", "of", "data", "to", "the", "socket", "followed", "by", "a", "trailing", "newline", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L485-L492
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readByte
public function readByte() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } return ord(@fread($this->fp, 1)); }
php
public function readByte() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } return ord(@fread($this->fp, 1)); }
[ "public", "function", "readByte", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "return", "ord", "(", "@", "fread", "(", "$", "this", "->", "fp", ",", "1", ")", ")", ";", "}" ]
Reads a byte of data @access public @return integer 1 byte of data from the socket, or a PEAR_Error if not connected.
[ "Reads", "a", "byte", "of", "data" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L514-L521
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readWord
public function readWord() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 2); return (ord($buf[0]) + (ord($buf[1]) << 8)); }
php
public function readWord() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 2); return (ord($buf[0]) + (ord($buf[1]) << 8)); }
[ "public", "function", "readWord", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "buf", "=", "@", "fread", "(", "$", "this", "->", "fp", ",", "2", ")", ";", "return", "(", "ord", "(", "$", "buf", "[", "0", "]", ")", "+", "(", "ord", "(", "$", "buf", "[", "1", "]", ")", "<<", "8", ")", ")", ";", "}" ]
Reads a word of data @access public @return integer 1 word of data from the socket, or a PEAR_Error if not connected.
[ "Reads", "a", "word", "of", "data" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L530-L539
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readInt
public function readInt() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 4); return (ord($buf[0]) + (ord($buf[1]) << 8) + (ord($buf[2]) << 16) + (ord($buf[3]) << 24)); }
php
public function readInt() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 4); return (ord($buf[0]) + (ord($buf[1]) << 8) + (ord($buf[2]) << 16) + (ord($buf[3]) << 24)); }
[ "public", "function", "readInt", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "buf", "=", "@", "fread", "(", "$", "this", "->", "fp", ",", "4", ")", ";", "return", "(", "ord", "(", "$", "buf", "[", "0", "]", ")", "+", "(", "ord", "(", "$", "buf", "[", "1", "]", ")", "<<", "8", ")", "+", "(", "ord", "(", "$", "buf", "[", "2", "]", ")", "<<", "16", ")", "+", "(", "ord", "(", "$", "buf", "[", "3", "]", ")", "<<", "24", ")", ")", ";", "}" ]
Reads an int of data @access public @return integer 1 int of data from the socket, or a PEAR_Error if not connected.
[ "Reads", "an", "int", "of", "data" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L548-L558
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readString
public function readString() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $string = ''; while (($char = @fread($this->fp, 1)) !== "\x00") { $string .= $char; } return $string; }
php
public function readString() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $string = ''; while (($char = @fread($this->fp, 1)) !== "\x00") { $string .= $char; } return $string; }
[ "public", "function", "readString", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "string", "=", "''", ";", "while", "(", "(", "$", "char", "=", "@", "fread", "(", "$", "this", "->", "fp", ",", "1", ")", ")", "!==", "\"\\x00\"", ")", "{", "$", "string", ".=", "$", "char", ";", "}", "return", "$", "string", ";", "}" ]
Reads a zero-terminated string of data @access public @return string, or a PEAR_Error if not connected.
[ "Reads", "a", "zero", "-", "terminated", "string", "of", "data" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L567-L579
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readIPAddress
public function readIPAddress() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 4); return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]), ord($buf[2]), ord($buf[3])); }
php
public function readIPAddress() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $buf = @fread($this->fp, 4); return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]), ord($buf[2]), ord($buf[3])); }
[ "public", "function", "readIPAddress", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "buf", "=", "@", "fread", "(", "$", "this", "->", "fp", ",", "4", ")", ";", "return", "sprintf", "(", "'%d.%d.%d.%d'", ",", "ord", "(", "$", "buf", "[", "0", "]", ")", ",", "ord", "(", "$", "buf", "[", "1", "]", ")", ",", "ord", "(", "$", "buf", "[", "2", "]", ")", ",", "ord", "(", "$", "buf", "[", "3", "]", ")", ")", ";", "}" ]
Reads an IP Address and returns it in a dot formatted string @access public @return string Dot formatted string, or a PEAR_Error if not connected.
[ "Reads", "an", "IP", "Address", "and", "returns", "it", "in", "a", "dot", "formatted", "string" ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L588-L598
train
pear/Net_Socket
Net/Socket.php
Net_Socket.readLine
public function readLine() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $line = ''; $timeout = time() + $this->timeout; while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) { $line .= @fgets($this->fp, $this->lineLength); if (substr($line, -1) == "\n") { return rtrim($line, $this->newline); } } return $line; }
php
public function readLine() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } $line = ''; $timeout = time() + $this->timeout; while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) { $line .= @fgets($this->fp, $this->lineLength); if (substr($line, -1) == "\n") { return rtrim($line, $this->newline); } } return $line; }
[ "public", "function", "readLine", "(", ")", "{", "if", "(", "!", "is_resource", "(", "$", "this", "->", "fp", ")", ")", "{", "return", "$", "this", "->", "raiseError", "(", "'not connected'", ")", ";", "}", "$", "line", "=", "''", ";", "$", "timeout", "=", "time", "(", ")", "+", "$", "this", "->", "timeout", ";", "while", "(", "!", "feof", "(", "$", "this", "->", "fp", ")", "&&", "(", "!", "$", "this", "->", "timeout", "||", "time", "(", ")", "<", "$", "timeout", ")", ")", "{", "$", "line", ".=", "@", "fgets", "(", "$", "this", "->", "fp", ",", "$", "this", "->", "lineLength", ")", ";", "if", "(", "substr", "(", "$", "line", ",", "-", "1", ")", "==", "\"\\n\"", ")", "{", "return", "rtrim", "(", "$", "line", ",", "$", "this", "->", "newline", ")", ";", "}", "}", "return", "$", "line", ";", "}" ]
Read until either the end of the socket or a newline, whichever comes first. Strips the trailing newline from the returned data. @access public @return string All available data up to a newline, without that newline, or until the end of the socket, or a PEAR_Error if not connected.
[ "Read", "until", "either", "the", "end", "of", "the", "socket", "or", "a", "newline", "whichever", "comes", "first", ".", "Strips", "the", "trailing", "newline", "from", "the", "returned", "data", "." ]
7482c62deab2c2685e00c221d97a83e17c795ef8
https://github.com/pear/Net_Socket/blob/7482c62deab2c2685e00c221d97a83e17c795ef8/Net/Socket.php#L609-L627
train