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
ezra-obiwale/dSCore
src/Stdlib/Table.php
Table.setHeaders
public static function setHeaders(array $data, array $attributes = array()) { foreach ($data as $header) { self::addHeader($header, $attributes); } }
php
public static function setHeaders(array $data, array $attributes = array()) { foreach ($data as $header) { self::addHeader($header, $attributes); } }
[ "public", "static", "function", "setHeaders", "(", "array", "$", "data", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "header", ")", "{", "self", "::", "addHeader", "(", "$", "header", ",", "$", "attributes", ")", ";", "}", "}" ]
Sets header data @param array $data Array of labels for each column @param array $attributes Array of attr => value to apply to each column
[ "Sets", "header", "data" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Table.php#L51-L55
train
ezra-obiwale/dSCore
src/Stdlib/Table.php
Table.setFooters
public static function setFooters(array $data, array $attributes = array()) { foreach ($data as $footer) { self::addFooter($footer, $attributes); } }
php
public static function setFooters(array $data, array $attributes = array()) { foreach ($data as $footer) { self::addFooter($footer, $attributes); } }
[ "public", "static", "function", "setFooters", "(", "array", "$", "data", ",", "array", "$", "attributes", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "footer", ")", "{", "self", "::", "addFooter", "(", "$", "footer", ",", "$", "attributes", ")", ";", "}", "}" ]
Sets footer data @param array $data Array of labels for each column @param array $attributes Array of attr => value to apply to each column
[ "Sets", "footer", "data" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Table.php#L89-L93
train
ezra-obiwale/dSCore
src/Stdlib/Table.php
Table.newRow
public static function newRow(array $attrs = array()) { if (!empty(self::$row_data)) self::$rows[count(self::$rows) - 1][] = self::$row_data; self::$row_data = array(); self::$rows[][] = $attrs; return count(self::$rows); }
php
public static function newRow(array $attrs = array()) { if (!empty(self::$row_data)) self::$rows[count(self::$rows) - 1][] = self::$row_data; self::$row_data = array(); self::$rows[][] = $attrs; return count(self::$rows); }
[ "public", "static", "function", "newRow", "(", "array", "$", "attrs", "=", "array", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "self", "::", "$", "row_data", ")", ")", "self", "::", "$", "rows", "[", "count", "(", "self", "::", "$", "rows", ")", "-", "1", "]", "[", "]", "=", "self", "::", "$", "row_data", ";", "self", "::", "$", "row_data", "=", "array", "(", ")", ";", "self", "::", "$", "rows", "[", "]", "[", "]", "=", "$", "attrs", ";", "return", "count", "(", "self", "::", "$", "rows", ")", ";", "}" ]
Signals beginning of a new row @param array $attrs Array of attr => value to apply to the row
[ "Signals", "beginning", "of", "a", "new", "row" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Table.php#L99-L105
train
ezra-obiwale/dSCore
src/Stdlib/Table.php
Table.render
public static function render() { self::newRow(); ob_start(); ?> <table <?php echo (!empty(self::$table_attributes)) ? self::parseAttributes(self::$table_attributes) : ""; ?>> <?php if (!empty(self::$headers)) { ?> <thead> <tr> <?php foreach (self::$headers as $header) { ?> <th <?php echo self::parseAttributes($header[1]); ?>><?php echo $header[0] ?></th> <?php } ?> </tr> </thead> <?php } if (!empty(self::$rows)) { ?> <tbody> <?php foreach (self::$rows as $rowData) { if (count($rowData) > 1) { ?> <tr <?php echo self::parseAttributes($rowData[0]); ?>> <?php foreach ($rowData[1] as $row) { ?> <td <?php echo self::parseAttributes($row[1]); ?>><?php echo $row[0] ?></td> <?php } ?> </tr> <?php } } ?> </tbody> <?php } if (!empty(self::$footers)) { ?> <tfoot> <tr> <?php foreach (self::$footers as $footer) { ?> <th <?php echo self::parseAttributes($footer[1]); ?>><?php echo $footer[0] ?></th> <?php } ?> </tr> </tfoot> <?php } ?> </table> <?php return ob_get_clean(); }
php
public static function render() { self::newRow(); ob_start(); ?> <table <?php echo (!empty(self::$table_attributes)) ? self::parseAttributes(self::$table_attributes) : ""; ?>> <?php if (!empty(self::$headers)) { ?> <thead> <tr> <?php foreach (self::$headers as $header) { ?> <th <?php echo self::parseAttributes($header[1]); ?>><?php echo $header[0] ?></th> <?php } ?> </tr> </thead> <?php } if (!empty(self::$rows)) { ?> <tbody> <?php foreach (self::$rows as $rowData) { if (count($rowData) > 1) { ?> <tr <?php echo self::parseAttributes($rowData[0]); ?>> <?php foreach ($rowData[1] as $row) { ?> <td <?php echo self::parseAttributes($row[1]); ?>><?php echo $row[0] ?></td> <?php } ?> </tr> <?php } } ?> </tbody> <?php } if (!empty(self::$footers)) { ?> <tfoot> <tr> <?php foreach (self::$footers as $footer) { ?> <th <?php echo self::parseAttributes($footer[1]); ?>><?php echo $footer[0] ?></th> <?php } ?> </tr> </tfoot> <?php } ?> </table> <?php return ob_get_clean(); }
[ "public", "static", "function", "render", "(", ")", "{", "self", "::", "newRow", "(", ")", ";", "ob_start", "(", ")", ";", "?>\n\n <table <?php", "echo", "(", "!", "empty", "(", "self", "::", "$", "table_attributes", ")", ")", "?", "self", "::", "parseAttributes", "(", "self", "::", "$", "table_attributes", ")", ":", "\"\"", ";", "?>>\n <?php", "if", "(", "!", "empty", "(", "self", "::", "$", "headers", ")", ")", "{", "?>\n\n <thead>\n <tr>\n <?php", "foreach", "(", "self", "::", "$", "headers", "as", "$", "header", ")", "{", "?>\n\n <th <?php", "echo", "self", "::", "parseAttributes", "(", "$", "header", "[", "1", "]", ")", ";", "?>><?php", "echo", "$", "header", "[", "0", "]", "?></th>\n <?php", "}", "?>\n\n </tr>\n </thead>\n <?php", "}", "if", "(", "!", "empty", "(", "self", "::", "$", "rows", ")", ")", "{", "?>\n\n <tbody>\n <?php", "foreach", "(", "self", "::", "$", "rows", "as", "$", "rowData", ")", "{", "if", "(", "count", "(", "$", "rowData", ")", ">", "1", ")", "{", "?>\n\n <tr <?php", "echo", "self", "::", "parseAttributes", "(", "$", "rowData", "[", "0", "]", ")", ";", "?>>\n <?php", "foreach", "(", "$", "rowData", "[", "1", "]", "as", "$", "row", ")", "{", "?>\n <td <?php", "echo", "self", "::", "parseAttributes", "(", "$", "row", "[", "1", "]", ")", ";", "?>><?php", "echo", "$", "row", "[", "0", "]", "?></td>\n <?php", "}", "?>\n\n </tr>\n <?php", "}", "}", "?>\n\n </tbody>\n <?php", "}", "if", "(", "!", "empty", "(", "self", "::", "$", "footers", ")", ")", "{", "?>\n\n <tfoot>\n <tr>\n <?php", "foreach", "(", "self", "::", "$", "footers", "as", "$", "footer", ")", "{", "?>\n\n <th <?php", "echo", "self", "::", "parseAttributes", "(", "$", "footer", "[", "1", "]", ")", ";", "?>><?php", "echo", "$", "footer", "[", "0", "]", "?></th>\n <?php", "}", "?>\n\n </tr>\n </tfoot>\n <?php", "}", "?>\n </table>\n <?php", "return", "ob_get_clean", "(", ")", ";", "}" ]
Renders the HTML Table @return HTMLContent
[ "Renders", "the", "HTML", "Table" ]
dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d
https://github.com/ezra-obiwale/dSCore/blob/dd51246e0dc2c64d4d44de7992d7ff1b5165ab2d/src/Stdlib/Table.php#L119-L192
train
Wedeto/HTTP
src/Forms/TransformStore.php
TransformStore.getTransformer
public function getTransformer(string $target_class) { if (isset($this->transformers[$target_class])) return $this->transformers[$target_class]; foreach ($this->transformers as $class => $transformer) { $inherit_mode = $transformer->getInheritMode(); if ( ($inherit_mode === Transformer::INHERIT_UP && is_a($class, $target_class, true)) || ($inherit_mode === Transformer::INHERIT_DOWN && is_a($target_class, $class, true)) ) { return $transformer; } } throw new TransformException("No transform to class $target_class"); }
php
public function getTransformer(string $target_class) { if (isset($this->transformers[$target_class])) return $this->transformers[$target_class]; foreach ($this->transformers as $class => $transformer) { $inherit_mode = $transformer->getInheritMode(); if ( ($inherit_mode === Transformer::INHERIT_UP && is_a($class, $target_class, true)) || ($inherit_mode === Transformer::INHERIT_DOWN && is_a($target_class, $class, true)) ) { return $transformer; } } throw new TransformException("No transform to class $target_class"); }
[ "public", "function", "getTransformer", "(", "string", "$", "target_class", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "transformers", "[", "$", "target_class", "]", ")", ")", "return", "$", "this", "->", "transformers", "[", "$", "target_class", "]", ";", "foreach", "(", "$", "this", "->", "transformers", "as", "$", "class", "=>", "$", "transformer", ")", "{", "$", "inherit_mode", "=", "$", "transformer", "->", "getInheritMode", "(", ")", ";", "if", "(", "(", "$", "inherit_mode", "===", "Transformer", "::", "INHERIT_UP", "&&", "is_a", "(", "$", "class", ",", "$", "target_class", ",", "true", ")", ")", "||", "(", "$", "inherit_mode", "===", "Transformer", "::", "INHERIT_DOWN", "&&", "is_a", "(", "$", "target_class", ",", "$", "class", ",", "true", ")", ")", ")", "{", "return", "$", "transformer", ";", "}", "}", "throw", "new", "TransformException", "(", "\"No transform to class $target_class\"", ")", ";", "}" ]
Get a transformer that converts to the target class. If a direct version is available, that is returned. Otherwise, a transformer registered to transform to a superclass of the target may be returned instead. @param string $target_class The class to transform to @return Transformer A suitable transformer @throws TransformException When no transform is available
[ "Get", "a", "transformer", "that", "converts", "to", "the", "target", "class", ".", "If", "a", "direct", "version", "is", "available", "that", "is", "returned", ".", "Otherwise", "a", "transformer", "registered", "to", "transform", "to", "a", "superclass", "of", "the", "target", "may", "be", "returned", "instead", "." ]
7318eff1b81a3c103c4263466d09b7f3593b70b9
https://github.com/Wedeto/HTTP/blob/7318eff1b81a3c103c4263466d09b7f3593b70b9/src/Forms/TransformStore.php#L53-L71
train
koolkode/stream
src/ChunkEncodedOutputStream.php
ChunkEncodedOutputStream.flush
public function flush() { if($this->stream === NULL) { throw new \RuntimeException(sprintf('Cannot flush detached stream')); } if(strlen($this->buffer)) { $this->stream->write(sprintf("%X\r\n%s\r\n", strlen($this->buffer), $this->buffer)); $this->buffer = ''; } }
php
public function flush() { if($this->stream === NULL) { throw new \RuntimeException(sprintf('Cannot flush detached stream')); } if(strlen($this->buffer)) { $this->stream->write(sprintf("%X\r\n%s\r\n", strlen($this->buffer), $this->buffer)); $this->buffer = ''; } }
[ "public", "function", "flush", "(", ")", "{", "if", "(", "$", "this", "->", "stream", "===", "NULL", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Cannot flush detached stream'", ")", ")", ";", "}", "if", "(", "strlen", "(", "$", "this", "->", "buffer", ")", ")", "{", "$", "this", "->", "stream", "->", "write", "(", "sprintf", "(", "\"%X\\r\\n%s\\r\\n\"", ",", "strlen", "(", "$", "this", "->", "buffer", ")", ",", "$", "this", "->", "buffer", ")", ")", ";", "$", "this", "->", "buffer", "=", "''", ";", "}", "}" ]
Flush the current write buffer to the underlying output stream. Does nothing if the write buffer is empty. @throws \RuntimeException When the stream has been detached.
[ "Flush", "the", "current", "write", "buffer", "to", "the", "underlying", "output", "stream", "." ]
05e83efd76e1cb9e40a972711986b4a7e38bc141
https://github.com/koolkode/stream/blob/05e83efd76e1cb9e40a972711986b4a7e38bc141/src/ChunkEncodedOutputStream.php#L136-L148
train
bseddon/XPath20
DOM/XmlSchemaSet.php
XmlSchemaSet.AddSchema
public function AddSchema( $schema ) { if ( is_null( $schema ) ) throw new \lyquidity\xml\exceptions\ArgumentNullException(); if ( ! $schema instanceof XmlSchema ) throw new XmlSchemaException( "The parameter is not a valid XmlSchema instance" ); $this->schemas[ $schema->getTargetNamespace() ] = $schema; }
php
public function AddSchema( $schema ) { if ( is_null( $schema ) ) throw new \lyquidity\xml\exceptions\ArgumentNullException(); if ( ! $schema instanceof XmlSchema ) throw new XmlSchemaException( "The parameter is not a valid XmlSchema instance" ); $this->schemas[ $schema->getTargetNamespace() ] = $schema; }
[ "public", "function", "AddSchema", "(", "$", "schema", ")", "{", "if", "(", "is_null", "(", "$", "schema", ")", ")", "throw", "new", "\\", "lyquidity", "\\", "xml", "\\", "exceptions", "\\", "ArgumentNullException", "(", ")", ";", "if", "(", "!", "$", "schema", "instanceof", "XmlSchema", ")", "throw", "new", "XmlSchemaException", "(", "\"The parameter is not a valid XmlSchema instance\"", ")", ";", "$", "this", "->", "schemas", "[", "$", "schema", "->", "getTargetNamespace", "(", ")", "]", "=", "$", "schema", ";", "}" ]
Adds the given XmlSchema to the XmlSchemaSet. @param XmlSchema $schema The XmlSchema object to add to the XmlSchemaSet. @return XmlSchema An XmlSchema object if the schema is valid otherwise, an XmlSchemaException is thrown. @throws XmlSchemaException A schema in the XmlSchemaSet is not valid. ArgumentNullException The URL passed as a parameter is null or System.String.Empty.
[ "Adds", "the", "given", "XmlSchema", "to", "the", "XmlSchemaSet", "." ]
69882b6efffaa5470a819d5fdd2f6473ddeb046d
https://github.com/bseddon/XPath20/blob/69882b6efffaa5470a819d5fdd2f6473ddeb046d/DOM/XmlSchemaSet.php#L196-L202
train
naucon/Utility
src/EnumeratorAbstract.php
EnumeratorAbstract.set
public function set($key, $value) { if (!is_null($key) && is_scalar($key) ) { return $this->_items[$key] = $value; } else { // given index name is not valid throw new EnumeratorException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
php
public function set($key, $value) { if (!is_null($key) && is_scalar($key) ) { return $this->_items[$key] = $value; } else { // given index name is not valid throw new EnumeratorException('Element could not be added to list. Index is not valid.', E_NOTICE); } }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "is_null", "(", "$", "key", ")", "&&", "is_scalar", "(", "$", "key", ")", ")", "{", "return", "$", "this", "->", "_items", "[", "$", "key", "]", "=", "$", "value", ";", "}", "else", "{", "// given index name is not valid", "throw", "new", "EnumeratorException", "(", "'Element could not be added to list. Index is not valid.'", ",", "E_NOTICE", ")", ";", "}", "}" ]
add or replace a value with a specified key @param mixed $key key @param mixed $value value @return mixed value @throws EnumeratorException
[ "add", "or", "replace", "a", "value", "with", "a", "specified", "key" ]
d225bb5d09d82400917f710c9d502949a66442c4
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/EnumeratorAbstract.php#L59-L69
train
nails/module-blog
blog/models/blog_model.php
NAILS_Blog_model.getAssociations
public function getAssociations($post_id = null) { $oConfig = Factory::service('Config'); $oDb = Factory::service('Database'); $_associations = $oConfig->item('blog_post_associations'); if (!$_associations) { return array(); } // -------------------------------------------------------------------------- foreach ($_associations as &$assoc) { /** * Fetch the association data from the source, fail ungracefully - the dev * should have this configured correctly. * * Fetch current associations if a post_id has been supplied */ if ($post_id) { $oDb->where('post_id', $post_id); $assoc->current = $oDb->get($assoc->target)->result(); } else { $assoc->current = array(); } // Fetch the raw data $oDb->select($assoc->source->id . ' id, ' . $assoc->source->label . ' label'); $oDb->order_by('label'); if (isset($assoc->source->where) && $assoc->source->where) { $oDb->where($assoc->source->where); } $assoc->data = $oDb->get($assoc->source->table)->result(); } return $_associations; }
php
public function getAssociations($post_id = null) { $oConfig = Factory::service('Config'); $oDb = Factory::service('Database'); $_associations = $oConfig->item('blog_post_associations'); if (!$_associations) { return array(); } // -------------------------------------------------------------------------- foreach ($_associations as &$assoc) { /** * Fetch the association data from the source, fail ungracefully - the dev * should have this configured correctly. * * Fetch current associations if a post_id has been supplied */ if ($post_id) { $oDb->where('post_id', $post_id); $assoc->current = $oDb->get($assoc->target)->result(); } else { $assoc->current = array(); } // Fetch the raw data $oDb->select($assoc->source->id . ' id, ' . $assoc->source->label . ' label'); $oDb->order_by('label'); if (isset($assoc->source->where) && $assoc->source->where) { $oDb->where($assoc->source->where); } $assoc->data = $oDb->get($assoc->source->table)->result(); } return $_associations; }
[ "public", "function", "getAssociations", "(", "$", "post_id", "=", "null", ")", "{", "$", "oConfig", "=", "Factory", "::", "service", "(", "'Config'", ")", ";", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "_associations", "=", "$", "oConfig", "->", "item", "(", "'blog_post_associations'", ")", ";", "if", "(", "!", "$", "_associations", ")", "{", "return", "array", "(", ")", ";", "}", "// --------------------------------------------------------------------------", "foreach", "(", "$", "_associations", "as", "&", "$", "assoc", ")", "{", "/**\n * Fetch the association data from the source, fail ungracefully - the dev\n * should have this configured correctly.\n *\n * Fetch current associations if a post_id has been supplied\n */", "if", "(", "$", "post_id", ")", "{", "$", "oDb", "->", "where", "(", "'post_id'", ",", "$", "post_id", ")", ";", "$", "assoc", "->", "current", "=", "$", "oDb", "->", "get", "(", "$", "assoc", "->", "target", ")", "->", "result", "(", ")", ";", "}", "else", "{", "$", "assoc", "->", "current", "=", "array", "(", ")", ";", "}", "// Fetch the raw data", "$", "oDb", "->", "select", "(", "$", "assoc", "->", "source", "->", "id", ".", "' id, '", ".", "$", "assoc", "->", "source", "->", "label", ".", "' label'", ")", ";", "$", "oDb", "->", "order_by", "(", "'label'", ")", ";", "if", "(", "isset", "(", "$", "assoc", "->", "source", "->", "where", ")", "&&", "$", "assoc", "->", "source", "->", "where", ")", "{", "$", "oDb", "->", "where", "(", "$", "assoc", "->", "source", "->", "where", ")", ";", "}", "$", "assoc", "->", "data", "=", "$", "oDb", "->", "get", "(", "$", "assoc", "->", "source", "->", "table", ")", "->", "result", "(", ")", ";", "}", "return", "$", "_associations", ";", "}" ]
Fetch all the associations for a particular post @param int $post_id The ID f the post @return array
[ "Fetch", "all", "the", "associations", "for", "a", "particular", "post" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/blog/models/blog_model.php#L77-L121
train
nails/module-blog
blog/models/blog_model.php
NAILS_Blog_model.getBlogUrl
public function getBlogUrl($blogId) { if (isset($this->blogUrl[$blogId])) { return $this->blogUrl[$blogId]; } else { $url = appSetting('url', 'blog-' . $blogId); $url = $url ? $url : 'blog/'; $url = site_url($url); $this->blogUrl[$blogId] = $url; return $this->blogUrl[$blogId]; } }
php
public function getBlogUrl($blogId) { if (isset($this->blogUrl[$blogId])) { return $this->blogUrl[$blogId]; } else { $url = appSetting('url', 'blog-' . $blogId); $url = $url ? $url : 'blog/'; $url = site_url($url); $this->blogUrl[$blogId] = $url; return $this->blogUrl[$blogId]; } }
[ "public", "function", "getBlogUrl", "(", "$", "blogId", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "blogUrl", "[", "$", "blogId", "]", ")", ")", "{", "return", "$", "this", "->", "blogUrl", "[", "$", "blogId", "]", ";", "}", "else", "{", "$", "url", "=", "appSetting", "(", "'url'", ",", "'blog-'", ".", "$", "blogId", ")", ";", "$", "url", "=", "$", "url", "?", "$", "url", ":", "'blog/'", ";", "$", "url", "=", "site_url", "(", "$", "url", ")", ";", "$", "this", "->", "blogUrl", "[", "$", "blogId", "]", "=", "$", "url", ";", "return", "$", "this", "->", "blogUrl", "[", "$", "blogId", "]", ";", "}", "}" ]
Get the URL of a blog @param int $blogId The ID of the blog who's URL to get @return string
[ "Get", "the", "URL", "of", "a", "blog" ]
7b369c5209f4343fff7c7e2a22c237d5a95c8c24
https://github.com/nails/module-blog/blob/7b369c5209f4343fff7c7e2a22c237d5a95c8c24/blog/models/blog_model.php#L130-L146
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.compare
public function compare(Table $oldTable, Table $newTable) { $createdColumns = $this->getCreatedColumns($oldTable, $newTable); $alteredColumns = $this->getAlteredColumns($oldTable, $newTable); $droppedColumns = $this->getDroppedColumns($oldTable, $newTable); $this->detectRenamedColumns($createdColumns, $droppedColumns, $alteredColumns); return new TableDiff( $oldTable, $newTable, $createdColumns, $alteredColumns, $droppedColumns, $this->getCreatedPrimaryKey($oldTable, $newTable), $this->getDroppedPrimaryKey($oldTable, $newTable), $this->getCreatedForeignKeys($oldTable, $newTable), $this->getDroppedForeignKeys($oldTable, $newTable), $this->getCreatedIndexes($oldTable, $newTable), $this->getDroppedIndexes($oldTable, $newTable), $this->getCreatedChecks($oldTable, $newTable), $this->getDroppedChecks($oldTable, $newTable) ); }
php
public function compare(Table $oldTable, Table $newTable) { $createdColumns = $this->getCreatedColumns($oldTable, $newTable); $alteredColumns = $this->getAlteredColumns($oldTable, $newTable); $droppedColumns = $this->getDroppedColumns($oldTable, $newTable); $this->detectRenamedColumns($createdColumns, $droppedColumns, $alteredColumns); return new TableDiff( $oldTable, $newTable, $createdColumns, $alteredColumns, $droppedColumns, $this->getCreatedPrimaryKey($oldTable, $newTable), $this->getDroppedPrimaryKey($oldTable, $newTable), $this->getCreatedForeignKeys($oldTable, $newTable), $this->getDroppedForeignKeys($oldTable, $newTable), $this->getCreatedIndexes($oldTable, $newTable), $this->getDroppedIndexes($oldTable, $newTable), $this->getCreatedChecks($oldTable, $newTable), $this->getDroppedChecks($oldTable, $newTable) ); }
[ "public", "function", "compare", "(", "Table", "$", "oldTable", ",", "Table", "$", "newTable", ")", "{", "$", "createdColumns", "=", "$", "this", "->", "getCreatedColumns", "(", "$", "oldTable", ",", "$", "newTable", ")", ";", "$", "alteredColumns", "=", "$", "this", "->", "getAlteredColumns", "(", "$", "oldTable", ",", "$", "newTable", ")", ";", "$", "droppedColumns", "=", "$", "this", "->", "getDroppedColumns", "(", "$", "oldTable", ",", "$", "newTable", ")", ";", "$", "this", "->", "detectRenamedColumns", "(", "$", "createdColumns", ",", "$", "droppedColumns", ",", "$", "alteredColumns", ")", ";", "return", "new", "TableDiff", "(", "$", "oldTable", ",", "$", "newTable", ",", "$", "createdColumns", ",", "$", "alteredColumns", ",", "$", "droppedColumns", ",", "$", "this", "->", "getCreatedPrimaryKey", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getDroppedPrimaryKey", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getCreatedForeignKeys", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getDroppedForeignKeys", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getCreatedIndexes", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getDroppedIndexes", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getCreatedChecks", "(", "$", "oldTable", ",", "$", "newTable", ")", ",", "$", "this", "->", "getDroppedChecks", "(", "$", "oldTable", ",", "$", "newTable", ")", ")", ";", "}" ]
Compares two tables. @param \Fridge\DBAL\Schema\Table $oldTable The old table. @param \Fridge\DBAL\Schema\Table $newTable The new table. @return \Fridge\DBAL\Schema\Diff\TableDiff The difference between the two tables.
[ "Compares", "two", "tables", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L47-L70
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.comparePrimaryKeys
public function comparePrimaryKeys(PrimaryKey $oldPrimaryKey, PrimaryKey $newPrimaryKey) { return ($oldPrimaryKey->getName() !== $newPrimaryKey->getName()) || ($oldPrimaryKey->getColumnNames() !== $newPrimaryKey->getColumnNames()); }
php
public function comparePrimaryKeys(PrimaryKey $oldPrimaryKey, PrimaryKey $newPrimaryKey) { return ($oldPrimaryKey->getName() !== $newPrimaryKey->getName()) || ($oldPrimaryKey->getColumnNames() !== $newPrimaryKey->getColumnNames()); }
[ "public", "function", "comparePrimaryKeys", "(", "PrimaryKey", "$", "oldPrimaryKey", ",", "PrimaryKey", "$", "newPrimaryKey", ")", "{", "return", "(", "$", "oldPrimaryKey", "->", "getName", "(", ")", "!==", "$", "newPrimaryKey", "->", "getName", "(", ")", ")", "||", "(", "$", "oldPrimaryKey", "->", "getColumnNames", "(", ")", "!==", "$", "newPrimaryKey", "->", "getColumnNames", "(", ")", ")", ";", "}" ]
Compares two primary keys. @param \Fridge\DBAL\Schema\PrimaryKey $oldPrimaryKey The old primary key. @param \Fridge\DBAL\Schema\PrimaryKey $newPrimaryKey The new primary key. @return boolean TRUE if the primary keys are different else FALSE.
[ "Compares", "two", "primary", "keys", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L80-L84
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.compareForeignKeys
public function compareForeignKeys(ForeignKey $oldForeignKey, ForeignKey $newForeignKey) { return ($oldForeignKey->getName() !== $newForeignKey->getName()) || ($oldForeignKey->getLocalColumnNames() !== $newForeignKey->getLocalColumnNames()) || ($oldForeignKey->getForeignTableName() !== $newForeignKey->getForeignTableName()) || ($oldForeignKey->getForeignColumnNames() !== $newForeignKey->getForeignColumnNames()) || ($oldForeignKey->getOnDelete() !== $newForeignKey->getOnDelete()) || ($oldForeignKey->getOnUpdate() !== $newForeignKey->getOnUpdate()); }
php
public function compareForeignKeys(ForeignKey $oldForeignKey, ForeignKey $newForeignKey) { return ($oldForeignKey->getName() !== $newForeignKey->getName()) || ($oldForeignKey->getLocalColumnNames() !== $newForeignKey->getLocalColumnNames()) || ($oldForeignKey->getForeignTableName() !== $newForeignKey->getForeignTableName()) || ($oldForeignKey->getForeignColumnNames() !== $newForeignKey->getForeignColumnNames()) || ($oldForeignKey->getOnDelete() !== $newForeignKey->getOnDelete()) || ($oldForeignKey->getOnUpdate() !== $newForeignKey->getOnUpdate()); }
[ "public", "function", "compareForeignKeys", "(", "ForeignKey", "$", "oldForeignKey", ",", "ForeignKey", "$", "newForeignKey", ")", "{", "return", "(", "$", "oldForeignKey", "->", "getName", "(", ")", "!==", "$", "newForeignKey", "->", "getName", "(", ")", ")", "||", "(", "$", "oldForeignKey", "->", "getLocalColumnNames", "(", ")", "!==", "$", "newForeignKey", "->", "getLocalColumnNames", "(", ")", ")", "||", "(", "$", "oldForeignKey", "->", "getForeignTableName", "(", ")", "!==", "$", "newForeignKey", "->", "getForeignTableName", "(", ")", ")", "||", "(", "$", "oldForeignKey", "->", "getForeignColumnNames", "(", ")", "!==", "$", "newForeignKey", "->", "getForeignColumnNames", "(", ")", ")", "||", "(", "$", "oldForeignKey", "->", "getOnDelete", "(", ")", "!==", "$", "newForeignKey", "->", "getOnDelete", "(", ")", ")", "||", "(", "$", "oldForeignKey", "->", "getOnUpdate", "(", ")", "!==", "$", "newForeignKey", "->", "getOnUpdate", "(", ")", ")", ";", "}" ]
Compares two foreign keys. @param \Fridge\DBAL\Schema\ForeignKey $oldForeignKey The old foreign key. @param \Fridge\DBAL\Schema\ForeignKey $newForeignKey The new foreign key. @return boolean TRUE if foreign keys are different else FALSE.
[ "Compares", "two", "foreign", "keys", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L94-L102
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.compareIndexes
public function compareIndexes(Index $oldIndex, Index $newIndex) { return ($oldIndex->getName() !== $newIndex->getName()) || ($oldIndex->getColumnNames() !== $newIndex->getColumnNames()) || ($oldIndex->isUnique() !== $newIndex->isUnique()); }
php
public function compareIndexes(Index $oldIndex, Index $newIndex) { return ($oldIndex->getName() !== $newIndex->getName()) || ($oldIndex->getColumnNames() !== $newIndex->getColumnNames()) || ($oldIndex->isUnique() !== $newIndex->isUnique()); }
[ "public", "function", "compareIndexes", "(", "Index", "$", "oldIndex", ",", "Index", "$", "newIndex", ")", "{", "return", "(", "$", "oldIndex", "->", "getName", "(", ")", "!==", "$", "newIndex", "->", "getName", "(", ")", ")", "||", "(", "$", "oldIndex", "->", "getColumnNames", "(", ")", "!==", "$", "newIndex", "->", "getColumnNames", "(", ")", ")", "||", "(", "$", "oldIndex", "->", "isUnique", "(", ")", "!==", "$", "newIndex", "->", "isUnique", "(", ")", ")", ";", "}" ]
Compares two indexes. @param \Fridge\DBAL\Schema\Index $oldIndex The old index. @param \Fridge\DBAL\Schema\Index $newIndex The new index. @return boolean TRUE if indexes are different else FALSE.
[ "Compares", "two", "indexes", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L112-L117
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.compareChecks
public function compareChecks(Check $oldCheck, Check $newCheck) { return ($oldCheck->getName() !== $newCheck->getName()) || ($oldCheck->getDefinition() !== $newCheck->getDefinition()); }
php
public function compareChecks(Check $oldCheck, Check $newCheck) { return ($oldCheck->getName() !== $newCheck->getName()) || ($oldCheck->getDefinition() !== $newCheck->getDefinition()); }
[ "public", "function", "compareChecks", "(", "Check", "$", "oldCheck", ",", "Check", "$", "newCheck", ")", "{", "return", "(", "$", "oldCheck", "->", "getName", "(", ")", "!==", "$", "newCheck", "->", "getName", "(", ")", ")", "||", "(", "$", "oldCheck", "->", "getDefinition", "(", ")", "!==", "$", "newCheck", "->", "getDefinition", "(", ")", ")", ";", "}" ]
Compares two checks. @param \Fridge\DBAL\Schema\Check $oldCheck The old check. @param \Fridge\DBAL\Schema\Check $newCheck The new check. @return boolean TRUE if checks are different else FALSE.
[ "Compares", "two", "checks", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L127-L131
train
fridge-project/dbal
src/Fridge/DBAL/Schema/Comparator/TableComparator.php
TableComparator.detectRenamedColumns
private function detectRenamedColumns(array &$createdColumns, array &$droppedColumns, array &$alteredColumns) { foreach ($createdColumns as $createdIndex => $createdColumn) { foreach ($droppedColumns as $droppedIndex => $droppedColumn) { $columnDiff = $this->columnComparator->compare($droppedColumn, $createdColumn); if ($columnDiff->hasNameDifferenceOnly()) { $alteredColumns[] = $columnDiff; unset($createdColumns[$createdIndex]); unset($droppedColumns[$droppedIndex]); break; } } } }
php
private function detectRenamedColumns(array &$createdColumns, array &$droppedColumns, array &$alteredColumns) { foreach ($createdColumns as $createdIndex => $createdColumn) { foreach ($droppedColumns as $droppedIndex => $droppedColumn) { $columnDiff = $this->columnComparator->compare($droppedColumn, $createdColumn); if ($columnDiff->hasNameDifferenceOnly()) { $alteredColumns[] = $columnDiff; unset($createdColumns[$createdIndex]); unset($droppedColumns[$droppedIndex]); break; } } } }
[ "private", "function", "detectRenamedColumns", "(", "array", "&", "$", "createdColumns", ",", "array", "&", "$", "droppedColumns", ",", "array", "&", "$", "alteredColumns", ")", "{", "foreach", "(", "$", "createdColumns", "as", "$", "createdIndex", "=>", "$", "createdColumn", ")", "{", "foreach", "(", "$", "droppedColumns", "as", "$", "droppedIndex", "=>", "$", "droppedColumn", ")", "{", "$", "columnDiff", "=", "$", "this", "->", "columnComparator", "->", "compare", "(", "$", "droppedColumn", ",", "$", "createdColumn", ")", ";", "if", "(", "$", "columnDiff", "->", "hasNameDifferenceOnly", "(", ")", ")", "{", "$", "alteredColumns", "[", "]", "=", "$", "columnDiff", ";", "unset", "(", "$", "createdColumns", "[", "$", "createdIndex", "]", ")", ";", "unset", "(", "$", "droppedColumns", "[", "$", "droppedIndex", "]", ")", ";", "break", ";", "}", "}", "}", "}" ]
Detects and rewrites renamed columns. @param array &$createdColumns The create columns. @param array &$droppedColumns The dropped columns. @param array &$alteredColumns The altered columns.
[ "Detects", "and", "rewrites", "renamed", "columns", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/Schema/Comparator/TableComparator.php#L207-L223
train
itkg/core
src/Itkg/Core/Command/DatabaseUpdate/Query.php
Query.parse
protected function parse() { $query = preg_replace('/OR\s+REPLACE/', '', $this->value); /** * @TODO : Grant parse */ if (preg_match( '/(CREATE|UPDATE|DELETE|ALTER|INSERT|DROP|SELECT|GRANT)\s+(SEQUENCE|INDEX|SYNONYM|TABLE|INTO|FROM|VIEW|)\s*([a-zA-Z-_]*)\s*/im', $query, $matches ) ) { $this->type = trim(strtolower($matches[1])); if (in_array($this->type, array('create', 'drop'))) { $this->type = strtolower(trim(sprintf('%s_%s', $matches[1], $matches[2]))); } $this->data = array( 'identifier' => $matches[3] ); } }
php
protected function parse() { $query = preg_replace('/OR\s+REPLACE/', '', $this->value); /** * @TODO : Grant parse */ if (preg_match( '/(CREATE|UPDATE|DELETE|ALTER|INSERT|DROP|SELECT|GRANT)\s+(SEQUENCE|INDEX|SYNONYM|TABLE|INTO|FROM|VIEW|)\s*([a-zA-Z-_]*)\s*/im', $query, $matches ) ) { $this->type = trim(strtolower($matches[1])); if (in_array($this->type, array('create', 'drop'))) { $this->type = strtolower(trim(sprintf('%s_%s', $matches[1], $matches[2]))); } $this->data = array( 'identifier' => $matches[3] ); } }
[ "protected", "function", "parse", "(", ")", "{", "$", "query", "=", "preg_replace", "(", "'/OR\\s+REPLACE/'", ",", "''", ",", "$", "this", "->", "value", ")", ";", "/**\n * @TODO : Grant parse\n */", "if", "(", "preg_match", "(", "'/(CREATE|UPDATE|DELETE|ALTER|INSERT|DROP|SELECT|GRANT)\\s+(SEQUENCE|INDEX|SYNONYM|TABLE|INTO|FROM|VIEW|)\\s*([a-zA-Z-_]*)\\s*/im'", ",", "$", "query", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "type", "=", "trim", "(", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ")", ";", "if", "(", "in_array", "(", "$", "this", "->", "type", ",", "array", "(", "'create'", ",", "'drop'", ")", ")", ")", "{", "$", "this", "->", "type", "=", "strtolower", "(", "trim", "(", "sprintf", "(", "'%s_%s'", ",", "$", "matches", "[", "1", "]", ",", "$", "matches", "[", "2", "]", ")", ")", ")", ";", "}", "$", "this", "->", "data", "=", "array", "(", "'identifier'", "=>", "$", "matches", "[", "3", "]", ")", ";", "}", "}" ]
Parse query Extract type & extra data
[ "Parse", "query", "Extract", "type", "&", "extra", "data" ]
e5e4efb05feb4d23b0df41f2b21fd095103e593b
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/DatabaseUpdate/Query.php#L87-L108
train
sndsgd/http
src/http/data/decoder/DecoderOptions.php
DecoderOptions.getMaxFileSize
public function getMaxFileSize(): int { if ($this->maxFileSize === null) { $value = ini_get("upload_max_filesize"); $units = "BKMGT"; $unit = preg_replace("/[^$units]/i", "", $value); $value = floatval($value); if ($unit) { $value *= pow(1024, stripos($units, $unit[0])); } $this->maxFileSize = (int) $value; } return $this->maxFileSize; }
php
public function getMaxFileSize(): int { if ($this->maxFileSize === null) { $value = ini_get("upload_max_filesize"); $units = "BKMGT"; $unit = preg_replace("/[^$units]/i", "", $value); $value = floatval($value); if ($unit) { $value *= pow(1024, stripos($units, $unit[0])); } $this->maxFileSize = (int) $value; } return $this->maxFileSize; }
[ "public", "function", "getMaxFileSize", "(", ")", ":", "int", "{", "if", "(", "$", "this", "->", "maxFileSize", "===", "null", ")", "{", "$", "value", "=", "ini_get", "(", "\"upload_max_filesize\"", ")", ";", "$", "units", "=", "\"BKMGT\"", ";", "$", "unit", "=", "preg_replace", "(", "\"/[^$units]/i\"", ",", "\"\"", ",", "$", "value", ")", ";", "$", "value", "=", "floatval", "(", "$", "value", ")", ";", "if", "(", "$", "unit", ")", "{", "$", "value", "*=", "pow", "(", "1024", ",", "stripos", "(", "$", "units", ",", "$", "unit", "[", "0", "]", ")", ")", ";", "}", "$", "this", "->", "maxFileSize", "=", "(", "int", ")", "$", "value", ";", "}", "return", "$", "this", "->", "maxFileSize", ";", "}" ]
Retrieve the `upload_max_filesize` ini setting @return int
[ "Retrieve", "the", "upload_max_filesize", "ini", "setting" ]
e7f82010a66c6d3241a24ea82baf4593130c723b
https://github.com/sndsgd/http/blob/e7f82010a66c6d3241a24ea82baf4593130c723b/src/http/data/decoder/DecoderOptions.php#L59-L72
train
rawphp/RawConsole
src/RawPHP/RawConsole/Command.php
Command.init
public function init( $config = NULL ) { $option = new Option(); $option->shortCode = 'h'; $option->longCode = 'help'; $option->isOptional = TRUE; $option->type = Type::BOOLEAN; $option->shortDescription = 'Show the help menu'; $this->options[ ] = $option; $option = new Option(); $option->shortCode = 'v'; $option->longCode = 'verbose'; $option->isOptional = TRUE; $option->type = Type::BOOLEAN; $option->shortDescription = 'Show detailed log'; $this->options[ ] = $option; }
php
public function init( $config = NULL ) { $option = new Option(); $option->shortCode = 'h'; $option->longCode = 'help'; $option->isOptional = TRUE; $option->type = Type::BOOLEAN; $option->shortDescription = 'Show the help menu'; $this->options[ ] = $option; $option = new Option(); $option->shortCode = 'v'; $option->longCode = 'verbose'; $option->isOptional = TRUE; $option->type = Type::BOOLEAN; $option->shortDescription = 'Show detailed log'; $this->options[ ] = $option; }
[ "public", "function", "init", "(", "$", "config", "=", "NULL", ")", "{", "$", "option", "=", "new", "Option", "(", ")", ";", "$", "option", "->", "shortCode", "=", "'h'", ";", "$", "option", "->", "longCode", "=", "'help'", ";", "$", "option", "->", "isOptional", "=", "TRUE", ";", "$", "option", "->", "type", "=", "Type", "::", "BOOLEAN", ";", "$", "option", "->", "shortDescription", "=", "'Show the help menu'", ";", "$", "this", "->", "options", "[", "]", "=", "$", "option", ";", "$", "option", "=", "new", "Option", "(", ")", ";", "$", "option", "->", "shortCode", "=", "'v'", ";", "$", "option", "->", "longCode", "=", "'verbose'", ";", "$", "option", "->", "isOptional", "=", "TRUE", ";", "$", "option", "->", "type", "=", "Type", "::", "BOOLEAN", ";", "$", "option", "->", "shortDescription", "=", "'Show detailed log'", ";", "$", "this", "->", "options", "[", "]", "=", "$", "option", ";", "}" ]
This method adds the help and verbose options to the command. You can optionally remove these options by clearing the command options array before adding your own commands. @param array $config optional configuration array
[ "This", "method", "adds", "the", "help", "and", "verbose", "options", "to", "the", "command", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Command.php#L98-L117
train
rawphp/RawConsole
src/RawPHP/RawConsole/Command.php
Command.removeOption
public function removeOption( $longCode ) { $retVal = FALSE; $i = 0; foreach ( $this->options as $option ) { if ( $longCode === $option->longCode ) { break; } $i++; } if ( $i !== count( $this->options ) ) { unset( $this->options[ $i ] ); $retVal = TRUE; } return $retVal; }
php
public function removeOption( $longCode ) { $retVal = FALSE; $i = 0; foreach ( $this->options as $option ) { if ( $longCode === $option->longCode ) { break; } $i++; } if ( $i !== count( $this->options ) ) { unset( $this->options[ $i ] ); $retVal = TRUE; } return $retVal; }
[ "public", "function", "removeOption", "(", "$", "longCode", ")", "{", "$", "retVal", "=", "FALSE", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "this", "->", "options", "as", "$", "option", ")", "{", "if", "(", "$", "longCode", "===", "$", "option", "->", "longCode", ")", "{", "break", ";", "}", "$", "i", "++", ";", "}", "if", "(", "$", "i", "!==", "count", "(", "$", "this", "->", "options", ")", ")", "{", "unset", "(", "$", "this", "->", "options", "[", "$", "i", "]", ")", ";", "$", "retVal", "=", "TRUE", ";", "}", "return", "$", "retVal", ";", "}" ]
Removes an option by its long code. @param string $longCode option long code @return bool TRUE on success, FALSE on failure
[ "Removes", "an", "option", "by", "its", "long", "code", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Command.php#L150-L174
train
rawphp/RawConsole
src/RawPHP/RawConsole/Command.php
Command.getOption
public static function getOption( Command $command, $longCode ) { foreach ( $command->options as $op ) { if ( '--' === substr( $longCode, 0, 2 ) ) { $longCode = substr( $longCode, 2 ); } elseif ( '-' === substr( $longCode, 0, 1 ) ) { $longCode = substr( $longCode, 1 ); } if ( $op->shortCode === $longCode || $op->longCode === $longCode ) { return $op; } } throw new CommandException( 'Unable to find option: ' . $longCode ); }
php
public static function getOption( Command $command, $longCode ) { foreach ( $command->options as $op ) { if ( '--' === substr( $longCode, 0, 2 ) ) { $longCode = substr( $longCode, 2 ); } elseif ( '-' === substr( $longCode, 0, 1 ) ) { $longCode = substr( $longCode, 1 ); } if ( $op->shortCode === $longCode || $op->longCode === $longCode ) { return $op; } } throw new CommandException( 'Unable to find option: ' . $longCode ); }
[ "public", "static", "function", "getOption", "(", "Command", "$", "command", ",", "$", "longCode", ")", "{", "foreach", "(", "$", "command", "->", "options", "as", "$", "op", ")", "{", "if", "(", "'--'", "===", "substr", "(", "$", "longCode", ",", "0", ",", "2", ")", ")", "{", "$", "longCode", "=", "substr", "(", "$", "longCode", ",", "2", ")", ";", "}", "elseif", "(", "'-'", "===", "substr", "(", "$", "longCode", ",", "0", ",", "1", ")", ")", "{", "$", "longCode", "=", "substr", "(", "$", "longCode", ",", "1", ")", ";", "}", "if", "(", "$", "op", "->", "shortCode", "===", "$", "longCode", "||", "$", "op", "->", "longCode", "===", "$", "longCode", ")", "{", "return", "$", "op", ";", "}", "}", "throw", "new", "CommandException", "(", "'Unable to find option: '", ".", "$", "longCode", ")", ";", "}" ]
Gets an option either by short or long code. @param Command $command the command @param string $longCode the command name (code) @return Option the option @throws CommandException if option is not found
[ "Gets", "an", "option", "either", "by", "short", "or", "long", "code", "." ]
602bedd10f24962305a7ac1979ed326852f4224a
https://github.com/rawphp/RawConsole/blob/602bedd10f24962305a7ac1979ed326852f4224a/src/RawPHP/RawConsole/Command.php#L186-L206
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.getParentTemplateFilename
public function getParentTemplateFilename() { if(empty($this->parentTemplateFilename)) { if(preg_match($this->extendRex, $this->bufferInstance->__rawContents, $matches)) { $this->parentTemplateFilename = $matches[1]; } } return $this->parentTemplateFilename; }
php
public function getParentTemplateFilename() { if(empty($this->parentTemplateFilename)) { if(preg_match($this->extendRex, $this->bufferInstance->__rawContents, $matches)) { $this->parentTemplateFilename = $matches[1]; } } return $this->parentTemplateFilename; }
[ "public", "function", "getParentTemplateFilename", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "parentTemplateFilename", ")", ")", "{", "if", "(", "preg_match", "(", "$", "this", "->", "extendRex", ",", "$", "this", "->", "bufferInstance", "->", "__rawContents", ",", "$", "matches", ")", ")", "{", "$", "this", "->", "parentTemplateFilename", "=", "$", "matches", "[", "1", "]", ";", "}", "}", "return", "$", "this", "->", "parentTemplateFilename", ";", "}" ]
get filename of parent template @return string
[ "get", "filename", "of", "parent", "template" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L179-L192
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.assign
public function assign($var, $value = null) { $invalidProperties = ['__rawContents']; if(is_array($var)) { foreach($var as $k => $v) { if(in_array($k, $invalidProperties)) { throw new SimpleTemplateException("Tried to assign invalid property '%s'", $k); } $this->bufferInstance->$k = $v; } return $this; } if(in_array($var, $invalidProperties)) { throw new SimpleTemplateException("Tried to assign invalid property '%s'", $var); } $this->bufferInstance->$var = $value; return $this; }
php
public function assign($var, $value = null) { $invalidProperties = ['__rawContents']; if(is_array($var)) { foreach($var as $k => $v) { if(in_array($k, $invalidProperties)) { throw new SimpleTemplateException("Tried to assign invalid property '%s'", $k); } $this->bufferInstance->$k = $v; } return $this; } if(in_array($var, $invalidProperties)) { throw new SimpleTemplateException("Tried to assign invalid property '%s'", $var); } $this->bufferInstance->$var = $value; return $this; }
[ "public", "function", "assign", "(", "$", "var", ",", "$", "value", "=", "null", ")", "{", "$", "invalidProperties", "=", "[", "'__rawContents'", "]", ";", "if", "(", "is_array", "(", "$", "var", ")", ")", "{", "foreach", "(", "$", "var", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "in_array", "(", "$", "k", ",", "$", "invalidProperties", ")", ")", "{", "throw", "new", "SimpleTemplateException", "(", "\"Tried to assign invalid property '%s'\"", ",", "$", "k", ")", ";", "}", "$", "this", "->", "bufferInstance", "->", "$", "k", "=", "$", "v", ";", "}", "return", "$", "this", ";", "}", "if", "(", "in_array", "(", "$", "var", ",", "$", "invalidProperties", ")", ")", "{", "throw", "new", "SimpleTemplateException", "(", "\"Tried to assign invalid property '%s'\"", ",", "$", "var", ")", ";", "}", "$", "this", "->", "bufferInstance", "->", "$", "var", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
assign value to variable, which is then available within template @param string | array $var @param mixed $value @return SimpleTemplate @throws SimpleTemplateException
[ "assign", "value", "to", "variable", "which", "is", "then", "available", "within", "template" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L227-L249
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.blockFilter
public function blockFilter($filterId) { if(!in_array($filterId, $this->blockedFilters)) { $this->blockedFilters[] = $filterId; } return $this; }
php
public function blockFilter($filterId) { if(!in_array($filterId, $this->blockedFilters)) { $this->blockedFilters[] = $filterId; } return $this; }
[ "public", "function", "blockFilter", "(", "$", "filterId", ")", "{", "if", "(", "!", "in_array", "(", "$", "filterId", ",", "$", "this", "->", "blockedFilters", ")", ")", "{", "$", "this", "->", "blockedFilters", "[", "]", "=", "$", "filterId", ";", "}", "return", "$", "this", ";", "}" ]
block a pre-configured filter @param string $filterId @return $this
[ "block", "a", "pre", "-", "configured", "filter" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L271-L279
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.display
public function display($defaultFilters = null) { $this->extend(); $this->fillBuffer(); // check whether pre-configured filters are already in place if(is_null($defaultFilters)) { // add default filters $this->defaultFilters = [ new AnchorHref(), new ImageCache(), // new AssetsPath() ]; if(!$this->ignoreLocales) { $this->defaultFilters[] = new LocalizedPhrases(); } } else { $this->defaultFilters = $defaultFilters; if(!$this->ignoreLocales) { // check whether adding a localization filter is necessary $found = false; foreach($this->defaultFilters as $filter) { if($filter instanceof LocalizedPhrases) { $found = true; break; } } if(!$found) { $this->defaultFilters[] = new LocalizedPhrases(); } } } // add configured filters if($templatingConfig = Application::getInstance()->getConfig()->templating) { foreach($templatingConfig->filters as $id => $filter) { if(!in_array($id, $this->blockedFilters)) { // load class file $instance = new $filter['class'](); // check whether instance implements FilterInterface if (!$instance instanceof SimpleTemplateFilterInterface) { throw new SimpleTemplateException(sprintf("Template filter '%s' (class %s) does not implement the SimpleTemplateFilterInterface.", $id, $filter['class'])); } $this->defaultFilters[] = $instance; } } } $this->applyFilters(); return $this->contents; }
php
public function display($defaultFilters = null) { $this->extend(); $this->fillBuffer(); // check whether pre-configured filters are already in place if(is_null($defaultFilters)) { // add default filters $this->defaultFilters = [ new AnchorHref(), new ImageCache(), // new AssetsPath() ]; if(!$this->ignoreLocales) { $this->defaultFilters[] = new LocalizedPhrases(); } } else { $this->defaultFilters = $defaultFilters; if(!$this->ignoreLocales) { // check whether adding a localization filter is necessary $found = false; foreach($this->defaultFilters as $filter) { if($filter instanceof LocalizedPhrases) { $found = true; break; } } if(!$found) { $this->defaultFilters[] = new LocalizedPhrases(); } } } // add configured filters if($templatingConfig = Application::getInstance()->getConfig()->templating) { foreach($templatingConfig->filters as $id => $filter) { if(!in_array($id, $this->blockedFilters)) { // load class file $instance = new $filter['class'](); // check whether instance implements FilterInterface if (!$instance instanceof SimpleTemplateFilterInterface) { throw new SimpleTemplateException(sprintf("Template filter '%s' (class %s) does not implement the SimpleTemplateFilterInterface.", $id, $filter['class'])); } $this->defaultFilters[] = $instance; } } } $this->applyFilters(); return $this->contents; }
[ "public", "function", "display", "(", "$", "defaultFilters", "=", "null", ")", "{", "$", "this", "->", "extend", "(", ")", ";", "$", "this", "->", "fillBuffer", "(", ")", ";", "// check whether pre-configured filters are already in place", "if", "(", "is_null", "(", "$", "defaultFilters", ")", ")", "{", "// add default filters", "$", "this", "->", "defaultFilters", "=", "[", "new", "AnchorHref", "(", ")", ",", "new", "ImageCache", "(", ")", ",", "// new AssetsPath()", "]", ";", "if", "(", "!", "$", "this", "->", "ignoreLocales", ")", "{", "$", "this", "->", "defaultFilters", "[", "]", "=", "new", "LocalizedPhrases", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "defaultFilters", "=", "$", "defaultFilters", ";", "if", "(", "!", "$", "this", "->", "ignoreLocales", ")", "{", "// check whether adding a localization filter is necessary", "$", "found", "=", "false", ";", "foreach", "(", "$", "this", "->", "defaultFilters", "as", "$", "filter", ")", "{", "if", "(", "$", "filter", "instanceof", "LocalizedPhrases", ")", "{", "$", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "$", "found", ")", "{", "$", "this", "->", "defaultFilters", "[", "]", "=", "new", "LocalizedPhrases", "(", ")", ";", "}", "}", "}", "// add configured filters", "if", "(", "$", "templatingConfig", "=", "Application", "::", "getInstance", "(", ")", "->", "getConfig", "(", ")", "->", "templating", ")", "{", "foreach", "(", "$", "templatingConfig", "->", "filters", "as", "$", "id", "=>", "$", "filter", ")", "{", "if", "(", "!", "in_array", "(", "$", "id", ",", "$", "this", "->", "blockedFilters", ")", ")", "{", "// load class file", "$", "instance", "=", "new", "$", "filter", "[", "'class'", "]", "(", ")", ";", "// check whether instance implements FilterInterface", "if", "(", "!", "$", "instance", "instanceof", "SimpleTemplateFilterInterface", ")", "{", "throw", "new", "SimpleTemplateException", "(", "sprintf", "(", "\"Template filter '%s' (class %s) does not implement the SimpleTemplateFilterInterface.\"", ",", "$", "id", ",", "$", "filter", "[", "'class'", "]", ")", ")", ";", "}", "$", "this", "->", "defaultFilters", "[", "]", "=", "$", "instance", ";", "}", "}", "}", "$", "this", "->", "applyFilters", "(", ")", ";", "return", "$", "this", "->", "contents", ";", "}" ]
output parsed template @param SimpleTemplateFilterInterface [] @return string @throws SimpleTemplateException @throws \vxPHP\Application\Exception\ApplicationException
[ "output", "parsed", "template" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L289-L366
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.extend
private function extend() { if(preg_match($this->extendRex, $this->bufferInstance->__rawContents, $matches)) { $blockRegExp = '~<!--\s*\{\s*block\s*:\s*' . $matches[2] . '\s*\}\s*-->~'; $extendedContent = file_get_contents(Application::getInstance()->getRootPath() . (defined('TPL_PATH') ? str_replace('/', DIRECTORY_SEPARATOR, ltrim(TPL_PATH, '/')) : '') . $matches[1]); if(preg_match($blockRegExp, $extendedContent)) { $this->bufferInstance->__rawContents = preg_replace( $blockRegExp, preg_replace( $this->extendRex, '', $this->bufferInstance->__rawContents ), $extendedContent ); } else { throw new SimpleTemplateException("Could not extend with '{$matches[1]}' at '{$matches[2]}'.", SimpleTemplateException::TEMPLATE_INVALID_NESTING); } } }
php
private function extend() { if(preg_match($this->extendRex, $this->bufferInstance->__rawContents, $matches)) { $blockRegExp = '~<!--\s*\{\s*block\s*:\s*' . $matches[2] . '\s*\}\s*-->~'; $extendedContent = file_get_contents(Application::getInstance()->getRootPath() . (defined('TPL_PATH') ? str_replace('/', DIRECTORY_SEPARATOR, ltrim(TPL_PATH, '/')) : '') . $matches[1]); if(preg_match($blockRegExp, $extendedContent)) { $this->bufferInstance->__rawContents = preg_replace( $blockRegExp, preg_replace( $this->extendRex, '', $this->bufferInstance->__rawContents ), $extendedContent ); } else { throw new SimpleTemplateException("Could not extend with '{$matches[1]}' at '{$matches[2]}'.", SimpleTemplateException::TEMPLATE_INVALID_NESTING); } } }
[ "private", "function", "extend", "(", ")", "{", "if", "(", "preg_match", "(", "$", "this", "->", "extendRex", ",", "$", "this", "->", "bufferInstance", "->", "__rawContents", ",", "$", "matches", ")", ")", "{", "$", "blockRegExp", "=", "'~<!--\\s*\\{\\s*block\\s*:\\s*'", ".", "$", "matches", "[", "2", "]", ".", "'\\s*\\}\\s*-->~'", ";", "$", "extendedContent", "=", "file_get_contents", "(", "Application", "::", "getInstance", "(", ")", "->", "getRootPath", "(", ")", ".", "(", "defined", "(", "'TPL_PATH'", ")", "?", "str_replace", "(", "'/'", ",", "DIRECTORY_SEPARATOR", ",", "ltrim", "(", "TPL_PATH", ",", "'/'", ")", ")", ":", "''", ")", ".", "$", "matches", "[", "1", "]", ")", ";", "if", "(", "preg_match", "(", "$", "blockRegExp", ",", "$", "extendedContent", ")", ")", "{", "$", "this", "->", "bufferInstance", "->", "__rawContents", "=", "preg_replace", "(", "$", "blockRegExp", ",", "preg_replace", "(", "$", "this", "->", "extendRex", ",", "''", ",", "$", "this", "->", "bufferInstance", "->", "__rawContents", ")", ",", "$", "extendedContent", ")", ";", "}", "else", "{", "throw", "new", "SimpleTemplateException", "(", "\"Could not extend with '{$matches[1]}' at '{$matches[2]}'.\"", ",", "SimpleTemplateException", "::", "TEMPLATE_INVALID_NESTING", ")", ";", "}", "}", "}" ]
allow extension of a parent template with current template searches in current rawContents for <!-- { extend: parent_template.php @ content_block } --> and in template to extend for <!-- { block: content_block } --> current rawContents is then replaced by parent rawContents with current rawContents filled in @throws SimpleTemplateException @throws \vxPHP\Application\Exception\ApplicationException
[ "allow", "extension", "of", "a", "parent", "template", "with", "current", "template" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L381-L407
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.applyFilters
private function applyFilters() { // handle default and pre-configured filters first foreach($this->defaultFilters as $f) { $f->apply($this->contents); } // handle added custom filters last foreach($this->filters as $f) { $f->apply($this->contents); } }
php
private function applyFilters() { // handle default and pre-configured filters first foreach($this->defaultFilters as $f) { $f->apply($this->contents); } // handle added custom filters last foreach($this->filters as $f) { $f->apply($this->contents); } }
[ "private", "function", "applyFilters", "(", ")", "{", "// handle default and pre-configured filters first", "foreach", "(", "$", "this", "->", "defaultFilters", "as", "$", "f", ")", "{", "$", "f", "->", "apply", "(", "$", "this", "->", "contents", ")", ";", "}", "// handle added custom filters last", "foreach", "(", "$", "this", "->", "filters", "as", "$", "f", ")", "{", "$", "f", "->", "apply", "(", "$", "this", "->", "contents", ")", ";", "}", "}" ]
applies all stacked filters to template before output
[ "applies", "all", "stacked", "filters", "to", "template", "before", "output" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L412-L426
train
Vectrex/vxPHP
src/Template/SimpleTemplate.php
SimpleTemplate.fillBuffer
private function fillBuffer() { // wrap bufferInstance in closure to allow the use of $this in template $closure = function($outer) { ob_start(); /* @deprecated use $this when accessing assigned variables */ $tpl = $this; eval('?>' . $this->__rawContents); $outer->contents = ob_get_contents(); ob_end_clean(); }; $boundClosure = $closure->bindTo($this->bufferInstance); $boundClosure($this); }
php
private function fillBuffer() { // wrap bufferInstance in closure to allow the use of $this in template $closure = function($outer) { ob_start(); /* @deprecated use $this when accessing assigned variables */ $tpl = $this; eval('?>' . $this->__rawContents); $outer->contents = ob_get_contents(); ob_end_clean(); }; $boundClosure = $closure->bindTo($this->bufferInstance); $boundClosure($this); }
[ "private", "function", "fillBuffer", "(", ")", "{", "// wrap bufferInstance in closure to allow the use of $this in template", "$", "closure", "=", "function", "(", "$", "outer", ")", "{", "ob_start", "(", ")", ";", "/* @deprecated use $this when accessing assigned variables */", "$", "tpl", "=", "$", "this", ";", "eval", "(", "'?>'", ".", "$", "this", "->", "__rawContents", ")", ";", "$", "outer", "->", "contents", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "}", ";", "$", "boundClosure", "=", "$", "closure", "->", "bindTo", "(", "$", "this", "->", "bufferInstance", ")", ";", "$", "boundClosure", "(", "$", "this", ")", ";", "}" ]
fetches template file and evals content immediate output supressed by output buffering
[ "fetches", "template", "file", "and", "evals", "content", "immediate", "output", "supressed", "by", "output", "buffering" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Template/SimpleTemplate.php#L432-L453
train
fridge-project/dbal
src/Fridge/DBAL/SchemaManager/SQLCollector/DropTableSQLCollector.php
DropTableSQLCollector.collect
public function collect(Table $table) { foreach ($table->getForeignKeys() as $foreignKey) { $this->dropForeignKeyQueries = array_merge( $this->dropForeignKeyQueries, $this->platform->getDropForeignKeySQLQueries($foreignKey, $table->getName()) ); } $this->dropTableQueries = array_merge( $this->dropTableQueries, $this->platform->getDropTableSQLQueries($table) ); }
php
public function collect(Table $table) { foreach ($table->getForeignKeys() as $foreignKey) { $this->dropForeignKeyQueries = array_merge( $this->dropForeignKeyQueries, $this->platform->getDropForeignKeySQLQueries($foreignKey, $table->getName()) ); } $this->dropTableQueries = array_merge( $this->dropTableQueries, $this->platform->getDropTableSQLQueries($table) ); }
[ "public", "function", "collect", "(", "Table", "$", "table", ")", "{", "foreach", "(", "$", "table", "->", "getForeignKeys", "(", ")", "as", "$", "foreignKey", ")", "{", "$", "this", "->", "dropForeignKeyQueries", "=", "array_merge", "(", "$", "this", "->", "dropForeignKeyQueries", ",", "$", "this", "->", "platform", "->", "getDropForeignKeySQLQueries", "(", "$", "foreignKey", ",", "$", "table", "->", "getName", "(", ")", ")", ")", ";", "}", "$", "this", "->", "dropTableQueries", "=", "array_merge", "(", "$", "this", "->", "dropTableQueries", ",", "$", "this", "->", "platform", "->", "getDropTableSQLQueries", "(", "$", "table", ")", ")", ";", "}" ]
Collects queries to drop tables. @param \Fridge\DBAL\Schema\Table $table The table.
[ "Collects", "queries", "to", "drop", "tables", "." ]
d0b8c3551922d696836487aa0eb1bd74014edcd4
https://github.com/fridge-project/dbal/blob/d0b8c3551922d696836487aa0eb1bd74014edcd4/src/Fridge/DBAL/SchemaManager/SQLCollector/DropTableSQLCollector.php#L83-L96
train
Erebot/URI
src/URI.php
URI.parseURI
protected function parseURI($uri, $relative) { $result = array(); if (!$relative) { // Parse scheme. $pos = strpos($uri, ':'); if (!$pos) { // An URI starting with ":" is also invalid. throw new \InvalidArgumentException('No scheme found'); } $result['scheme'] = substr($uri, 0, $pos); $uri = (string) substr($uri, $pos + 1); } // Parse fragment. $pos = strpos($uri, '#'); if ($pos !== false) { $result['fragment'] = (string) substr($uri, $pos + 1); $uri = (string) substr($uri, 0, $pos); } // Parse query string. $pos = strpos($uri, '?'); if ($pos !== false) { $result['query'] = (string) substr($uri, $pos + 1); $uri = (string) substr($uri, 0, $pos); } // Handle "path-empty". if ($uri == '') { $result['path'] = ''; return $result; } // Handle "hier-part". if (substr($uri, 0, 2) == '//') { // Remove leftovers from the scheme field. $uri = (string) substr($uri, 2); // Parse path. $result['path'] = ''; $pos = strpos($uri, '/'); if ($pos !== false) { $result['path'] = substr($uri, $pos); $uri = (string) substr($uri, 0, $pos); } // Parse userinfo. $pos = strpos($uri, '@'); if ($pos !== false) { $result['userinfo'] = (string) substr($uri, 0, $pos); $uri = (string) substr($uri, $pos + 1); } // Parse port. $rpos = strcspn(strrev($uri), ':]'); $len = strlen($uri); if ($rpos != 0 && $rpos < $len && $uri[$len - $rpos - 1] != "]") { $result['port'] = (string) substr($uri, -1 * $rpos); $uri = (string) substr($uri, 0, -1 * $rpos - 1); } $result['host'] = $uri; return $result; } // Handle "path-absolute" & "path-rootless". $result['path'] = $uri; return $result; }
php
protected function parseURI($uri, $relative) { $result = array(); if (!$relative) { // Parse scheme. $pos = strpos($uri, ':'); if (!$pos) { // An URI starting with ":" is also invalid. throw new \InvalidArgumentException('No scheme found'); } $result['scheme'] = substr($uri, 0, $pos); $uri = (string) substr($uri, $pos + 1); } // Parse fragment. $pos = strpos($uri, '#'); if ($pos !== false) { $result['fragment'] = (string) substr($uri, $pos + 1); $uri = (string) substr($uri, 0, $pos); } // Parse query string. $pos = strpos($uri, '?'); if ($pos !== false) { $result['query'] = (string) substr($uri, $pos + 1); $uri = (string) substr($uri, 0, $pos); } // Handle "path-empty". if ($uri == '') { $result['path'] = ''; return $result; } // Handle "hier-part". if (substr($uri, 0, 2) == '//') { // Remove leftovers from the scheme field. $uri = (string) substr($uri, 2); // Parse path. $result['path'] = ''; $pos = strpos($uri, '/'); if ($pos !== false) { $result['path'] = substr($uri, $pos); $uri = (string) substr($uri, 0, $pos); } // Parse userinfo. $pos = strpos($uri, '@'); if ($pos !== false) { $result['userinfo'] = (string) substr($uri, 0, $pos); $uri = (string) substr($uri, $pos + 1); } // Parse port. $rpos = strcspn(strrev($uri), ':]'); $len = strlen($uri); if ($rpos != 0 && $rpos < $len && $uri[$len - $rpos - 1] != "]") { $result['port'] = (string) substr($uri, -1 * $rpos); $uri = (string) substr($uri, 0, -1 * $rpos - 1); } $result['host'] = $uri; return $result; } // Handle "path-absolute" & "path-rootless". $result['path'] = $uri; return $result; }
[ "protected", "function", "parseURI", "(", "$", "uri", ",", "$", "relative", ")", "{", "$", "result", "=", "array", "(", ")", ";", "if", "(", "!", "$", "relative", ")", "{", "// Parse scheme.", "$", "pos", "=", "strpos", "(", "$", "uri", ",", "':'", ")", ";", "if", "(", "!", "$", "pos", ")", "{", "// An URI starting with \":\" is also invalid.", "throw", "new", "\\", "InvalidArgumentException", "(", "'No scheme found'", ")", ";", "}", "$", "result", "[", "'scheme'", "]", "=", "substr", "(", "$", "uri", ",", "0", ",", "$", "pos", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "$", "pos", "+", "1", ")", ";", "}", "// Parse fragment.", "$", "pos", "=", "strpos", "(", "$", "uri", ",", "'#'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "result", "[", "'fragment'", "]", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "$", "pos", "+", "1", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "0", ",", "$", "pos", ")", ";", "}", "// Parse query string.", "$", "pos", "=", "strpos", "(", "$", "uri", ",", "'?'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "result", "[", "'query'", "]", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "$", "pos", "+", "1", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "0", ",", "$", "pos", ")", ";", "}", "// Handle \"path-empty\".", "if", "(", "$", "uri", "==", "''", ")", "{", "$", "result", "[", "'path'", "]", "=", "''", ";", "return", "$", "result", ";", "}", "// Handle \"hier-part\".", "if", "(", "substr", "(", "$", "uri", ",", "0", ",", "2", ")", "==", "'//'", ")", "{", "// Remove leftovers from the scheme field.", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "2", ")", ";", "// Parse path.", "$", "result", "[", "'path'", "]", "=", "''", ";", "$", "pos", "=", "strpos", "(", "$", "uri", ",", "'/'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "result", "[", "'path'", "]", "=", "substr", "(", "$", "uri", ",", "$", "pos", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "0", ",", "$", "pos", ")", ";", "}", "// Parse userinfo.", "$", "pos", "=", "strpos", "(", "$", "uri", ",", "'@'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "result", "[", "'userinfo'", "]", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "0", ",", "$", "pos", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "$", "pos", "+", "1", ")", ";", "}", "// Parse port.", "$", "rpos", "=", "strcspn", "(", "strrev", "(", "$", "uri", ")", ",", "':]'", ")", ";", "$", "len", "=", "strlen", "(", "$", "uri", ")", ";", "if", "(", "$", "rpos", "!=", "0", "&&", "$", "rpos", "<", "$", "len", "&&", "$", "uri", "[", "$", "len", "-", "$", "rpos", "-", "1", "]", "!=", "\"]\"", ")", "{", "$", "result", "[", "'port'", "]", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "-", "1", "*", "$", "rpos", ")", ";", "$", "uri", "=", "(", "string", ")", "substr", "(", "$", "uri", ",", "0", ",", "-", "1", "*", "$", "rpos", "-", "1", ")", ";", "}", "$", "result", "[", "'host'", "]", "=", "$", "uri", ";", "return", "$", "result", ";", "}", "// Handle \"path-absolute\" & \"path-rootless\".", "$", "result", "[", "'path'", "]", "=", "$", "uri", ";", "return", "$", "result", ";", "}" ]
Parses an URI using the grammar defined in RFC 3986. \param string $uri URI to parse. \param bool $relative Whether $uri must be considered as an absolute URI (\b false) or a relative reference (\b true). \retval array An associative array containing the different components that could be parsed out of this URI. It uses the same format as parse_url(), except that the "user" and "pass" components are merged into a single "userinfo" component and only string keys are defined. \throw ::InvalidArgumentException The given $uri is not valid.
[ "Parses", "an", "URI", "using", "the", "grammar", "defined", "in", "RFC", "3986", "." ]
f8277882f1251da9a9acb69ae04777e377e02ce8
https://github.com/Erebot/URI/blob/f8277882f1251da9a9acb69ae04777e377e02ce8/src/URI.php#L136-L207
train
Erebot/URI
src/URI.php
URI.normalizePercentReal
public static function normalizePercentReal($hexchr) { // 6.2.2.1. Case Normalization // Percent-encoded characters must use uppercase letters. // 6.2.2.2. Percent-Encoding Normalization $unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. 'abcdefghijklmnopqrstuvwxyz'. '-._~'; $chr = chr(hexdec($hexchr[1])); if (strpos($unreserved, $chr) !== false) { return $chr; } return '%' . strtoupper($hexchr[1]); }
php
public static function normalizePercentReal($hexchr) { // 6.2.2.1. Case Normalization // Percent-encoded characters must use uppercase letters. // 6.2.2.2. Percent-Encoding Normalization $unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'. 'abcdefghijklmnopqrstuvwxyz'. '-._~'; $chr = chr(hexdec($hexchr[1])); if (strpos($unreserved, $chr) !== false) { return $chr; } return '%' . strtoupper($hexchr[1]); }
[ "public", "static", "function", "normalizePercentReal", "(", "$", "hexchr", ")", "{", "// 6.2.2.1. Case Normalization", "// Percent-encoded characters must use uppercase letters.", "// 6.2.2.2. Percent-Encoding Normalization", "$", "unreserved", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", ".", "'abcdefghijklmnopqrstuvwxyz'", ".", "'-._~'", ";", "$", "chr", "=", "chr", "(", "hexdec", "(", "$", "hexchr", "[", "1", "]", ")", ")", ";", "if", "(", "strpos", "(", "$", "unreserved", ",", "$", "chr", ")", "!==", "false", ")", "{", "return", "$", "chr", ";", "}", "return", "'%'", ".", "strtoupper", "(", "$", "hexchr", "[", "1", "]", ")", ";", "}" ]
Performs normalization of a percent-encoded character. \param string $hexchr One percent-encoded character that needs to be normalized. \retval string The same text, after percent-encoding normalization.
[ "Performs", "normalization", "of", "a", "percent", "-", "encoded", "character", "." ]
f8277882f1251da9a9acb69ae04777e377e02ce8
https://github.com/Erebot/URI/blob/f8277882f1251da9a9acb69ae04777e377e02ce8/src/URI.php#L241-L255
train
Erebot/URI
src/URI.php
URI.merge
protected function merge($path) { // 5.2.3. Merge Paths if ($this->host !== null && $this->path == '') { return '/'.$path; } $pos = strrpos($this->path, '/'); if ($pos === false) { return $path; } return substr($this->path, 0, $pos + 1).$path; }
php
protected function merge($path) { // 5.2.3. Merge Paths if ($this->host !== null && $this->path == '') { return '/'.$path; } $pos = strrpos($this->path, '/'); if ($pos === false) { return $path; } return substr($this->path, 0, $pos + 1).$path; }
[ "protected", "function", "merge", "(", "$", "path", ")", "{", "// 5.2.3. Merge Paths", "if", "(", "$", "this", "->", "host", "!==", "null", "&&", "$", "this", "->", "path", "==", "''", ")", "{", "return", "'/'", ".", "$", "path", ";", "}", "$", "pos", "=", "strrpos", "(", "$", "this", "->", "path", ",", "'/'", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "{", "return", "$", "path", ";", "}", "return", "substr", "(", "$", "this", "->", "path", ",", "0", ",", "$", "pos", "+", "1", ")", ".", "$", "path", ";", "}" ]
Merges the given path with the current URI's path. \param string $path Path to merge into the current path. \retval string Result of that merge. \note Despite its name, this method does not modify the given $path nor the current object.
[ "Merges", "the", "given", "path", "with", "the", "current", "URI", "s", "path", "." ]
f8277882f1251da9a9acb69ae04777e377e02ce8
https://github.com/Erebot/URI/blob/f8277882f1251da9a9acb69ae04777e377e02ce8/src/URI.php#L539-L551
train
Erebot/URI
src/URI.php
URI.validatePath
protected function validatePath($path, $relative) { /* path = path-abempty ; begins with "/" or is empty / path-absolute ; begins with "/" but not "//" / path-noscheme ; begins with a non-colon segment / path-rootless ; begins with a segment / path-empty ; zero characters path-abempty = *( "/" segment ) path-absolute = "/" [ segment-nz *( "/" segment ) ] path-noscheme = segment-nz-nc *( "/" segment ) ; only used for a relative URI path-rootless = segment-nz *( "/" segment ) ; only used for an absolute URI path-empty = 0<pchar> segment = *pchar segment-nz = 1*pchar segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) ; non-zero-length segment without any colon ":" pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" pct-encoded = "%" HEXDIG HEXDIG */ $pchar = '(?:'. '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=:@]|'. '%[[:xdigit:]]'. ')'; $segment = '(?:'.$pchar.'*)'; $segmentNz = '(?:'.$pchar.'+)'; $segmentNzNc = '(?:'. '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=@]|'. '%[[:xdigit:]]'. ')+'; $pathAbempty = '(?:/'.$segment.')*'; $pathAbsolute = '/(?:'.$segmentNz.'(?:/'.$segment.')*)?'; $pathNoscheme = $segmentNzNc.'(?:/'.$segment.')*'; $pathRootless = $segmentNz.'(?:/'.$segment.')*'; $pathEmpty = '(?!'.$pchar.')'; $pattern = '(?:' . $pathAbempty.'|'.$pathAbsolute; if ($relative) { $pattern .= '|'.$pathNoscheme; } else { $pattern .= '|'.$pathRootless; } $pattern .= '|'.$pathEmpty . ')'; return (bool) preg_match('#^'.$pattern.'$#Di', $path); }
php
protected function validatePath($path, $relative) { /* path = path-abempty ; begins with "/" or is empty / path-absolute ; begins with "/" but not "//" / path-noscheme ; begins with a non-colon segment / path-rootless ; begins with a segment / path-empty ; zero characters path-abempty = *( "/" segment ) path-absolute = "/" [ segment-nz *( "/" segment ) ] path-noscheme = segment-nz-nc *( "/" segment ) ; only used for a relative URI path-rootless = segment-nz *( "/" segment ) ; only used for an absolute URI path-empty = 0<pchar> segment = *pchar segment-nz = 1*pchar segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) ; non-zero-length segment without any colon ":" pchar = unreserved / pct-encoded / sub-delims / ":" / "@" unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" pct-encoded = "%" HEXDIG HEXDIG */ $pchar = '(?:'. '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=:@]|'. '%[[:xdigit:]]'. ')'; $segment = '(?:'.$pchar.'*)'; $segmentNz = '(?:'.$pchar.'+)'; $segmentNzNc = '(?:'. '[-[:alnum:]\\._~!\\$&\'\\(\\)\\*\\+,;=@]|'. '%[[:xdigit:]]'. ')+'; $pathAbempty = '(?:/'.$segment.')*'; $pathAbsolute = '/(?:'.$segmentNz.'(?:/'.$segment.')*)?'; $pathNoscheme = $segmentNzNc.'(?:/'.$segment.')*'; $pathRootless = $segmentNz.'(?:/'.$segment.')*'; $pathEmpty = '(?!'.$pchar.')'; $pattern = '(?:' . $pathAbempty.'|'.$pathAbsolute; if ($relative) { $pattern .= '|'.$pathNoscheme; } else { $pattern .= '|'.$pathRootless; } $pattern .= '|'.$pathEmpty . ')'; return (bool) preg_match('#^'.$pattern.'$#Di', $path); }
[ "protected", "function", "validatePath", "(", "$", "path", ",", "$", "relative", ")", "{", "/*\n path = path-abempty ; begins with \"/\" or is empty\n / path-absolute ; begins with \"/\" but not \"//\"\n / path-noscheme ; begins with a non-colon segment\n / path-rootless ; begins with a segment\n / path-empty ; zero characters\n path-abempty = *( \"/\" segment )\n path-absolute = \"/\" [ segment-nz *( \"/\" segment ) ]\n path-noscheme = segment-nz-nc *( \"/\" segment )\n ; only used for a relative URI\n path-rootless = segment-nz *( \"/\" segment )\n ; only used for an absolute URI\n path-empty = 0<pchar>\n segment = *pchar\n segment-nz = 1*pchar\n segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / \"@\" )\n ; non-zero-length segment without any colon \":\"\n pchar = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n unreserved = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n pct-encoded = \"%\" HEXDIG HEXDIG\n */", "$", "pchar", "=", "'(?:'", ".", "'[-[:alnum:]\\\\._~!\\\\$&\\'\\\\(\\\\)\\\\*\\\\+,;=:@]|'", ".", "'%[[:xdigit:]]'", ".", "')'", ";", "$", "segment", "=", "'(?:'", ".", "$", "pchar", ".", "'*)'", ";", "$", "segmentNz", "=", "'(?:'", ".", "$", "pchar", ".", "'+)'", ";", "$", "segmentNzNc", "=", "'(?:'", ".", "'[-[:alnum:]\\\\._~!\\\\$&\\'\\\\(\\\\)\\\\*\\\\+,;=@]|'", ".", "'%[[:xdigit:]]'", ".", "')+'", ";", "$", "pathAbempty", "=", "'(?:/'", ".", "$", "segment", ".", "')*'", ";", "$", "pathAbsolute", "=", "'/(?:'", ".", "$", "segmentNz", ".", "'(?:/'", ".", "$", "segment", ".", "')*)?'", ";", "$", "pathNoscheme", "=", "$", "segmentNzNc", ".", "'(?:/'", ".", "$", "segment", ".", "')*'", ";", "$", "pathRootless", "=", "$", "segmentNz", ".", "'(?:/'", ".", "$", "segment", ".", "')*'", ";", "$", "pathEmpty", "=", "'(?!'", ".", "$", "pchar", ".", "')'", ";", "$", "pattern", "=", "'(?:'", ".", "$", "pathAbempty", ".", "'|'", ".", "$", "pathAbsolute", ";", "if", "(", "$", "relative", ")", "{", "$", "pattern", ".=", "'|'", ".", "$", "pathNoscheme", ";", "}", "else", "{", "$", "pattern", ".=", "'|'", ".", "$", "pathRootless", ";", "}", "$", "pattern", ".=", "'|'", ".", "$", "pathEmpty", ".", "')'", ";", "return", "(", "bool", ")", "preg_match", "(", "'#^'", ".", "$", "pattern", ".", "'$#Di'", ",", "$", "path", ")", ";", "}" ]
Validates the given path. \param string $path Path to validate. \param bool $relative Whether the given $path is relative (\b true) or not (\b false). \retval bool \b true if the given $path is valid, \b false otherwise.
[ "Validates", "the", "given", "path", "." ]
f8277882f1251da9a9acb69ae04777e377e02ce8
https://github.com/Erebot/URI/blob/f8277882f1251da9a9acb69ae04777e377e02ce8/src/URI.php#L579-L629
train
Erebot/URI
src/URI.php
URI.realSetPath
protected function realSetPath($path, $relative) { if (!is_string($path) || !$this->validatePath($path, $relative)) { throw new \InvalidArgumentException( 'Invalid path; use relative() for relative paths' ); } $this->path = $path; }
php
protected function realSetPath($path, $relative) { if (!is_string($path) || !$this->validatePath($path, $relative)) { throw new \InvalidArgumentException( 'Invalid path; use relative() for relative paths' ); } $this->path = $path; }
[ "protected", "function", "realSetPath", "(", "$", "path", ",", "$", "relative", ")", "{", "if", "(", "!", "is_string", "(", "$", "path", ")", "||", "!", "$", "this", "->", "validatePath", "(", "$", "path", ",", "$", "relative", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid path; use relative() for relative paths'", ")", ";", "}", "$", "this", "->", "path", "=", "$", "path", ";", "}" ]
Sets the current URI's path. \param string $path New path for this URI. \param bool $relative Whether the given $path is relative (\b true) or not (\b false). \throw ::InvalidArgumentException The given $path is not valid.
[ "Sets", "the", "current", "URI", "s", "path", "." ]
f8277882f1251da9a9acb69ae04777e377e02ce8
https://github.com/Erebot/URI/blob/f8277882f1251da9a9acb69ae04777e377e02ce8/src/URI.php#L644-L652
train
BenGorUser/DoctrineODMMongoDBBridge
src/BenGorUser/DoctrineODMMongoDBBridge/Infrastructure/Persistence/DocumentManagerFactory.php
DocumentManagerFactory.build
public function build(Connection $aConnection = null) { Type::addType('user_email', UserEmailType::class); Type::addType('user_id', UserIdType::class); Type::addType('user_password', UserPasswordType::class); Type::addType('user_roles', UserRolesType::class); Type::addType('user_token', UserTokenType::class); $configuration = new Configuration(); $driver = new YamlDriver([__DIR__ . '/Mapping']); $configuration->setMetadataDriverImpl($driver); $configuration->setProxyDir(__DIR__ . '/Proxies'); $configuration->setProxyNamespace('Proxies'); $configuration->setHydratorDir(__DIR__ . '/Hydrators'); $configuration->setHydratorNamespace('Hydrators'); return DocumentManager::create($aConnection, $configuration); }
php
public function build(Connection $aConnection = null) { Type::addType('user_email', UserEmailType::class); Type::addType('user_id', UserIdType::class); Type::addType('user_password', UserPasswordType::class); Type::addType('user_roles', UserRolesType::class); Type::addType('user_token', UserTokenType::class); $configuration = new Configuration(); $driver = new YamlDriver([__DIR__ . '/Mapping']); $configuration->setMetadataDriverImpl($driver); $configuration->setProxyDir(__DIR__ . '/Proxies'); $configuration->setProxyNamespace('Proxies'); $configuration->setHydratorDir(__DIR__ . '/Hydrators'); $configuration->setHydratorNamespace('Hydrators'); return DocumentManager::create($aConnection, $configuration); }
[ "public", "function", "build", "(", "Connection", "$", "aConnection", "=", "null", ")", "{", "Type", "::", "addType", "(", "'user_email'", ",", "UserEmailType", "::", "class", ")", ";", "Type", "::", "addType", "(", "'user_id'", ",", "UserIdType", "::", "class", ")", ";", "Type", "::", "addType", "(", "'user_password'", ",", "UserPasswordType", "::", "class", ")", ";", "Type", "::", "addType", "(", "'user_roles'", ",", "UserRolesType", "::", "class", ")", ";", "Type", "::", "addType", "(", "'user_token'", ",", "UserTokenType", "::", "class", ")", ";", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$", "driver", "=", "new", "YamlDriver", "(", "[", "__DIR__", ".", "'/Mapping'", "]", ")", ";", "$", "configuration", "->", "setMetadataDriverImpl", "(", "$", "driver", ")", ";", "$", "configuration", "->", "setProxyDir", "(", "__DIR__", ".", "'/Proxies'", ")", ";", "$", "configuration", "->", "setProxyNamespace", "(", "'Proxies'", ")", ";", "$", "configuration", "->", "setHydratorDir", "(", "__DIR__", ".", "'/Hydrators'", ")", ";", "$", "configuration", "->", "setHydratorNamespace", "(", "'Hydrators'", ")", ";", "return", "DocumentManager", "::", "create", "(", "$", "aConnection", ",", "$", "configuration", ")", ";", "}" ]
Creates an document manager instance enabling mappings and custom types. @param Connection|null $aConnection The MongoDB connection, it can be null @return DocumentManager
[ "Creates", "an", "document", "manager", "instance", "enabling", "mappings", "and", "custom", "types", "." ]
be1ef0641ab179ef429388cef81c287f33a61108
https://github.com/BenGorUser/DoctrineODMMongoDBBridge/blob/be1ef0641ab179ef429388cef81c287f33a61108/src/BenGorUser/DoctrineODMMongoDBBridge/Infrastructure/Persistence/DocumentManagerFactory.php#L40-L57
train
agentmedia/phine-core
src/Core/Logic/Access/Backend/GroupFinder.php
GroupFinder.FindContentGroup
static function FindContentGroup(Content $content) { $result = null; $currContent = $content; do { $result = $currContent->GetUserGroup(); $currContent = ContentTreeUtil::ParentOf($currContent); } while (!$result && $currContent); if ($result) { return $result; } return self::GetUpperContentGroup($content); }
php
static function FindContentGroup(Content $content) { $result = null; $currContent = $content; do { $result = $currContent->GetUserGroup(); $currContent = ContentTreeUtil::ParentOf($currContent); } while (!$result && $currContent); if ($result) { return $result; } return self::GetUpperContentGroup($content); }
[ "static", "function", "FindContentGroup", "(", "Content", "$", "content", ")", "{", "$", "result", "=", "null", ";", "$", "currContent", "=", "$", "content", ";", "do", "{", "$", "result", "=", "$", "currContent", "->", "GetUserGroup", "(", ")", ";", "$", "currContent", "=", "ContentTreeUtil", "::", "ParentOf", "(", "$", "currContent", ")", ";", "}", "while", "(", "!", "$", "result", "&&", "$", "currContent", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "return", "self", "::", "GetUpperContentGroup", "(", "$", "content", ")", ";", "}" ]
Finds the user group by searching in element tree @param Content $content The content @return Usergroup The assigned user group
[ "Finds", "the", "user", "group", "by", "searching", "in", "element", "tree" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Access/Backend/GroupFinder.php#L19-L34
train
agentmedia/phine-core
src/Core/Logic/Access/Backend/GroupFinder.php
GroupFinder.GetUpperContentGroup
private static function GetUpperContentGroup(Content $content) { if ($content->GetPageContent()) { return self::FindPageGroup($content->GetPageContent()->GetPage()); } else if ($content->GetLayoutContent()) { return $content->GetLayoutContent()-> GetArea()->GetLayout()->GetUserGroup(); } else if ($content->GetContainerContent()) { return $content->GetContainerContent()-> GetContainer()->GetUserGroup(); } return null; }
php
private static function GetUpperContentGroup(Content $content) { if ($content->GetPageContent()) { return self::FindPageGroup($content->GetPageContent()->GetPage()); } else if ($content->GetLayoutContent()) { return $content->GetLayoutContent()-> GetArea()->GetLayout()->GetUserGroup(); } else if ($content->GetContainerContent()) { return $content->GetContainerContent()-> GetContainer()->GetUserGroup(); } return null; }
[ "private", "static", "function", "GetUpperContentGroup", "(", "Content", "$", "content", ")", "{", "if", "(", "$", "content", "->", "GetPageContent", "(", ")", ")", "{", "return", "self", "::", "FindPageGroup", "(", "$", "content", "->", "GetPageContent", "(", ")", "->", "GetPage", "(", ")", ")", ";", "}", "else", "if", "(", "$", "content", "->", "GetLayoutContent", "(", ")", ")", "{", "return", "$", "content", "->", "GetLayoutContent", "(", ")", "->", "GetArea", "(", ")", "->", "GetLayout", "(", ")", "->", "GetUserGroup", "(", ")", ";", "}", "else", "if", "(", "$", "content", "->", "GetContainerContent", "(", ")", ")", "{", "return", "$", "content", "->", "GetContainerContent", "(", ")", "->", "GetContainer", "(", ")", "->", "GetUserGroup", "(", ")", ";", "}", "return", "null", ";", "}" ]
Gets the upper countent user group @param Content $content The content @return Usergroup Gets the content rights of the upper, containing element (layout, page, container)
[ "Gets", "the", "upper", "countent", "user", "group" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Access/Backend/GroupFinder.php#L41-L58
train
agentmedia/phine-core
src/Core/Logic/Access/Backend/GroupFinder.php
GroupFinder.FindPageGroup
static function FindPageGroup(Page $page) { $currPage = $page; $result = null; do { $result = $currPage->GetUserGroup(); $currPage = $currPage->GetParent(); } while (!$result && $currPage); if (!$result && $page->GetSite()) { return $page->GetSite()->GetUserGroup(); } return $result; }
php
static function FindPageGroup(Page $page) { $currPage = $page; $result = null; do { $result = $currPage->GetUserGroup(); $currPage = $currPage->GetParent(); } while (!$result && $currPage); if (!$result && $page->GetSite()) { return $page->GetSite()->GetUserGroup(); } return $result; }
[ "static", "function", "FindPageGroup", "(", "Page", "$", "page", ")", "{", "$", "currPage", "=", "$", "page", ";", "$", "result", "=", "null", ";", "do", "{", "$", "result", "=", "$", "currPage", "->", "GetUserGroup", "(", ")", ";", "$", "currPage", "=", "$", "currPage", "->", "GetParent", "(", ")", ";", "}", "while", "(", "!", "$", "result", "&&", "$", "currPage", ")", ";", "if", "(", "!", "$", "result", "&&", "$", "page", "->", "GetSite", "(", ")", ")", "{", "return", "$", "page", "->", "GetSite", "(", ")", "->", "GetUserGroup", "(", ")", ";", "}", "return", "$", "result", ";", "}" ]
Gets the page's user group @param Page $page @return Usergroup
[ "Gets", "the", "page", "s", "user", "group" ]
38c1be8d03ebffae950d00a96da3c612aff67832
https://github.com/agentmedia/phine-core/blob/38c1be8d03ebffae950d00a96da3c612aff67832/src/Core/Logic/Access/Backend/GroupFinder.php#L65-L80
train
ibonly/Potato-ORM
src/Helper/GetData.php
GetData.DESC
protected function DESC($limit = NULL) { $value = array_reverse($this->value); if ($limit === NULL) { return $value; } else { return array_slice($value, 0, $limit); } }
php
protected function DESC($limit = NULL) { $value = array_reverse($this->value); if ($limit === NULL) { return $value; } else { return array_slice($value, 0, $limit); } }
[ "protected", "function", "DESC", "(", "$", "limit", "=", "NULL", ")", "{", "$", "value", "=", "array_reverse", "(", "$", "this", "->", "value", ")", ";", "if", "(", "$", "limit", "===", "NULL", ")", "{", "return", "$", "value", ";", "}", "else", "{", "return", "array_slice", "(", "$", "value", ",", "0", ",", "$", "limit", ")", ";", "}", "}" ]
Reverse the json data @param [int] $limit
[ "Reverse", "the", "json", "data" ]
644962a99e1c0191b732d7729cd466d52c5d8652
https://github.com/ibonly/Potato-ORM/blob/644962a99e1c0191b732d7729cd466d52c5d8652/src/Helper/GetData.php#L28-L36
train
ibonly/Potato-ORM
src/Helper/GetData.php
GetData.toJson
public function toJson($all = false) { return $all ? json_encode($this->getAllData()) : json_encode($this->toArray()); }
php
public function toJson($all = false) { return $all ? json_encode($this->getAllData()) : json_encode($this->toArray()); }
[ "public", "function", "toJson", "(", "$", "all", "=", "false", ")", "{", "return", "$", "all", "?", "json_encode", "(", "$", "this", "->", "getAllData", "(", ")", ")", ":", "json_encode", "(", "$", "this", "->", "toArray", "(", ")", ")", ";", "}" ]
Convert the fetched row to json
[ "Convert", "the", "fetched", "row", "to", "json" ]
644962a99e1c0191b732d7729cd466d52c5d8652
https://github.com/ibonly/Potato-ORM/blob/644962a99e1c0191b732d7729cd466d52c5d8652/src/Helper/GetData.php#L66-L69
train
Polosa/shade-framework-core
app/Controller.php
Controller.render
protected function render($templates, array $data = array()) { $content = $this->view->render($templates, $data); $response = new Response(); $response->setContent($content); return $response; }
php
protected function render($templates, array $data = array()) { $content = $this->view->render($templates, $data); $response = new Response(); $response->setContent($content); return $response; }
[ "protected", "function", "render", "(", "$", "templates", ",", "array", "$", "data", "=", "array", "(", ")", ")", "{", "$", "content", "=", "$", "this", "->", "view", "->", "render", "(", "$", "templates", ",", "$", "data", ")", ";", "$", "response", "=", "new", "Response", "(", ")", ";", "$", "response", "->", "setContent", "(", "$", "content", ")", ";", "return", "$", "response", ";", "}" ]
Render template and get Response @param string|array $templates Path to template or array of paths to template and layouts @param array $data Data for templates @return \Shade\Response
[ "Render", "template", "and", "get", "Response" ]
d735d3e8e0616fb9cf4ffc25b8425762ed07940f
https://github.com/Polosa/shade-framework-core/blob/d735d3e8e0616fb9cf4ffc25b8425762ed07940f/app/Controller.php#L188-L195
train
phossa/phossa-di
src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php
ReferenceActionTrait.dereferenceArray
protected function dereferenceArray(array &$arrayData) { try { foreach ($arrayData as $idx => $data) { // go deeper if is array if (is_array($data)) { $this->dereferenceArray($arrayData[$idx]); // dereference if it is a reference #changed } elseif (false !== ($ref = $this->isReference($data))) { $arrayData[$idx] = $this->getReferenceValue($ref); } } } catch (\Exception $e) { throw new LogicException($e->getMessage(), $e->getCode(), $e); } }
php
protected function dereferenceArray(array &$arrayData) { try { foreach ($arrayData as $idx => $data) { // go deeper if is array if (is_array($data)) { $this->dereferenceArray($arrayData[$idx]); // dereference if it is a reference #changed } elseif (false !== ($ref = $this->isReference($data))) { $arrayData[$idx] = $this->getReferenceValue($ref); } } } catch (\Exception $e) { throw new LogicException($e->getMessage(), $e->getCode(), $e); } }
[ "protected", "function", "dereferenceArray", "(", "array", "&", "$", "arrayData", ")", "{", "try", "{", "foreach", "(", "$", "arrayData", "as", "$", "idx", "=>", "$", "data", ")", "{", "// go deeper if is array", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "$", "this", "->", "dereferenceArray", "(", "$", "arrayData", "[", "$", "idx", "]", ")", ";", "// dereference if it is a reference #changed", "}", "elseif", "(", "false", "!==", "(", "$", "ref", "=", "$", "this", "->", "isReference", "(", "$", "data", ")", ")", ")", "{", "$", "arrayData", "[", "$", "idx", "]", "=", "$", "this", "->", "getReferenceValue", "(", "$", "ref", ")", ";", "}", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "throw", "new", "LogicException", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "e", "->", "getCode", "(", ")", ",", "$", "e", ")", ";", "}", "}" ]
Replace all the references in the array with values @param array &$arrayData @return void @throws LogicException if something goes wrong @access protected
[ "Replace", "all", "the", "references", "in", "the", "array", "with", "values" ]
bbe1e95b081068e2bc49c6cd465f38aab0374be5
https://github.com/phossa/phossa-di/blob/bbe1e95b081068e2bc49c6cd465f38aab0374be5/src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php#L47-L63
train
phossa/phossa-di
src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php
ReferenceActionTrait.getReferenceValue
protected function getReferenceValue( ReferenceAbstract $reference, /*# int */ $level = 0 ) { $name = $reference->getName(); // loop found if ($level > 2) { throw new NotFoundException( Message::get(Message::PARAMETER_LOOP_FOUND, $name), Message::PARAMETER_LOOP_FOUND ); } // get service reference value if ($reference instanceof ServiceReference) { return $this->delegatedGet($name); // get parameter value, if value is another reference, go deeper } else { $val = $this->getParameter($name); if (is_string($val) && ($ref = $this->isReference($val))) { return $this->getReferenceValue($ref, ++$level); } return $val; } }
php
protected function getReferenceValue( ReferenceAbstract $reference, /*# int */ $level = 0 ) { $name = $reference->getName(); // loop found if ($level > 2) { throw new NotFoundException( Message::get(Message::PARAMETER_LOOP_FOUND, $name), Message::PARAMETER_LOOP_FOUND ); } // get service reference value if ($reference instanceof ServiceReference) { return $this->delegatedGet($name); // get parameter value, if value is another reference, go deeper } else { $val = $this->getParameter($name); if (is_string($val) && ($ref = $this->isReference($val))) { return $this->getReferenceValue($ref, ++$level); } return $val; } }
[ "protected", "function", "getReferenceValue", "(", "ReferenceAbstract", "$", "reference", ",", "/*# int */", "$", "level", "=", "0", ")", "{", "$", "name", "=", "$", "reference", "->", "getName", "(", ")", ";", "// loop found", "if", "(", "$", "level", ">", "2", ")", "{", "throw", "new", "NotFoundException", "(", "Message", "::", "get", "(", "Message", "::", "PARAMETER_LOOP_FOUND", ",", "$", "name", ")", ",", "Message", "::", "PARAMETER_LOOP_FOUND", ")", ";", "}", "// get service reference value", "if", "(", "$", "reference", "instanceof", "ServiceReference", ")", "{", "return", "$", "this", "->", "delegatedGet", "(", "$", "name", ")", ";", "// get parameter value, if value is another reference, go deeper", "}", "else", "{", "$", "val", "=", "$", "this", "->", "getParameter", "(", "$", "name", ")", ";", "if", "(", "is_string", "(", "$", "val", ")", "&&", "(", "$", "ref", "=", "$", "this", "->", "isReference", "(", "$", "val", ")", ")", ")", "{", "return", "$", "this", "->", "getReferenceValue", "(", "$", "ref", ",", "++", "$", "level", ")", ";", "}", "return", "$", "val", ";", "}", "}" ]
Get the reference value @param ReferenceAbstract $reference @param int $level current recursive level @return mixed @access protected
[ "Get", "the", "reference", "value" ]
bbe1e95b081068e2bc49c6cd465f38aab0374be5
https://github.com/phossa/phossa-di/blob/bbe1e95b081068e2bc49c6cd465f38aab0374be5/src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php#L73-L99
train
phossa/phossa-di
src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php
ReferenceActionTrait.isReference
protected function isReference($data) { // is a reference object if (is_object($data) && $data instanceof ReferenceAbstract) { return $data; // is string and matches reference pattern } elseif (is_string($data)) { $pat = '/^(@|%)([^\s]+)\1$/'; $mat = []; // placeholders if (preg_match($pat, $data, $mat)) { return $mat[1] === '@' ? new ServiceReference($mat[2]) : new ParameterReference($mat[2]); } // parameter resolver support if ($this->hasResolver() && $this->getResolver()->hasReference($data)) { list($s, $e) = $this->paramter_pattern; $pat = '/^' . preg_quote($s) . '([^\s]+)' . preg_quote($e). '$/'; if (preg_match($pat, $data, $mat)) { return new ParameterReference($mat[1]); } } return false; // not a match } else { return false; } }
php
protected function isReference($data) { // is a reference object if (is_object($data) && $data instanceof ReferenceAbstract) { return $data; // is string and matches reference pattern } elseif (is_string($data)) { $pat = '/^(@|%)([^\s]+)\1$/'; $mat = []; // placeholders if (preg_match($pat, $data, $mat)) { return $mat[1] === '@' ? new ServiceReference($mat[2]) : new ParameterReference($mat[2]); } // parameter resolver support if ($this->hasResolver() && $this->getResolver()->hasReference($data)) { list($s, $e) = $this->paramter_pattern; $pat = '/^' . preg_quote($s) . '([^\s]+)' . preg_quote($e). '$/'; if (preg_match($pat, $data, $mat)) { return new ParameterReference($mat[1]); } } return false; // not a match } else { return false; } }
[ "protected", "function", "isReference", "(", "$", "data", ")", "{", "// is a reference object", "if", "(", "is_object", "(", "$", "data", ")", "&&", "$", "data", "instanceof", "ReferenceAbstract", ")", "{", "return", "$", "data", ";", "// is string and matches reference pattern", "}", "elseif", "(", "is_string", "(", "$", "data", ")", ")", "{", "$", "pat", "=", "'/^(@|%)([^\\s]+)\\1$/'", ";", "$", "mat", "=", "[", "]", ";", "// placeholders", "if", "(", "preg_match", "(", "$", "pat", ",", "$", "data", ",", "$", "mat", ")", ")", "{", "return", "$", "mat", "[", "1", "]", "===", "'@'", "?", "new", "ServiceReference", "(", "$", "mat", "[", "2", "]", ")", ":", "new", "ParameterReference", "(", "$", "mat", "[", "2", "]", ")", ";", "}", "// parameter resolver support", "if", "(", "$", "this", "->", "hasResolver", "(", ")", "&&", "$", "this", "->", "getResolver", "(", ")", "->", "hasReference", "(", "$", "data", ")", ")", "{", "list", "(", "$", "s", ",", "$", "e", ")", "=", "$", "this", "->", "paramter_pattern", ";", "$", "pat", "=", "'/^'", ".", "preg_quote", "(", "$", "s", ")", ".", "'([^\\s]+)'", ".", "preg_quote", "(", "$", "e", ")", ".", "'$/'", ";", "if", "(", "preg_match", "(", "$", "pat", ",", "$", "data", ",", "$", "mat", ")", ")", "{", "return", "new", "ParameterReference", "(", "$", "mat", "[", "1", "]", ")", ";", "}", "}", "return", "false", ";", "// not a match", "}", "else", "{", "return", "false", ";", "}", "}" ]
Is a reference string or reference object. convert to object @param mixed $data data to check @return ReferenceAbstract|false @access protected
[ "Is", "a", "reference", "string", "or", "reference", "object", ".", "convert", "to", "object" ]
bbe1e95b081068e2bc49c6cd465f38aab0374be5
https://github.com/phossa/phossa-di/blob/bbe1e95b081068e2bc49c6cd465f38aab0374be5/src/Phossa/Di/Definition/Reference/ReferenceActionTrait.php#L108-L142
train
nice-php/benchmark
src/Benchmark.php
Benchmark.execute
public function execute() { $this->resultPrinter->printBenchmarkIntro($this); $results = array(); foreach ($this->tests as $test) { $testResults = array(); for ($i = 0; $i < $this->iterations; $i++) { $start = time() + microtime(); $test->run($this->parameters); $testResults[] = round((time() + microtime()) - $start, 10); } $testResults = $this->resultPruner->prune($testResults); $this->resultPrinter->printSingleTestResult($test, $testResults); $results[$test->getName()] = $testResults; } $this->resultPrinter->printBenchmarkSummary($this, $results); $this->resultPrinter->printBreak(); return $results; }
php
public function execute() { $this->resultPrinter->printBenchmarkIntro($this); $results = array(); foreach ($this->tests as $test) { $testResults = array(); for ($i = 0; $i < $this->iterations; $i++) { $start = time() + microtime(); $test->run($this->parameters); $testResults[] = round((time() + microtime()) - $start, 10); } $testResults = $this->resultPruner->prune($testResults); $this->resultPrinter->printSingleTestResult($test, $testResults); $results[$test->getName()] = $testResults; } $this->resultPrinter->printBenchmarkSummary($this, $results); $this->resultPrinter->printBreak(); return $results; }
[ "public", "function", "execute", "(", ")", "{", "$", "this", "->", "resultPrinter", "->", "printBenchmarkIntro", "(", "$", "this", ")", ";", "$", "results", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "tests", "as", "$", "test", ")", "{", "$", "testResults", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "this", "->", "iterations", ";", "$", "i", "++", ")", "{", "$", "start", "=", "time", "(", ")", "+", "microtime", "(", ")", ";", "$", "test", "->", "run", "(", "$", "this", "->", "parameters", ")", ";", "$", "testResults", "[", "]", "=", "round", "(", "(", "time", "(", ")", "+", "microtime", "(", ")", ")", "-", "$", "start", ",", "10", ")", ";", "}", "$", "testResults", "=", "$", "this", "->", "resultPruner", "->", "prune", "(", "$", "testResults", ")", ";", "$", "this", "->", "resultPrinter", "->", "printSingleTestResult", "(", "$", "test", ",", "$", "testResults", ")", ";", "$", "results", "[", "$", "test", "->", "getName", "(", ")", "]", "=", "$", "testResults", ";", "}", "$", "this", "->", "resultPrinter", "->", "printBenchmarkSummary", "(", "$", "this", ",", "$", "results", ")", ";", "$", "this", "->", "resultPrinter", "->", "printBreak", "(", ")", ";", "return", "$", "results", ";", "}" ]
Execute the registered tests and display the results
[ "Execute", "the", "registered", "tests", "and", "display", "the", "results" ]
2084c77dbb88cd76006abbfe85b2b704f6bbd1cf
https://github.com/nice-php/benchmark/blob/2084c77dbb88cd76006abbfe85b2b704f6bbd1cf/src/Benchmark.php#L79-L102
train
dmitrya2e/filtration-bundle
CallableFunction/Validator/BaseFunctionValidator.php
BaseFunctionValidator.doValidate
protected function doValidate() { if ($this->argumentTypes === false) { throw new CallableFunctionValidatorException('Variable $argumentTypes must be defined.'); } $argumentCount = count($this->argumentTypes); $reflectionFunction = new \ReflectionFunction($this->callableFunction); $reflectionParams = $reflectionFunction->getParameters(); // Checking argument count. if (count($reflectionParams) != $argumentCount) { throw new CallableFunctionValidatorException(sprintf( 'There is not sufficient argument count (required %s arguments).', $argumentCount )); } // Checking argument types. foreach ($this->argumentTypes as $k => $type) { if (!array_key_exists('type', $type)) { throw new \InvalidArgumentException('Key "type" must be defined.'); } $parameter = $reflectionParams[$k]; $class = $parameter->getClass(); if ($type['type'] !== null) { if ($class === null || $type['type'] !== $class->getName()) { throw new CallableFunctionValidatorException(sprintf( 'Argument %s must be type of "%s".', $k, $type['type'] )); } } if (array_key_exists('array', $type) && $type['array'] === true) { if ($class !== null) { throw new CallableFunctionValidatorException(sprintf('Argument %s must be type of null.', $k)); } if (!$parameter->isArray()) { throw new CallableFunctionValidatorException(sprintf('Argument %s must be an array.', $k)); } } } }
php
protected function doValidate() { if ($this->argumentTypes === false) { throw new CallableFunctionValidatorException('Variable $argumentTypes must be defined.'); } $argumentCount = count($this->argumentTypes); $reflectionFunction = new \ReflectionFunction($this->callableFunction); $reflectionParams = $reflectionFunction->getParameters(); // Checking argument count. if (count($reflectionParams) != $argumentCount) { throw new CallableFunctionValidatorException(sprintf( 'There is not sufficient argument count (required %s arguments).', $argumentCount )); } // Checking argument types. foreach ($this->argumentTypes as $k => $type) { if (!array_key_exists('type', $type)) { throw new \InvalidArgumentException('Key "type" must be defined.'); } $parameter = $reflectionParams[$k]; $class = $parameter->getClass(); if ($type['type'] !== null) { if ($class === null || $type['type'] !== $class->getName()) { throw new CallableFunctionValidatorException(sprintf( 'Argument %s must be type of "%s".', $k, $type['type'] )); } } if (array_key_exists('array', $type) && $type['array'] === true) { if ($class !== null) { throw new CallableFunctionValidatorException(sprintf('Argument %s must be type of null.', $k)); } if (!$parameter->isArray()) { throw new CallableFunctionValidatorException(sprintf('Argument %s must be an array.', $k)); } } } }
[ "protected", "function", "doValidate", "(", ")", "{", "if", "(", "$", "this", "->", "argumentTypes", "===", "false", ")", "{", "throw", "new", "CallableFunctionValidatorException", "(", "'Variable $argumentTypes must be defined.'", ")", ";", "}", "$", "argumentCount", "=", "count", "(", "$", "this", "->", "argumentTypes", ")", ";", "$", "reflectionFunction", "=", "new", "\\", "ReflectionFunction", "(", "$", "this", "->", "callableFunction", ")", ";", "$", "reflectionParams", "=", "$", "reflectionFunction", "->", "getParameters", "(", ")", ";", "// Checking argument count.\r", "if", "(", "count", "(", "$", "reflectionParams", ")", "!=", "$", "argumentCount", ")", "{", "throw", "new", "CallableFunctionValidatorException", "(", "sprintf", "(", "'There is not sufficient argument count (required %s arguments).'", ",", "$", "argumentCount", ")", ")", ";", "}", "// Checking argument types.\r", "foreach", "(", "$", "this", "->", "argumentTypes", "as", "$", "k", "=>", "$", "type", ")", "{", "if", "(", "!", "array_key_exists", "(", "'type'", ",", "$", "type", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Key \"type\" must be defined.'", ")", ";", "}", "$", "parameter", "=", "$", "reflectionParams", "[", "$", "k", "]", ";", "$", "class", "=", "$", "parameter", "->", "getClass", "(", ")", ";", "if", "(", "$", "type", "[", "'type'", "]", "!==", "null", ")", "{", "if", "(", "$", "class", "===", "null", "||", "$", "type", "[", "'type'", "]", "!==", "$", "class", "->", "getName", "(", ")", ")", "{", "throw", "new", "CallableFunctionValidatorException", "(", "sprintf", "(", "'Argument %s must be type of \"%s\".'", ",", "$", "k", ",", "$", "type", "[", "'type'", "]", ")", ")", ";", "}", "}", "if", "(", "array_key_exists", "(", "'array'", ",", "$", "type", ")", "&&", "$", "type", "[", "'array'", "]", "===", "true", ")", "{", "if", "(", "$", "class", "!==", "null", ")", "{", "throw", "new", "CallableFunctionValidatorException", "(", "sprintf", "(", "'Argument %s must be type of null.'", ",", "$", "k", ")", ")", ";", "}", "if", "(", "!", "$", "parameter", "->", "isArray", "(", ")", ")", "{", "throw", "new", "CallableFunctionValidatorException", "(", "sprintf", "(", "'Argument %s must be an array.'", ",", "$", "k", ")", ")", ";", "}", "}", "}", "}" ]
Validates callable function arguments. @throws CallableFunctionValidatorException @throws \InvalidArgumentException
[ "Validates", "callable", "function", "arguments", "." ]
fed5764af4e43871835744fb84957b2a76e9a215
https://github.com/dmitrya2e/filtration-bundle/blob/fed5764af4e43871835744fb84957b2a76e9a215/CallableFunction/Validator/BaseFunctionValidator.php#L106-L151
train
ValkSystems/bootbuilder
src/bootbuilder/Validation/Validator.php
Validator.save
public static function save($form, $formid, $prepare = true) { if($prepare) { self::prepareSession(); } // Save in session $_SESSION['bbforms'][$formid] = $form; }
php
public static function save($form, $formid, $prepare = true) { if($prepare) { self::prepareSession(); } // Save in session $_SESSION['bbforms'][$formid] = $form; }
[ "public", "static", "function", "save", "(", "$", "form", ",", "$", "formid", ",", "$", "prepare", "=", "true", ")", "{", "if", "(", "$", "prepare", ")", "{", "self", "::", "prepareSession", "(", ")", ";", "}", "// Save in session", "$", "_SESSION", "[", "'bbforms'", "]", "[", "$", "formid", "]", "=", "$", "form", ";", "}" ]
Save Form into session, and prepare it for validation later on @param \bootbuilder\Form $form @param int $formid @param boolean $prepare prepare the sesison, false on unittesting
[ "Save", "Form", "into", "session", "and", "prepare", "it", "for", "validation", "later", "on" ]
7601a403f42eba47ce4cf02a3c852d5196b1d860
https://github.com/ValkSystems/bootbuilder/blob/7601a403f42eba47ce4cf02a3c852d5196b1d860/src/bootbuilder/Validation/Validator.php#L21-L28
train
ValkSystems/bootbuilder
src/bootbuilder/Validation/Validator.php
Validator.load
public function load($parameters, $prepare = true) { $this->parameters = $parameters; if($prepare) { $this->prepareSession(); } if (isset($parameters['bootbuilder-form']) && isset($_SESSION['bbforms']) && isset($_SESSION['bbforms'][$parameters['bootbuilder-form']])) { $this->form = $this->loadForm($parameters['bootbuilder-form']); if ($this->form instanceof \bootbuilder\Form) { $this->form->parseParameters($parameters); } }else{ $this->form = new \bootbuilder\NormalForm(); } return $this; }
php
public function load($parameters, $prepare = true) { $this->parameters = $parameters; if($prepare) { $this->prepareSession(); } if (isset($parameters['bootbuilder-form']) && isset($_SESSION['bbforms']) && isset($_SESSION['bbforms'][$parameters['bootbuilder-form']])) { $this->form = $this->loadForm($parameters['bootbuilder-form']); if ($this->form instanceof \bootbuilder\Form) { $this->form->parseParameters($parameters); } }else{ $this->form = new \bootbuilder\NormalForm(); } return $this; }
[ "public", "function", "load", "(", "$", "parameters", ",", "$", "prepare", "=", "true", ")", "{", "$", "this", "->", "parameters", "=", "$", "parameters", ";", "if", "(", "$", "prepare", ")", "{", "$", "this", "->", "prepareSession", "(", ")", ";", "}", "if", "(", "isset", "(", "$", "parameters", "[", "'bootbuilder-form'", "]", ")", "&&", "isset", "(", "$", "_SESSION", "[", "'bbforms'", "]", ")", "&&", "isset", "(", "$", "_SESSION", "[", "'bbforms'", "]", "[", "$", "parameters", "[", "'bootbuilder-form'", "]", "]", ")", ")", "{", "$", "this", "->", "form", "=", "$", "this", "->", "loadForm", "(", "$", "parameters", "[", "'bootbuilder-form'", "]", ")", ";", "if", "(", "$", "this", "->", "form", "instanceof", "\\", "bootbuilder", "\\", "Form", ")", "{", "$", "this", "->", "form", "->", "parseParameters", "(", "$", "parameters", ")", ";", "}", "}", "else", "{", "$", "this", "->", "form", "=", "new", "\\", "bootbuilder", "\\", "NormalForm", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Load previous form from session @param array $parameters POST/GET parameters array @param boolean $prepare Prepare session, false on unittesting @return \bootbuilder\Validation\Validator
[ "Load", "previous", "form", "from", "session" ]
7601a403f42eba47ce4cf02a3c852d5196b1d860
https://github.com/ValkSystems/bootbuilder/blob/7601a403f42eba47ce4cf02a3c852d5196b1d860/src/bootbuilder/Validation/Validator.php#L36-L54
train
ValkSystems/bootbuilder
src/bootbuilder/Validation/Validator.php
Validator.validate
public function validate() { $status = new ValidationResult(); // Check if the form is loaded if (!$this->form instanceof \bootbuilder\Form) { $status->setError(true); return $status; } // Validate form controls (and panes) foreach ($this->form->getRawControls() as $nr => $control) { if(!$this->validateControl($control, $status)) { $status->setError(true); $control->setErrorState(true); } $this->form->replaceControl($nr, $control); } return $status; }
php
public function validate() { $status = new ValidationResult(); // Check if the form is loaded if (!$this->form instanceof \bootbuilder\Form) { $status->setError(true); return $status; } // Validate form controls (and panes) foreach ($this->form->getRawControls() as $nr => $control) { if(!$this->validateControl($control, $status)) { $status->setError(true); $control->setErrorState(true); } $this->form->replaceControl($nr, $control); } return $status; }
[ "public", "function", "validate", "(", ")", "{", "$", "status", "=", "new", "ValidationResult", "(", ")", ";", "// Check if the form is loaded", "if", "(", "!", "$", "this", "->", "form", "instanceof", "\\", "bootbuilder", "\\", "Form", ")", "{", "$", "status", "->", "setError", "(", "true", ")", ";", "return", "$", "status", ";", "}", "// Validate form controls (and panes)", "foreach", "(", "$", "this", "->", "form", "->", "getRawControls", "(", ")", "as", "$", "nr", "=>", "$", "control", ")", "{", "if", "(", "!", "$", "this", "->", "validateControl", "(", "$", "control", ",", "$", "status", ")", ")", "{", "$", "status", "->", "setError", "(", "true", ")", ";", "$", "control", "->", "setErrorState", "(", "true", ")", ";", "}", "$", "this", "->", "form", "->", "replaceControl", "(", "$", "nr", ",", "$", "control", ")", ";", "}", "return", "$", "status", ";", "}" ]
Validate the form controls, validates by the required status, and some specific control validations such as email control @return \bootbuilder\Validation\ValidationResult
[ "Validate", "the", "form", "controls", "validates", "by", "the", "required", "status", "and", "some", "specific", "control", "validations", "such", "as", "email", "control" ]
7601a403f42eba47ce4cf02a3c852d5196b1d860
https://github.com/ValkSystems/bootbuilder/blob/7601a403f42eba47ce4cf02a3c852d5196b1d860/src/bootbuilder/Validation/Validator.php#L61-L81
train
SlaxWeb/Hooks
src/Hook.php
Hook.create
public function create(string $name, callable $definition) { $this->_name = $name; $this->_definition = $definition; }
php
public function create(string $name, callable $definition) { $this->_name = $name; $this->_definition = $definition; }
[ "public", "function", "create", "(", "string", "$", "name", ",", "callable", "$", "definition", ")", "{", "$", "this", "->", "_name", "=", "$", "name", ";", "$", "this", "->", "_definition", "=", "$", "definition", ";", "}" ]
Create the Hook Create the hook by adding its name and definition to the protected properties. @param string $name Name of the hook @param callable $definition Definition of the hook @return void
[ "Create", "the", "Hook" ]
678f4d5425c27e0dd2a61b68d59bfb2793955b91
https://github.com/SlaxWeb/Hooks/blob/678f4d5425c27e0dd2a61b68d59bfb2793955b91/src/Hook.php#L69-L73
train
Wedeto/DB
src/Query/UpdateField.php
UpdateField.toSQL
public function toSQL(Parameters $params, bool $inner_clause) { $drv = $params->getDriver(); $fieldname = $drv->toSQL($params, $this->getField()); $value = $drv->toSQL($params, $this->getValue()); return $fieldname . ' = ' . $value; }
php
public function toSQL(Parameters $params, bool $inner_clause) { $drv = $params->getDriver(); $fieldname = $drv->toSQL($params, $this->getField()); $value = $drv->toSQL($params, $this->getValue()); return $fieldname . ' = ' . $value; }
[ "public", "function", "toSQL", "(", "Parameters", "$", "params", ",", "bool", "$", "inner_clause", ")", "{", "$", "drv", "=", "$", "params", "->", "getDriver", "(", ")", ";", "$", "fieldname", "=", "$", "drv", "->", "toSQL", "(", "$", "params", ",", "$", "this", "->", "getField", "(", ")", ")", ";", "$", "value", "=", "$", "drv", "->", "toSQL", "(", "$", "params", ",", "$", "this", "->", "getValue", "(", ")", ")", ";", "return", "$", "fieldname", ".", "' = '", ".", "$", "value", ";", "}" ]
Write a update assignment as SQL query syntax @param Parameters $params THe query parameters: tables and placeholder values @param UpdateField $update The field to update and the new value @param bool $inner_clause Unused @return string The generated SQL
[ "Write", "a", "update", "assignment", "as", "SQL", "query", "syntax" ]
715f8f2e3ae6b53c511c40b620921cb9c87e6f62
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Query/UpdateField.php#L71-L78
train
cubicmushroom/valueobjects
src/Web/QueryString.php
QueryString.toDictionary
public function toDictionary() { $value = \ltrim($this->toNative(), '?'); \parse_str($value, $data); return Dictionary::fromNative($data); }
php
public function toDictionary() { $value = \ltrim($this->toNative(), '?'); \parse_str($value, $data); return Dictionary::fromNative($data); }
[ "public", "function", "toDictionary", "(", ")", "{", "$", "value", "=", "\\", "ltrim", "(", "$", "this", "->", "toNative", "(", ")", ",", "'?'", ")", ";", "\\", "parse_str", "(", "$", "value", ",", "$", "data", ")", ";", "return", "Dictionary", "::", "fromNative", "(", "$", "data", ")", ";", "}" ]
Returns a Dictionary structured representation of the query string @return Dictionary
[ "Returns", "a", "Dictionary", "structured", "representation", "of", "the", "query", "string" ]
4554239ab75d65eeb9773219aa5b07e9fbfabb92
https://github.com/cubicmushroom/valueobjects/blob/4554239ab75d65eeb9773219aa5b07e9fbfabb92/src/Web/QueryString.php#L30-L36
train
Vectrex/vxPHP
src/Observer/EventDispatcher.php
EventDispatcher.removeSubscriber
public function removeSubscriber(SubscriberInterface $instance) { // check for object hash if(FALSE !== ($pos = array_search(spl_object_hash($instance), $this->registeredHashes))) { // remove instance from registry before re-inserting unset($this->registeredHashes[$pos]); foreach($instance::getEventsToSubscribe() as $eventName => $parameters) { $methodName = array_shift($parameters); $callable = array($instance, $methodName); foreach($this->registry[$eventName] as $priority => $subscribers) { if (false !== ($pos = array_search($callable, $subscribers, TRUE))) { unset( $this->registry[$eventName][$priority][$pos], $this->sortedRegistry[$eventName] ); } } } } }
php
public function removeSubscriber(SubscriberInterface $instance) { // check for object hash if(FALSE !== ($pos = array_search(spl_object_hash($instance), $this->registeredHashes))) { // remove instance from registry before re-inserting unset($this->registeredHashes[$pos]); foreach($instance::getEventsToSubscribe() as $eventName => $parameters) { $methodName = array_shift($parameters); $callable = array($instance, $methodName); foreach($this->registry[$eventName] as $priority => $subscribers) { if (false !== ($pos = array_search($callable, $subscribers, TRUE))) { unset( $this->registry[$eventName][$priority][$pos], $this->sortedRegistry[$eventName] ); } } } } }
[ "public", "function", "removeSubscriber", "(", "SubscriberInterface", "$", "instance", ")", "{", "// check for object hash", "if", "(", "FALSE", "!==", "(", "$", "pos", "=", "array_search", "(", "spl_object_hash", "(", "$", "instance", ")", ",", "$", "this", "->", "registeredHashes", ")", ")", ")", "{", "// remove instance from registry before re-inserting", "unset", "(", "$", "this", "->", "registeredHashes", "[", "$", "pos", "]", ")", ";", "foreach", "(", "$", "instance", "::", "getEventsToSubscribe", "(", ")", "as", "$", "eventName", "=>", "$", "parameters", ")", "{", "$", "methodName", "=", "array_shift", "(", "$", "parameters", ")", ";", "$", "callable", "=", "array", "(", "$", "instance", ",", "$", "methodName", ")", ";", "foreach", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", "as", "$", "priority", "=>", "$", "subscribers", ")", "{", "if", "(", "false", "!==", "(", "$", "pos", "=", "array_search", "(", "$", "callable", ",", "$", "subscribers", ",", "TRUE", ")", ")", ")", "{", "unset", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", "[", "$", "priority", "]", "[", "$", "pos", "]", ",", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", ")", ";", "}", "}", "}", "}", "}" ]
remove a subscriber from the registry @param SubscriberInterface $instance
[ "remove", "a", "subscriber", "from", "the", "registry" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Observer/EventDispatcher.php#L91-L118
train
Vectrex/vxPHP
src/Observer/EventDispatcher.php
EventDispatcher.addSubscriber
public function addSubscriber(SubscriberInterface $instance) { // make sure that an already registered object is removed before re-registering $this->removeSubscriber($instance); // register object hash $this->registeredHashes[] = spl_object_hash($instance); // parameters contain at least a method name; additionally a priority can be added foreach($instance::getEventsToSubscribe() as $eventName => $parameters) { $parameters = (array) $parameters; $methodName = array_shift($parameters); if(count($parameters)) { $priority = (int) $parameters[0]; } else { $priority = 0; } if(!isset($this->registry[$eventName]) || !isset($this->registry[$eventName][$priority])) { $this->registry[$eventName][$priority] = []; } $this->registry[$eventName][$priority][] = [$instance, $methodName]; // force re-sort upon next dispatch unset ($this->sortedRegistry[$eventName]); } }
php
public function addSubscriber(SubscriberInterface $instance) { // make sure that an already registered object is removed before re-registering $this->removeSubscriber($instance); // register object hash $this->registeredHashes[] = spl_object_hash($instance); // parameters contain at least a method name; additionally a priority can be added foreach($instance::getEventsToSubscribe() as $eventName => $parameters) { $parameters = (array) $parameters; $methodName = array_shift($parameters); if(count($parameters)) { $priority = (int) $parameters[0]; } else { $priority = 0; } if(!isset($this->registry[$eventName]) || !isset($this->registry[$eventName][$priority])) { $this->registry[$eventName][$priority] = []; } $this->registry[$eventName][$priority][] = [$instance, $methodName]; // force re-sort upon next dispatch unset ($this->sortedRegistry[$eventName]); } }
[ "public", "function", "addSubscriber", "(", "SubscriberInterface", "$", "instance", ")", "{", "// make sure that an already registered object is removed before re-registering", "$", "this", "->", "removeSubscriber", "(", "$", "instance", ")", ";", "// register object hash", "$", "this", "->", "registeredHashes", "[", "]", "=", "spl_object_hash", "(", "$", "instance", ")", ";", "// parameters contain at least a method name; additionally a priority can be added", "foreach", "(", "$", "instance", "::", "getEventsToSubscribe", "(", ")", "as", "$", "eventName", "=>", "$", "parameters", ")", "{", "$", "parameters", "=", "(", "array", ")", "$", "parameters", ";", "$", "methodName", "=", "array_shift", "(", "$", "parameters", ")", ";", "if", "(", "count", "(", "$", "parameters", ")", ")", "{", "$", "priority", "=", "(", "int", ")", "$", "parameters", "[", "0", "]", ";", "}", "else", "{", "$", "priority", "=", "0", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", "||", "!", "isset", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", "[", "$", "priority", "]", ")", ")", "{", "$", "this", "->", "registry", "[", "$", "eventName", "]", "[", "$", "priority", "]", "=", "[", "]", ";", "}", "$", "this", "->", "registry", "[", "$", "eventName", "]", "[", "$", "priority", "]", "[", "]", "=", "[", "$", "instance", ",", "$", "methodName", "]", ";", "// force re-sort upon next dispatch", "unset", "(", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", ")", ";", "}", "}" ]
register a subscriber for event types provided by subscriber @param SubscriberInterface $instance
[ "register", "a", "subscriber", "for", "event", "types", "provided", "by", "subscriber" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Observer/EventDispatcher.php#L125-L161
train
Vectrex/vxPHP
src/Observer/EventDispatcher.php
EventDispatcher.getListeners
public function getListeners($eventName = null) { if ($eventName) { if (empty($this->registry[$eventName])) { return []; } return $this->getSortedRegistry($eventName); } foreach ($this->registry as $eventName => $listeners) { $this->getSortedRegistry($eventName); } return $this->sortedRegistry; }
php
public function getListeners($eventName = null) { if ($eventName) { if (empty($this->registry[$eventName])) { return []; } return $this->getSortedRegistry($eventName); } foreach ($this->registry as $eventName => $listeners) { $this->getSortedRegistry($eventName); } return $this->sortedRegistry; }
[ "public", "function", "getListeners", "(", "$", "eventName", "=", "null", ")", "{", "if", "(", "$", "eventName", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", ")", "{", "return", "[", "]", ";", "}", "return", "$", "this", "->", "getSortedRegistry", "(", "$", "eventName", ")", ";", "}", "foreach", "(", "$", "this", "->", "registry", "as", "$", "eventName", "=>", "$", "listeners", ")", "{", "$", "this", "->", "getSortedRegistry", "(", "$", "eventName", ")", ";", "}", "return", "$", "this", "->", "sortedRegistry", ";", "}" ]
get all listeners registered for a given event name if no event name is supplied this will return all registered listeners grouped by event name and sorted by priority @param null $eventName @return array
[ "get", "all", "listeners", "registered", "for", "a", "given", "event", "name", "if", "no", "event", "name", "is", "supplied", "this", "will", "return", "all", "registered", "listeners", "grouped", "by", "event", "name", "and", "sorted", "by", "priority" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Observer/EventDispatcher.php#L202-L220
train
Vectrex/vxPHP
src/Observer/EventDispatcher.php
EventDispatcher.hasListeners
public function hasListeners($eventName = null) { if($eventName) { return !empty($this->registry[$eventName]); } foreach($this->registry as $eventName => $listeners) { if(!empty($listeners)) { return true; } } return false; }
php
public function hasListeners($eventName = null) { if($eventName) { return !empty($this->registry[$eventName]); } foreach($this->registry as $eventName => $listeners) { if(!empty($listeners)) { return true; } } return false; }
[ "public", "function", "hasListeners", "(", "$", "eventName", "=", "null", ")", "{", "if", "(", "$", "eventName", ")", "{", "return", "!", "empty", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", ";", "}", "foreach", "(", "$", "this", "->", "registry", "as", "$", "eventName", "=>", "$", "listeners", ")", "{", "if", "(", "!", "empty", "(", "$", "listeners", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
check whether listeners for a given event name are registered if no event name is supplied this will evaluate to true if there any listeners registered @param string $eventName @return bool
[ "check", "whether", "listeners", "for", "a", "given", "event", "name", "are", "registered", "if", "no", "event", "name", "is", "supplied", "this", "will", "evaluate", "to", "true", "if", "there", "any", "listeners", "registered" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Observer/EventDispatcher.php#L230-L244
train
Vectrex/vxPHP
src/Observer/EventDispatcher.php
EventDispatcher.getSortedRegistry
private function getSortedRegistry($eventName) { if(!isset($this->sortedRegistry[$eventName])) { $this->sortedRegistry[$eventName] = []; if (isset($this->registry[$eventName])) { // sort reverse by priority key krsort($this->registry[$eventName]); // merge the sorted arrays into one $this->sortedRegistry[$eventName] = call_user_func_array('array_merge', $this->registry[$eventName]); } } return $this->sortedRegistry[$eventName]; }
php
private function getSortedRegistry($eventName) { if(!isset($this->sortedRegistry[$eventName])) { $this->sortedRegistry[$eventName] = []; if (isset($this->registry[$eventName])) { // sort reverse by priority key krsort($this->registry[$eventName]); // merge the sorted arrays into one $this->sortedRegistry[$eventName] = call_user_func_array('array_merge', $this->registry[$eventName]); } } return $this->sortedRegistry[$eventName]; }
[ "private", "function", "getSortedRegistry", "(", "$", "eventName", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", ")", ")", "{", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", ")", "{", "// sort reverse by priority key", "krsort", "(", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", ";", "// merge the sorted arrays into one", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", "=", "call_user_func_array", "(", "'array_merge'", ",", "$", "this", "->", "registry", "[", "$", "eventName", "]", ")", ";", "}", "}", "return", "$", "this", "->", "sortedRegistry", "[", "$", "eventName", "]", ";", "}" ]
helper method to collect all listener callbacks for a named event into one array observing priorities @param string $eventName @return array
[ "helper", "method", "to", "collect", "all", "listener", "callbacks", "for", "a", "named", "event", "into", "one", "array", "observing", "priorities" ]
295c21b00e7ef6085efcdf5b64fabb28d499b5a6
https://github.com/Vectrex/vxPHP/blob/295c21b00e7ef6085efcdf5b64fabb28d499b5a6/src/Observer/EventDispatcher.php#L254-L274
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/LinkFilterer.php
LinkFilterer.noReferer
public function noReferer() { if ($this->getParameter('url') == null) return; if ($this->getParameter('service') == null) return "http://hiderefer.com/?" . $this->getParameter('url'); return $this->getParameter('service') . $this->getParameter('url'); }
php
public function noReferer() { if ($this->getParameter('url') == null) return; if ($this->getParameter('service') == null) return "http://hiderefer.com/?" . $this->getParameter('url'); return $this->getParameter('service') . $this->getParameter('url'); }
[ "public", "function", "noReferer", "(", ")", "{", "if", "(", "$", "this", "->", "getParameter", "(", "'url'", ")", "==", "null", ")", "return", ";", "if", "(", "$", "this", "->", "getParameter", "(", "'service'", ")", "==", "null", ")", "return", "\"http://hiderefer.com/?\"", ".", "$", "this", "->", "getParameter", "(", "'url'", ")", ";", "return", "$", "this", "->", "getParameter", "(", "'service'", ")", ".", "$", "this", "->", "getParameter", "(", "'url'", ")", ";", "}" ]
Returns a url safe from referers Expected Params: url string A url to be filtered through hiderefer.com @return string The specified url filtered through hiderefer.com
[ "Returns", "a", "url", "safe", "from", "referers" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/LinkFilterer.php#L112-L121
train
wb-crowdfusion/crowdfusion
system/core/classes/mvc/filters/LinkFilterer.php
LinkFilterer.appendQueryString
public function appendQueryString() { $url = $this->getParameter('url'); $params = $this->getParameters(); unset($params['url']); return URLUtils::appendQueryString($url, $params); }
php
public function appendQueryString() { $url = $this->getParameter('url'); $params = $this->getParameters(); unset($params['url']); return URLUtils::appendQueryString($url, $params); }
[ "public", "function", "appendQueryString", "(", ")", "{", "$", "url", "=", "$", "this", "->", "getParameter", "(", "'url'", ")", ";", "$", "params", "=", "$", "this", "->", "getParameters", "(", ")", ";", "unset", "(", "$", "params", "[", "'url'", "]", ")", ";", "return", "URLUtils", "::", "appendQueryString", "(", "$", "url", ",", "$", "params", ")", ";", "}" ]
Constructs a URL with query string arguments from the given base url and parameters Expected Params: url string the URL to build a query string from [params] mixed any additional parameters serve as query string arguments @return string a complete url
[ "Constructs", "a", "URL", "with", "query", "string", "arguments", "from", "the", "given", "base", "url", "and", "parameters" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/mvc/filters/LinkFilterer.php#L146-L153
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.getTitleById
public static function getTitleById($table, $id) { //return "table = ".$table." and id = ".$id; // Special handling for users if ($table == "users") { return self::getUserForIndexListing($id); } // Special handling for posts (for post updates listing) if ($table == "posts") { return self::getPostForIndexListing($id); } $title = DB::table($table)->where('id', '=', $id)->pluck('title'); if ($title == "") { return '<span class="text-danger">n/a</span>'; } // ASSIGN COLOURS TO lookup_todo_priority_types if ($table == "lookup_todo_priority_types") { if (strtolower($title) == "green") { return '<button type="button" class="btn btn-success btn-sm">'.$title.'</button>'; } if (strtolower($title) == "yellow") { return '<button type="button" class="btn btn-warning btn-sm">'.$title.'</button>'; } if (strtolower($title) == "red") { return '<button type="button" class="btn btn-danger btn-sm">'.$title.'</button>'; } } return $title; }
php
public static function getTitleById($table, $id) { //return "table = ".$table." and id = ".$id; // Special handling for users if ($table == "users") { return self::getUserForIndexListing($id); } // Special handling for posts (for post updates listing) if ($table == "posts") { return self::getPostForIndexListing($id); } $title = DB::table($table)->where('id', '=', $id)->pluck('title'); if ($title == "") { return '<span class="text-danger">n/a</span>'; } // ASSIGN COLOURS TO lookup_todo_priority_types if ($table == "lookup_todo_priority_types") { if (strtolower($title) == "green") { return '<button type="button" class="btn btn-success btn-sm">'.$title.'</button>'; } if (strtolower($title) == "yellow") { return '<button type="button" class="btn btn-warning btn-sm">'.$title.'</button>'; } if (strtolower($title) == "red") { return '<button type="button" class="btn btn-danger btn-sm">'.$title.'</button>'; } } return $title; }
[ "public", "static", "function", "getTitleById", "(", "$", "table", ",", "$", "id", ")", "{", "//return \"table = \".$table.\" and id = \".$id;", "// Special handling for users", "if", "(", "$", "table", "==", "\"users\"", ")", "{", "return", "self", "::", "getUserForIndexListing", "(", "$", "id", ")", ";", "}", "// Special handling for posts (for post updates listing)", "if", "(", "$", "table", "==", "\"posts\"", ")", "{", "return", "self", "::", "getPostForIndexListing", "(", "$", "id", ")", ";", "}", "$", "title", "=", "DB", "::", "table", "(", "$", "table", ")", "->", "where", "(", "'id'", ",", "'='", ",", "$", "id", ")", "->", "pluck", "(", "'title'", ")", ";", "if", "(", "$", "title", "==", "\"\"", ")", "{", "return", "'<span class=\"text-danger\">n/a</span>'", ";", "}", "// ASSIGN COLOURS TO lookup_todo_priority_types", "if", "(", "$", "table", "==", "\"lookup_todo_priority_types\"", ")", "{", "if", "(", "strtolower", "(", "$", "title", ")", "==", "\"green\"", ")", "{", "return", "'<button type=\"button\" class=\"btn btn-success btn-sm\">'", ".", "$", "title", ".", "'</button>'", ";", "}", "if", "(", "strtolower", "(", "$", "title", ")", "==", "\"yellow\"", ")", "{", "return", "'<button type=\"button\" class=\"btn btn-warning btn-sm\">'", ".", "$", "title", ".", "'</button>'", ";", "}", "if", "(", "strtolower", "(", "$", "title", ")", "==", "\"red\"", ")", "{", "return", "'<button type=\"button\" class=\"btn btn-danger btn-sm\">'", ".", "$", "title", ".", "'</button>'", ";", "}", "}", "return", "$", "title", ";", "}" ]
Grab the title by ID @param string $table @param int $id @return string
[ "Grab", "the", "title", "by", "ID" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L146-L184
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.getPostForIndexListing
public static function getPostForIndexListing($id) { // Actually, it's dangerous and confusing to have the link to the post's EDIT // form display in the post update's create/edit form. So, I am omitting // the link; and, instead, am displaying the post's title with the post's // ID in brackets. /* $post = DB::table('posts')->where('id', $id)->first(); $html = '<a href="'; $html .= URL::route('admin.posts.edit', $id); $html .= '" target="_blank">'.$post->title.'</a>'; */ $title = DB::table('posts')->where('id', '=', $id)->pluck('title'); $html = $title." (".$id.")"; return $html; }
php
public static function getPostForIndexListing($id) { // Actually, it's dangerous and confusing to have the link to the post's EDIT // form display in the post update's create/edit form. So, I am omitting // the link; and, instead, am displaying the post's title with the post's // ID in brackets. /* $post = DB::table('posts')->where('id', $id)->first(); $html = '<a href="'; $html .= URL::route('admin.posts.edit', $id); $html .= '" target="_blank">'.$post->title.'</a>'; */ $title = DB::table('posts')->where('id', '=', $id)->pluck('title'); $html = $title." (".$id.")"; return $html; }
[ "public", "static", "function", "getPostForIndexListing", "(", "$", "id", ")", "{", "// Actually, it's dangerous and confusing to have the link to the post's EDIT", "// form display in the post update's create/edit form. So, I am omitting", "// the link; and, instead, am displaying the post's title with the post's", "// ID in brackets.", "/*\n $post = DB::table('posts')->where('id', $id)->first();\n $html = '<a href=\"';\n $html .= URL::route('admin.posts.edit', $id);\n $html .= '\" target=\"_blank\">'.$post->title.'</a>';\n */", "$", "title", "=", "DB", "::", "table", "(", "'posts'", ")", "->", "where", "(", "'id'", ",", "'='", ",", "$", "id", ")", "->", "pluck", "(", "'title'", ")", ";", "$", "html", "=", "$", "title", ".", "\" (\"", ".", "$", "id", ".", "\")\"", ";", "return", "$", "html", ";", "}" ]
Grab the Post info from the "posts" table. Created specifically for the "Post Updates" index listing @param int $id @return string
[ "Grab", "the", "Post", "info", "from", "the", "posts", "table", ".", "Created", "specifically", "for", "the", "Post", "Updates", "index", "listing" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L217-L235
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.finagleVarcharFieldTypeForIndexListing
public static function finagleVarcharFieldTypeForIndexListing($field, $data) { if (empty($field['persist_wash'])) { return $data; } if (strtolower($field['persist_wash']) == "url") { $prefacedURL = self::prefaceURLwithHTTP($data); return '<a href="'.$prefacedURL.'" target="_blank">'.$data.'</a>'; } return $data; }
php
public static function finagleVarcharFieldTypeForIndexListing($field, $data) { if (empty($field['persist_wash'])) { return $data; } if (strtolower($field['persist_wash']) == "url") { $prefacedURL = self::prefaceURLwithHTTP($data); return '<a href="'.$prefacedURL.'" target="_blank">'.$data.'</a>'; } return $data; }
[ "public", "static", "function", "finagleVarcharFieldTypeForIndexListing", "(", "$", "field", ",", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "field", "[", "'persist_wash'", "]", ")", ")", "{", "return", "$", "data", ";", "}", "if", "(", "strtolower", "(", "$", "field", "[", "'persist_wash'", "]", ")", "==", "\"url\"", ")", "{", "$", "prefacedURL", "=", "self", "::", "prefaceURLwithHTTP", "(", "$", "data", ")", ";", "return", "'<a href=\"'", ".", "$", "prefacedURL", ".", "'\" target=\"_blank\">'", ".", "$", "data", ".", "'</a>'", ";", "}", "return", "$", "data", ";", "}" ]
Need a helper method to finagle the varchar field in the index listing. @param array $field @param string $data @return string
[ "Need", "a", "helper", "method", "to", "finagle", "the", "varchar", "field", "in", "the", "index", "listing", "." ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L245-L256
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.categoryParentSingleSelectCreate
public static function categoryParentSingleSelectCreate($categories) { // STEP 1: Initiatize the html select tag $html = ""; $html .= '<select name="parent_id" id="parent_id" size="6" class="form-control" >'; $html .= '<option '; $html .= 'value="'; $html .= 0; $html .= '">'; $html .= 'No Parent Category'; $html .= '</option>"'; // STEP 2: Construct the <option></option> categories for ALL categories in the categories table foreach ($categories as $category) { $html .= '<option '; $html .= 'value="'; $html .= $category->id; $html .= '">'; $html .= $category->title; $html .= '</option>"'; } $html .= '</select>'; $html .= self::renderBootstrapMultiselectPlugin(count($categories)); return $html; }
php
public static function categoryParentSingleSelectCreate($categories) { // STEP 1: Initiatize the html select tag $html = ""; $html .= '<select name="parent_id" id="parent_id" size="6" class="form-control" >'; $html .= '<option '; $html .= 'value="'; $html .= 0; $html .= '">'; $html .= 'No Parent Category'; $html .= '</option>"'; // STEP 2: Construct the <option></option> categories for ALL categories in the categories table foreach ($categories as $category) { $html .= '<option '; $html .= 'value="'; $html .= $category->id; $html .= '">'; $html .= $category->title; $html .= '</option>"'; } $html .= '</select>'; $html .= self::renderBootstrapMultiselectPlugin(count($categories)); return $html; }
[ "public", "static", "function", "categoryParentSingleSelectCreate", "(", "$", "categories", ")", "{", "// STEP 1: Initiatize the html select tag", "$", "html", "=", "\"\"", ";", "$", "html", ".=", "'<select name=\"parent_id\" id=\"parent_id\" size=\"6\" class=\"form-control\" >'", ";", "$", "html", ".=", "'<option '", ";", "$", "html", ".=", "'value=\"'", ";", "$", "html", ".=", "0", ";", "$", "html", ".=", "'\">'", ";", "$", "html", ".=", "'No Parent Category'", ";", "$", "html", ".=", "'</option>\"'", ";", "// STEP 2: Construct the <option></option> categories for ALL categories in the categories table", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "$", "html", ".=", "'<option '", ";", "$", "html", ".=", "'value=\"'", ";", "$", "html", ".=", "$", "category", "->", "id", ";", "$", "html", ".=", "'\">'", ";", "$", "html", ".=", "$", "category", "->", "title", ";", "$", "html", ".=", "'</option>\"'", ";", "}", "$", "html", ".=", "'</select>'", ";", "$", "html", ".=", "self", "::", "renderBootstrapMultiselectPlugin", "(", "count", "(", "$", "categories", ")", ")", ";", "return", "$", "html", ";", "}" ]
Create a dropdown with a single select for the parent category @param collection $categories Laravel collection object of category @return string
[ "Create", "a", "dropdown", "with", "a", "single", "select", "for", "the", "parent", "category" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L287-L314
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.categoryParentSingleSelectEdit
public static function categoryParentSingleSelectEdit($categories, $parent_id, $category_id) { // STEP 1: Initiatize the html select tag $html = ""; $html .= '<select name="parent_id" id="parent_id" size="6" class="form-control">'; $html .= '<option '; if ( $parent_id == 0) { $html .= ' selected="selected" '; } $html .= 'value="'; $html .= 0; $html .= '">'; $html .= 'No Parent Category'; $html .= '</option>"'; // STEP 2: Construct the <option></option> categories for ALL categories in the categories table foreach ($categories as $category) { if ($category->id == $category_id) { continue; } // If this tag is attached to the post, then SELECTED it $selected = ""; if ( $category->id == $parent_id ) { $selected = ' selected="selected" '; } $html .= '<option '; $html .= $selected; $html .= 'value="'; $html .= $category->id; $html .= '">'; $html .= $category->title; $html .= '</option>"'; } $html .= '</select>'; $html .= self::renderBootstrapMultiselectPlugin(count($categories)); return $html; }
php
public static function categoryParentSingleSelectEdit($categories, $parent_id, $category_id) { // STEP 1: Initiatize the html select tag $html = ""; $html .= '<select name="parent_id" id="parent_id" size="6" class="form-control">'; $html .= '<option '; if ( $parent_id == 0) { $html .= ' selected="selected" '; } $html .= 'value="'; $html .= 0; $html .= '">'; $html .= 'No Parent Category'; $html .= '</option>"'; // STEP 2: Construct the <option></option> categories for ALL categories in the categories table foreach ($categories as $category) { if ($category->id == $category_id) { continue; } // If this tag is attached to the post, then SELECTED it $selected = ""; if ( $category->id == $parent_id ) { $selected = ' selected="selected" '; } $html .= '<option '; $html .= $selected; $html .= 'value="'; $html .= $category->id; $html .= '">'; $html .= $category->title; $html .= '</option>"'; } $html .= '</select>'; $html .= self::renderBootstrapMultiselectPlugin(count($categories)); return $html; }
[ "public", "static", "function", "categoryParentSingleSelectEdit", "(", "$", "categories", ",", "$", "parent_id", ",", "$", "category_id", ")", "{", "// STEP 1: Initiatize the html select tag", "$", "html", "=", "\"\"", ";", "$", "html", ".=", "'<select name=\"parent_id\" id=\"parent_id\" size=\"6\" class=\"form-control\">'", ";", "$", "html", ".=", "'<option '", ";", "if", "(", "$", "parent_id", "==", "0", ")", "{", "$", "html", ".=", "' selected=\"selected\" '", ";", "}", "$", "html", ".=", "'value=\"'", ";", "$", "html", ".=", "0", ";", "$", "html", ".=", "'\">'", ";", "$", "html", ".=", "'No Parent Category'", ";", "$", "html", ".=", "'</option>\"'", ";", "// STEP 2: Construct the <option></option> categories for ALL categories in the categories table", "foreach", "(", "$", "categories", "as", "$", "category", ")", "{", "if", "(", "$", "category", "->", "id", "==", "$", "category_id", ")", "{", "continue", ";", "}", "// If this tag is attached to the post, then SELECTED it", "$", "selected", "=", "\"\"", ";", "if", "(", "$", "category", "->", "id", "==", "$", "parent_id", ")", "{", "$", "selected", "=", "' selected=\"selected\" '", ";", "}", "$", "html", ".=", "'<option '", ";", "$", "html", ".=", "$", "selected", ";", "$", "html", ".=", "'value=\"'", ";", "$", "html", ".=", "$", "category", "->", "id", ";", "$", "html", ".=", "'\">'", ";", "$", "html", ".=", "$", "category", "->", "title", ";", "$", "html", ".=", "'</option>\"'", ";", "}", "$", "html", ".=", "'</select>'", ";", "$", "html", ".=", "self", "::", "renderBootstrapMultiselectPlugin", "(", "count", "(", "$", "categories", ")", ")", ";", "return", "$", "html", ";", "}" ]
Create a multiple select drop down for tags that have the existing tags for that post already selected There is only one parent_id per category @param collection $categories All categories @param int $parent id category's parent id @param int $category id category's id @return string
[ "Create", "a", "multiple", "select", "drop", "down", "for", "tags", "that", "have", "the", "existing", "tags", "for", "that", "post", "already", "selected" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L327-L372
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.adminPageTitle
public static function adminPageTitle($package_title, $table_type_plural, $extra_title='') { $table_type_plural = self::properPlural($table_type_plural); $html = ''; $html .= '<br /><br />'; $html .= '<div class="row">'; $html .= ' <div class="oaerror info">'; $html .= ' <strong>'.$package_title.'</strong> - '.ucwords($table_type_plural); $html .= ' '.$extra_title; $html .= ' </div'; $html .= '<br /><br />'; $html .= '</div>'; $html .= '<br /><br />'; return $html; }
php
public static function adminPageTitle($package_title, $table_type_plural, $extra_title='') { $table_type_plural = self::properPlural($table_type_plural); $html = ''; $html .= '<br /><br />'; $html .= '<div class="row">'; $html .= ' <div class="oaerror info">'; $html .= ' <strong>'.$package_title.'</strong> - '.ucwords($table_type_plural); $html .= ' '.$extra_title; $html .= ' </div'; $html .= '<br /><br />'; $html .= '</div>'; $html .= '<br /><br />'; return $html; }
[ "public", "static", "function", "adminPageTitle", "(", "$", "package_title", ",", "$", "table_type_plural", ",", "$", "extra_title", "=", "''", ")", "{", "$", "table_type_plural", "=", "self", "::", "properPlural", "(", "$", "table_type_plural", ")", ";", "$", "html", "=", "''", ";", "$", "html", ".=", "'<br /><br />'", ";", "$", "html", ".=", "'<div class=\"row\">'", ";", "$", "html", ".=", "' <div class=\"oaerror info\">'", ";", "$", "html", ".=", "' <strong>'", ".", "$", "package_title", ".", "'</strong> - '", ".", "ucwords", "(", "$", "table_type_plural", ")", ";", "$", "html", ".=", "' '", ".", "$", "extra_title", ";", "$", "html", ".=", "' </div'", ";", "$", "html", ".=", "'<br /><br />'", ";", "$", "html", ".=", "'</div>'", ";", "$", "html", ".=", "'<br /><br />'", ";", "return", "$", "html", ";", "}" ]
Page title for admin pages @param string $package_title package's title @param string $table_type_plural table's type, in the plural @param string $extra_title extra text to append to the table's title @return string
[ "Page", "title", "for", "admin", "pages" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L426-L442
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.adminPageSubTitle
public static function adminPageSubTitle($record = null, $modelClass, $show=false) { $modelClass = self::properPlural($modelClass); $html = ''; $html .= '<div class="row">'; $html .= '<div class="col-md-3"></div>'; $html .= '<div class="col-md-6">'; $html .= '<h1>'; $html .= '<span class="label label-info">'; // Edit or Create? if ($record) { $html .= 'Edit the '; if ($show) { $html .= 'Show the '; } else { $html .= 'Edit the '; } $html .= ucwords($modelClass); $html .= ': "'; $html .= $record->title; $html .= '"'; } else { $html .= 'Create '; $html .= ucwords($modelClass); } $html .= '</span>'; $html .= '</h1>'; $html .= '</div>'; $html .= '<div class="col-md-3"></div>'; $html .= '</div>'; return $html; }
php
public static function adminPageSubTitle($record = null, $modelClass, $show=false) { $modelClass = self::properPlural($modelClass); $html = ''; $html .= '<div class="row">'; $html .= '<div class="col-md-3"></div>'; $html .= '<div class="col-md-6">'; $html .= '<h1>'; $html .= '<span class="label label-info">'; // Edit or Create? if ($record) { $html .= 'Edit the '; if ($show) { $html .= 'Show the '; } else { $html .= 'Edit the '; } $html .= ucwords($modelClass); $html .= ': "'; $html .= $record->title; $html .= '"'; } else { $html .= 'Create '; $html .= ucwords($modelClass); } $html .= '</span>'; $html .= '</h1>'; $html .= '</div>'; $html .= '<div class="col-md-3"></div>'; $html .= '</div>'; return $html; }
[ "public", "static", "function", "adminPageSubTitle", "(", "$", "record", "=", "null", ",", "$", "modelClass", ",", "$", "show", "=", "false", ")", "{", "$", "modelClass", "=", "self", "::", "properPlural", "(", "$", "modelClass", ")", ";", "$", "html", "=", "''", ";", "$", "html", ".=", "'<div class=\"row\">'", ";", "$", "html", ".=", "'<div class=\"col-md-3\"></div>'", ";", "$", "html", ".=", "'<div class=\"col-md-6\">'", ";", "$", "html", ".=", "'<h1>'", ";", "$", "html", ".=", "'<span class=\"label label-info\">'", ";", "// Edit or Create?", "if", "(", "$", "record", ")", "{", "$", "html", ".=", "'Edit the '", ";", "if", "(", "$", "show", ")", "{", "$", "html", ".=", "'Show the '", ";", "}", "else", "{", "$", "html", ".=", "'Edit the '", ";", "}", "$", "html", ".=", "ucwords", "(", "$", "modelClass", ")", ";", "$", "html", ".=", "': \"'", ";", "$", "html", ".=", "$", "record", "->", "title", ";", "$", "html", ".=", "'\"'", ";", "}", "else", "{", "$", "html", ".=", "'Create '", ";", "$", "html", ".=", "ucwords", "(", "$", "modelClass", ")", ";", "}", "$", "html", ".=", "'</span>'", ";", "$", "html", ".=", "'</h1>'", ";", "$", "html", ".=", "'</div>'", ";", "$", "html", ".=", "'<div class=\"col-md-3\"></div>'", ";", "$", "html", ".=", "'</div>'", ";", "return", "$", "html", ";", "}" ]
Display button with a label describing what the form is doing. @param object $record Optional record from the database @param string $modelClass The model's classname @param bool $show True when from controller SHOW @return string
[ "Display", "button", "with", "a", "label", "describing", "what", "the", "form", "is", "doing", "." ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L452-L490
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.adminFormFieldLabel
public static function adminFormFieldLabel($field) { // Does the field have an alternate name? $name = $field['name']; if (!empty($field['alternate_form_name'])) { $name = $field['alternate_form_name']; } if ($name == "id") return "ID"; $html = str_replace("_", " ", $name); $html = ucwords($html); return $html; }
php
public static function adminFormFieldLabel($field) { // Does the field have an alternate name? $name = $field['name']; if (!empty($field['alternate_form_name'])) { $name = $field['alternate_form_name']; } if ($name == "id") return "ID"; $html = str_replace("_", " ", $name); $html = ucwords($html); return $html; }
[ "public", "static", "function", "adminFormFieldLabel", "(", "$", "field", ")", "{", "// Does the field have an alternate name?", "$", "name", "=", "$", "field", "[", "'name'", "]", ";", "if", "(", "!", "empty", "(", "$", "field", "[", "'alternate_form_name'", "]", ")", ")", "{", "$", "name", "=", "$", "field", "[", "'alternate_form_name'", "]", ";", "}", "if", "(", "$", "name", "==", "\"id\"", ")", "return", "\"ID\"", ";", "$", "html", "=", "str_replace", "(", "\"_\"", ",", "\" \"", ",", "$", "name", ")", ";", "$", "html", "=", "ucwords", "(", "$", "html", ")", ";", "return", "$", "html", ";", "}" ]
Transform the field name into a format suitable for a form label @param array $field Form field array from the model @return string
[ "Transform", "the", "field", "name", "into", "a", "format", "suitable", "for", "a", "form", "label" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L504-L518
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.properPlural
public static function properPlural($pluralWordToCheck) { $listOfPlurals = [ 'categorys' => 'categories', 'kb_item' => 'item', 'kb_items' => 'Items', 'list_email' => 'email list', 'listlist' => 'list', 'people' => 'person', 'peoples' => 'people', 'postupdate' =>'post update', 'postupdates' =>'post updates', 'social' => 'social site', 'socials' => 'social sites', 'todo_items' => 'To Do items', 'Todo_item' => 'To Do Item', 'email_messages' => 'Email Messages', 'email_message' => 'Email Message', ]; foreach ($listOfPlurals as $improperPlural => $correctPlural) { if (strtolower($improperPlural) == strtolower($pluralWordToCheck)) { return $correctPlural; } } return $pluralWordToCheck; }
php
public static function properPlural($pluralWordToCheck) { $listOfPlurals = [ 'categorys' => 'categories', 'kb_item' => 'item', 'kb_items' => 'Items', 'list_email' => 'email list', 'listlist' => 'list', 'people' => 'person', 'peoples' => 'people', 'postupdate' =>'post update', 'postupdates' =>'post updates', 'social' => 'social site', 'socials' => 'social sites', 'todo_items' => 'To Do items', 'Todo_item' => 'To Do Item', 'email_messages' => 'Email Messages', 'email_message' => 'Email Message', ]; foreach ($listOfPlurals as $improperPlural => $correctPlural) { if (strtolower($improperPlural) == strtolower($pluralWordToCheck)) { return $correctPlural; } } return $pluralWordToCheck; }
[ "public", "static", "function", "properPlural", "(", "$", "pluralWordToCheck", ")", "{", "$", "listOfPlurals", "=", "[", "'categorys'", "=>", "'categories'", ",", "'kb_item'", "=>", "'item'", ",", "'kb_items'", "=>", "'Items'", ",", "'list_email'", "=>", "'email list'", ",", "'listlist'", "=>", "'list'", ",", "'people'", "=>", "'person'", ",", "'peoples'", "=>", "'people'", ",", "'postupdate'", "=>", "'post update'", ",", "'postupdates'", "=>", "'post updates'", ",", "'social'", "=>", "'social site'", ",", "'socials'", "=>", "'social sites'", ",", "'todo_items'", "=>", "'To Do items'", ",", "'Todo_item'", "=>", "'To Do Item'", ",", "'email_messages'", "=>", "'Email Messages'", ",", "'email_message'", "=>", "'Email Message'", ",", "]", ";", "foreach", "(", "$", "listOfPlurals", "as", "$", "improperPlural", "=>", "$", "correctPlural", ")", "{", "if", "(", "strtolower", "(", "$", "improperPlural", ")", "==", "strtolower", "(", "$", "pluralWordToCheck", ")", ")", "{", "return", "$", "correctPlural", ";", "}", "}", "return", "$", "pluralWordToCheck", ";", "}" ]
Is the plural word grammatically correct? Also, a method to specify custom admin form subtitle names (regular create/edit forms), and called from Formhandler's AdminBaseFormController. @param string $pluralWordToCheck Plural word to check @return string
[ "Is", "the", "plural", "word", "grammatically", "correct?" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L636-L663
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.determineEpisodeImagePath
public static function determineEpisodeImagePath($episode, $show) { if (empty($episode->featured_image)) { // I'm gonna be a very bad boy here and just return the cloudfront path, // because, at this point, LaSalleCast is just for moi, and I use AWS cloudfront return $show->featured_image; //return Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image; } return $show->image_file_storage_url . $episode->featured_image; }
php
public static function determineEpisodeImagePath($episode, $show) { if (empty($episode->featured_image)) { // I'm gonna be a very bad boy here and just return the cloudfront path, // because, at this point, LaSalleCast is just for moi, and I use AWS cloudfront return $show->featured_image; //return Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image; } return $show->image_file_storage_url . $episode->featured_image; }
[ "public", "static", "function", "determineEpisodeImagePath", "(", "$", "episode", ",", "$", "show", ")", "{", "if", "(", "empty", "(", "$", "episode", "->", "featured_image", ")", ")", "{", "// I'm gonna be a very bad boy here and just return the cloudfront path,", "// because, at this point, LaSalleCast is just for moi, and I use AWS cloudfront", "return", "$", "show", "->", "featured_image", ";", "//return Config('app.url') .'/'. Config::get('lasallecastfrontend.images_shows') .'/'. $show->featured_image;", "}", "return", "$", "show", "->", "image_file_storage_url", ".", "$", "episode", "->", "featured_image", ";", "}" ]
What is the episode's image's path? @param $episode @param $show @return string
[ "What", "is", "the", "episode", "s", "image", "s", "path?" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L848-L860
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.createOpenGraphTagsForPost
public static function createOpenGraphTagsForPost($post) { return [ 'og:title' => $post->title, 'og:type' => 'article', 'og:url' => $post->canonical_url, 'og:image' => $post->urlImage, 'og:description' => $post->meta_description, 'og:site_name' => Config::get('lasallecmsfrontend.og_site_name'), 'article:published_time' => $post->created_at, 'article:modified_time' => $post->updated_at, ]; }
php
public static function createOpenGraphTagsForPost($post) { return [ 'og:title' => $post->title, 'og:type' => 'article', 'og:url' => $post->canonical_url, 'og:image' => $post->urlImage, 'og:description' => $post->meta_description, 'og:site_name' => Config::get('lasallecmsfrontend.og_site_name'), 'article:published_time' => $post->created_at, 'article:modified_time' => $post->updated_at, ]; }
[ "public", "static", "function", "createOpenGraphTagsForPost", "(", "$", "post", ")", "{", "return", "[", "'og:title'", "=>", "$", "post", "->", "title", ",", "'og:type'", "=>", "'article'", ",", "'og:url'", "=>", "$", "post", "->", "canonical_url", ",", "'og:image'", "=>", "$", "post", "->", "urlImage", ",", "'og:description'", "=>", "$", "post", "->", "meta_description", ",", "'og:site_name'", "=>", "Config", "::", "get", "(", "'lasallecmsfrontend.og_site_name'", ")", ",", "'article:published_time'", "=>", "$", "post", "->", "created_at", ",", "'article:modified_time'", "=>", "$", "post", "->", "updated_at", ",", "]", ";", "}" ]
Create an array of OG tags and their values for a post. https://developers.facebook.com/docs/sharing/webmasters @param object $post The post object. @return array
[ "Create", "an", "array", "of", "OG", "tags", "and", "their", "values", "for", "a", "post", "." ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L876-L887
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.createTwitterTagsForPost
public static function createTwitterTagsForPost($post) { return [ 'twitter:card' => Config::get('lasallecmsfrontend.twitter_card'), 'twitter:site' => Config::get('lasallecmsfrontend.twitter_site'), 'twitter:title' => $post->title, 'twitter:description' => $post->meta_description, 'twitter:creator' => Config::get('lasallecmsfrontend.twitter_creator'), //'twitter:image:src' => $post->urlImage, 'twitter:image' => $post->urlImage, ]; }
php
public static function createTwitterTagsForPost($post) { return [ 'twitter:card' => Config::get('lasallecmsfrontend.twitter_card'), 'twitter:site' => Config::get('lasallecmsfrontend.twitter_site'), 'twitter:title' => $post->title, 'twitter:description' => $post->meta_description, 'twitter:creator' => Config::get('lasallecmsfrontend.twitter_creator'), //'twitter:image:src' => $post->urlImage, 'twitter:image' => $post->urlImage, ]; }
[ "public", "static", "function", "createTwitterTagsForPost", "(", "$", "post", ")", "{", "return", "[", "'twitter:card'", "=>", "Config", "::", "get", "(", "'lasallecmsfrontend.twitter_card'", ")", ",", "'twitter:site'", "=>", "Config", "::", "get", "(", "'lasallecmsfrontend.twitter_site'", ")", ",", "'twitter:title'", "=>", "$", "post", "->", "title", ",", "'twitter:description'", "=>", "$", "post", "->", "meta_description", ",", "'twitter:creator'", "=>", "Config", "::", "get", "(", "'lasallecmsfrontend.twitter_creator'", ")", ",", "//'twitter:image:src' => $post->urlImage,", "'twitter:image'", "=>", "$", "post", "->", "urlImage", ",", "]", ";", "}" ]
Create an array of Twitter tags and their values for a post. https://dev.twitter.com/cards/overview @param object $post The post object. @return array
[ "Create", "an", "array", "of", "Twitter", "tags", "and", "their", "values", "for", "a", "post", "." ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L897-L907
train
lasallecms/lasallecms-l5-helpers-pkg
src/HTML/HTMLHelper.php
HTMLHelper.prefaceURLwithHTTP
public static function prefaceURLwithHTTP($url) { $url = trim($url); if (substr($url, 0, 7 ) == "http://") { return $url; } if (substr($url, 0, 8 ) == "https://") { return $url; } return "http://".$url; }
php
public static function prefaceURLwithHTTP($url) { $url = trim($url); if (substr($url, 0, 7 ) == "http://") { return $url; } if (substr($url, 0, 8 ) == "https://") { return $url; } return "http://".$url; }
[ "public", "static", "function", "prefaceURLwithHTTP", "(", "$", "url", ")", "{", "$", "url", "=", "trim", "(", "$", "url", ")", ";", "if", "(", "substr", "(", "$", "url", ",", "0", ",", "7", ")", "==", "\"http://\"", ")", "{", "return", "$", "url", ";", "}", "if", "(", "substr", "(", "$", "url", ",", "0", ",", "8", ")", "==", "\"https://\"", ")", "{", "return", "$", "url", ";", "}", "return", "\"http://\"", ".", "$", "url", ";", "}" ]
Make sure the URL is fully qualified @param string $url @return string
[ "Make", "sure", "the", "URL", "is", "fully", "qualified" ]
733967ce3fd81a1efba5265e11663c324ff983c4
https://github.com/lasallecms/lasallecms-l5-helpers-pkg/blob/733967ce3fd81a1efba5265e11663c324ff983c4/src/HTML/HTMLHelper.php#L940-L952
train
ekyna/Resource
Doctrine/ORM/Mapping/EmbeddableMapper.php
EmbeddableMapper.processClassMetadata
public function processClassMetadata(ClassMetadata $metadata, $property, $prefix) { if (in_array($metadata->getName(), $this->processedClasses)) { return; } $metadata->mapEmbedded([ 'fieldName' => $property, 'class' => $this->embeddableMetadata->getName(), 'columnPrefix' => empty($prefix) ? false : $prefix, ]); $metadata->inlineEmbeddable($property, $this->embeddableMetadata); $this->processedClasses[] = $metadata->getName(); }
php
public function processClassMetadata(ClassMetadata $metadata, $property, $prefix) { if (in_array($metadata->getName(), $this->processedClasses)) { return; } $metadata->mapEmbedded([ 'fieldName' => $property, 'class' => $this->embeddableMetadata->getName(), 'columnPrefix' => empty($prefix) ? false : $prefix, ]); $metadata->inlineEmbeddable($property, $this->embeddableMetadata); $this->processedClasses[] = $metadata->getName(); }
[ "public", "function", "processClassMetadata", "(", "ClassMetadata", "$", "metadata", ",", "$", "property", ",", "$", "prefix", ")", "{", "if", "(", "in_array", "(", "$", "metadata", "->", "getName", "(", ")", ",", "$", "this", "->", "processedClasses", ")", ")", "{", "return", ";", "}", "$", "metadata", "->", "mapEmbedded", "(", "[", "'fieldName'", "=>", "$", "property", ",", "'class'", "=>", "$", "this", "->", "embeddableMetadata", "->", "getName", "(", ")", ",", "'columnPrefix'", "=>", "empty", "(", "$", "prefix", ")", "?", "false", ":", "$", "prefix", ",", "]", ")", ";", "$", "metadata", "->", "inlineEmbeddable", "(", "$", "property", ",", "$", "this", "->", "embeddableMetadata", ")", ";", "$", "this", "->", "processedClasses", "[", "]", "=", "$", "metadata", "->", "getName", "(", ")", ";", "}" ]
Processes the class metadata. @param ClassMetadata $metadata @param string $property @param string $prefix
[ "Processes", "the", "class", "metadata", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Doctrine/ORM/Mapping/EmbeddableMapper.php#L49-L64
train
ekyna/Resource
Serializer/AbstractResourceNormalizer.php
AbstractResourceNormalizer.normalizeObject
protected function normalizeObject($object, $format, array $context) { if (!$this->serializer instanceof NormalizerInterface) { throw new LogicException( 'Cannot normalize object because the injected serializer is not a normalizer' ); } return $this->serializer->normalize($object, $format, $context); }
php
protected function normalizeObject($object, $format, array $context) { if (!$this->serializer instanceof NormalizerInterface) { throw new LogicException( 'Cannot normalize object because the injected serializer is not a normalizer' ); } return $this->serializer->normalize($object, $format, $context); }
[ "protected", "function", "normalizeObject", "(", "$", "object", ",", "$", "format", ",", "array", "$", "context", ")", "{", "if", "(", "!", "$", "this", "->", "serializer", "instanceof", "NormalizerInterface", ")", "{", "throw", "new", "LogicException", "(", "'Cannot normalize object because the injected serializer is not a normalizer'", ")", ";", "}", "return", "$", "this", "->", "serializer", "->", "normalize", "(", "$", "object", ",", "$", "format", ",", "$", "context", ")", ";", "}" ]
Normalizes the object. @param object $object @param string $format @param array $context @return array|string
[ "Normalizes", "the", "object", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Serializer/AbstractResourceNormalizer.php#L93-L102
train
ekyna/Resource
Serializer/AbstractResourceNormalizer.php
AbstractResourceNormalizer.denormalizeObject
protected function denormalizeObject($data, $class, $format, array $context) { if (!$this->serializer instanceof DenormalizerInterface) { throw new LogicException( 'Cannot denormalize object because the injected serializer is not a denormalizer' ); } return $this->serializer->denormalize($data, $class, $format, $context); }
php
protected function denormalizeObject($data, $class, $format, array $context) { if (!$this->serializer instanceof DenormalizerInterface) { throw new LogicException( 'Cannot denormalize object because the injected serializer is not a denormalizer' ); } return $this->serializer->denormalize($data, $class, $format, $context); }
[ "protected", "function", "denormalizeObject", "(", "$", "data", ",", "$", "class", ",", "$", "format", ",", "array", "$", "context", ")", "{", "if", "(", "!", "$", "this", "->", "serializer", "instanceof", "DenormalizerInterface", ")", "{", "throw", "new", "LogicException", "(", "'Cannot denormalize object because the injected serializer is not a denormalizer'", ")", ";", "}", "return", "$", "this", "->", "serializer", "->", "denormalize", "(", "$", "data", ",", "$", "class", ",", "$", "format", ",", "$", "context", ")", ";", "}" ]
Denormalizes the object. @param array $data @param string $class @param string $format @param array $context @return object|void
[ "Denormalizes", "the", "object", "." ]
96ee3d28e02bd9513705408e3bb7f88a76e52f56
https://github.com/ekyna/Resource/blob/96ee3d28e02bd9513705408e3bb7f88a76e52f56/Serializer/AbstractResourceNormalizer.php#L122-L131
train
hoffmann-oss/arrays-php
src/Arrays2d.php
Arrays2d.rotateX
public static function rotateX(array &$array, int $distance, int $startX = 0, int $startY = 0, int $stopX = null, int $stopY = null) { self::prepare($array, $stopX, $stopY); $rotateLeft = $distance > 0; $distance = abs($distance) % ($stopX - $startX); $x = $rotateLeft ? $startX + $distance : $stopX - $distance; self::reverseX($array, $startX, $startY, $x, $stopY); self::reverseX($array, $x, $startY, $stopX, $stopY); self::reverseX($array, $startX, $startY, $stopX, $stopY); }
php
public static function rotateX(array &$array, int $distance, int $startX = 0, int $startY = 0, int $stopX = null, int $stopY = null) { self::prepare($array, $stopX, $stopY); $rotateLeft = $distance > 0; $distance = abs($distance) % ($stopX - $startX); $x = $rotateLeft ? $startX + $distance : $stopX - $distance; self::reverseX($array, $startX, $startY, $x, $stopY); self::reverseX($array, $x, $startY, $stopX, $stopY); self::reverseX($array, $startX, $startY, $stopX, $stopY); }
[ "public", "static", "function", "rotateX", "(", "array", "&", "$", "array", ",", "int", "$", "distance", ",", "int", "$", "startX", "=", "0", ",", "int", "$", "startY", "=", "0", ",", "int", "$", "stopX", "=", "null", ",", "int", "$", "stopY", "=", "null", ")", "{", "self", "::", "prepare", "(", "$", "array", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "$", "rotateLeft", "=", "$", "distance", ">", "0", ";", "$", "distance", "=", "abs", "(", "$", "distance", ")", "%", "(", "$", "stopX", "-", "$", "startX", ")", ";", "$", "x", "=", "$", "rotateLeft", "?", "$", "startX", "+", "$", "distance", ":", "$", "stopX", "-", "$", "distance", ";", "self", "::", "reverseX", "(", "$", "array", ",", "$", "startX", ",", "$", "startY", ",", "$", "x", ",", "$", "stopY", ")", ";", "self", "::", "reverseX", "(", "$", "array", ",", "$", "x", ",", "$", "startY", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "self", "::", "reverseX", "(", "$", "array", ",", "$", "startX", ",", "$", "startY", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "}" ]
Array items rotate left if distance is greater than 0.
[ "Array", "items", "rotate", "left", "if", "distance", "is", "greater", "than", "0", "." ]
e565352ef6118acefe6ec02c0e85f1c3f78642df
https://github.com/hoffmann-oss/arrays-php/blob/e565352ef6118acefe6ec02c0e85f1c3f78642df/src/Arrays2d.php#L73-L83
train
hoffmann-oss/arrays-php
src/Arrays2d.php
Arrays2d.rotateY
public static function rotateY(array &$array, int $distance, int $startX = 0, int $startY = 0, int $stopX = null, int $stopY = null) { self::prepare($array, $stopX, $stopY); $rotateUp = $distance > 0; $distance = abs($distance) % ($stopY - $startY); $y = $rotateUp ? $startY + $distance : $stopY - $distance; self::reverseY($array, $startX, $startY, $stopX, $y); self::reverseY($array, $startX, $y, $stopX, $stopY); self::reverseY($array, $startX, $startY, $stopX, $stopY); }
php
public static function rotateY(array &$array, int $distance, int $startX = 0, int $startY = 0, int $stopX = null, int $stopY = null) { self::prepare($array, $stopX, $stopY); $rotateUp = $distance > 0; $distance = abs($distance) % ($stopY - $startY); $y = $rotateUp ? $startY + $distance : $stopY - $distance; self::reverseY($array, $startX, $startY, $stopX, $y); self::reverseY($array, $startX, $y, $stopX, $stopY); self::reverseY($array, $startX, $startY, $stopX, $stopY); }
[ "public", "static", "function", "rotateY", "(", "array", "&", "$", "array", ",", "int", "$", "distance", ",", "int", "$", "startX", "=", "0", ",", "int", "$", "startY", "=", "0", ",", "int", "$", "stopX", "=", "null", ",", "int", "$", "stopY", "=", "null", ")", "{", "self", "::", "prepare", "(", "$", "array", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "$", "rotateUp", "=", "$", "distance", ">", "0", ";", "$", "distance", "=", "abs", "(", "$", "distance", ")", "%", "(", "$", "stopY", "-", "$", "startY", ")", ";", "$", "y", "=", "$", "rotateUp", "?", "$", "startY", "+", "$", "distance", ":", "$", "stopY", "-", "$", "distance", ";", "self", "::", "reverseY", "(", "$", "array", ",", "$", "startX", ",", "$", "startY", ",", "$", "stopX", ",", "$", "y", ")", ";", "self", "::", "reverseY", "(", "$", "array", ",", "$", "startX", ",", "$", "y", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "self", "::", "reverseY", "(", "$", "array", ",", "$", "startX", ",", "$", "startY", ",", "$", "stopX", ",", "$", "stopY", ")", ";", "}" ]
Array items rotate up if distance is greater than 0.
[ "Array", "items", "rotate", "up", "if", "distance", "is", "greater", "than", "0", "." ]
e565352ef6118acefe6ec02c0e85f1c3f78642df
https://github.com/hoffmann-oss/arrays-php/blob/e565352ef6118acefe6ec02c0e85f1c3f78642df/src/Arrays2d.php#L88-L98
train
imsamurai/CakePHP-AdvancedShell
Console/Command/AdvancedShell.php
AdvancedShell.statisticsEnd
public function statisticsEnd($name) { $this->hr(); $this->out('Took: ' . $this->_startTime[$name]->diff(new DateTime())->format('%ad %hh %im %ss')); $this->out('Memory: ' . sprintf('%0.3f', memory_get_peak_usage(true) / (1024 * 1024)) . "Mb max used"); $this->hr(); }
php
public function statisticsEnd($name) { $this->hr(); $this->out('Took: ' . $this->_startTime[$name]->diff(new DateTime())->format('%ad %hh %im %ss')); $this->out('Memory: ' . sprintf('%0.3f', memory_get_peak_usage(true) / (1024 * 1024)) . "Mb max used"); $this->hr(); }
[ "public", "function", "statisticsEnd", "(", "$", "name", ")", "{", "$", "this", "->", "hr", "(", ")", ";", "$", "this", "->", "out", "(", "'Took: '", ".", "$", "this", "->", "_startTime", "[", "$", "name", "]", "->", "diff", "(", "new", "DateTime", "(", ")", ")", "->", "format", "(", "'%ad %hh %im %ss'", ")", ")", ";", "$", "this", "->", "out", "(", "'Memory: '", ".", "sprintf", "(", "'%0.3f'", ",", "memory_get_peak_usage", "(", "true", ")", "/", "(", "1024", "*", "1024", ")", ")", ".", "\"Mb max used\"", ")", ";", "$", "this", "->", "hr", "(", ")", ";", "}" ]
Stop and output statistics @param string $name
[ "Stop", "and", "output", "statistics" ]
087d483742e2a76bee45e35b8d94957b0d20f857
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/AdvancedShell.php#L76-L81
train
imsamurai/CakePHP-AdvancedShell
Console/Command/AdvancedShell.php
AdvancedShell.sqlDump
public function sqlDump($sorted = false, $clear = true) { if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) { return; } $sources = ConnectionManager::sourceList(); $logs = array(); foreach ($sources as $source) { $db = ConnectionManager::getDataSource($source); if (!method_exists($db, 'getLog')) { continue; } $logs[$source] = $db->getLog($sorted, $clear); } if (empty($logs)) { return; } $this->out('<b>SQL dump:</b>'); foreach ($logs as $source => $log) { $this->out("<b>Source: $source, queries: {$log['count']}, took: {$log['time']}ms</b>"); foreach ($log['log'] as $k => $i) { $i += array('error' => ''); $this->out(($k + 1) . ". {$i['query']} <sqlinfo>{e:{$i['error']}, a:{$i['affected']}, t:{$i['took']}, n:{$i['numRows']}}</sqlinfo>"); } } }
php
public function sqlDump($sorted = false, $clear = true) { if (!class_exists('ConnectionManager') || Configure::read('debug') < 2) { return; } $sources = ConnectionManager::sourceList(); $logs = array(); foreach ($sources as $source) { $db = ConnectionManager::getDataSource($source); if (!method_exists($db, 'getLog')) { continue; } $logs[$source] = $db->getLog($sorted, $clear); } if (empty($logs)) { return; } $this->out('<b>SQL dump:</b>'); foreach ($logs as $source => $log) { $this->out("<b>Source: $source, queries: {$log['count']}, took: {$log['time']}ms</b>"); foreach ($log['log'] as $k => $i) { $i += array('error' => ''); $this->out(($k + 1) . ". {$i['query']} <sqlinfo>{e:{$i['error']}, a:{$i['affected']}, t:{$i['took']}, n:{$i['numRows']}}</sqlinfo>"); } } }
[ "public", "function", "sqlDump", "(", "$", "sorted", "=", "false", ",", "$", "clear", "=", "true", ")", "{", "if", "(", "!", "class_exists", "(", "'ConnectionManager'", ")", "||", "Configure", "::", "read", "(", "'debug'", ")", "<", "2", ")", "{", "return", ";", "}", "$", "sources", "=", "ConnectionManager", "::", "sourceList", "(", ")", ";", "$", "logs", "=", "array", "(", ")", ";", "foreach", "(", "$", "sources", "as", "$", "source", ")", "{", "$", "db", "=", "ConnectionManager", "::", "getDataSource", "(", "$", "source", ")", ";", "if", "(", "!", "method_exists", "(", "$", "db", ",", "'getLog'", ")", ")", "{", "continue", ";", "}", "$", "logs", "[", "$", "source", "]", "=", "$", "db", "->", "getLog", "(", "$", "sorted", ",", "$", "clear", ")", ";", "}", "if", "(", "empty", "(", "$", "logs", ")", ")", "{", "return", ";", "}", "$", "this", "->", "out", "(", "'<b>SQL dump:</b>'", ")", ";", "foreach", "(", "$", "logs", "as", "$", "source", "=>", "$", "log", ")", "{", "$", "this", "->", "out", "(", "\"<b>Source: $source, queries: {$log['count']}, took: {$log['time']}ms</b>\"", ")", ";", "foreach", "(", "$", "log", "[", "'log'", "]", "as", "$", "k", "=>", "$", "i", ")", "{", "$", "i", "+=", "array", "(", "'error'", "=>", "''", ")", ";", "$", "this", "->", "out", "(", "(", "$", "k", "+", "1", ")", ".", "\". {$i['query']} <sqlinfo>{e:{$i['error']}, a:{$i['affected']}, t:{$i['took']}, n:{$i['numRows']}}</sqlinfo>\"", ")", ";", "}", "}", "}" ]
Shows sql dump @param bool $sorted Get the queries sorted by time taken, defaults to false. @param bool $clear If True the existing log will cleared.
[ "Shows", "sql", "dump" ]
087d483742e2a76bee45e35b8d94957b0d20f857
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/AdvancedShell.php#L108-L135
train
bartonlp/site-class
includes/database-engines/dbAbstract.class.php
dbAbstract.query
public function query($query) { if(method_exists($this->db, 'query')) { return $this->db->query($query); } else { throw new Exception(__METHOD__ . " not implemented"); } }
php
public function query($query) { if(method_exists($this->db, 'query')) { return $this->db->query($query); } else { throw new Exception(__METHOD__ . " not implemented"); } }
[ "public", "function", "query", "(", "$", "query", ")", "{", "if", "(", "method_exists", "(", "$", "this", "->", "db", ",", "'query'", ")", ")", "{", "return", "$", "this", "->", "db", "->", "query", "(", "$", "query", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "__METHOD__", ".", "\" not implemented\"", ")", ";", "}", "}" ]
The following methods either execute or if the method is not defined throw an Exception
[ "The", "following", "methods", "either", "execute", "or", "if", "the", "method", "is", "not", "defined", "throw", "an", "Exception" ]
9095b101701ef0ae12ea9a2b4587a18072d04438
https://github.com/bartonlp/site-class/blob/9095b101701ef0ae12ea9a2b4587a18072d04438/includes/database-engines/dbAbstract.class.php#L34-L40
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.allowAttribute
public function allowAttribute($attribute) { if (is_array($attribute)) { foreach ($attribute as $attrib) $this->allowed_attributes[$attrib] = true; } else $this->allowed_attributes[$attribute] = true; return $this; }
php
public function allowAttribute($attribute) { if (is_array($attribute)) { foreach ($attribute as $attrib) $this->allowed_attributes[$attrib] = true; } else $this->allowed_attributes[$attribute] = true; return $this; }
[ "public", "function", "allowAttribute", "(", "$", "attribute", ")", "{", "if", "(", "is_array", "(", "$", "attribute", ")", ")", "{", "foreach", "(", "$", "attribute", "as", "$", "attrib", ")", "$", "this", "->", "allowed_attributes", "[", "$", "attrib", "]", "=", "true", ";", "}", "else", "$", "this", "->", "allowed_attributes", "[", "$", "attribute", "]", "=", "true", ";", "return", "$", "this", ";", "}" ]
Add an attribute to the whitelist @param $attribute string|Array The name of the attribute to add to the whitelist. Can also be an array to add multiple attributes. @return SafeHTML Provides fluent interface
[ "Add", "an", "attribute", "to", "the", "whitelist" ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L131-L141
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.removeTag
public function removeTag($tag) { if (is_array($tag)) { foreach ($tag as $t) { if (isset($this->allowed_tags[$t])) unset($this->allowed_tags[$t]); $this->remove_tags[$t] = true; } } else { if (isset($this->allowed_tags[$tag])) unset($this->allowed_tags[$tag]); $this->remove_tags[$tag] = true; } return $this; }
php
public function removeTag($tag) { if (is_array($tag)) { foreach ($tag as $t) { if (isset($this->allowed_tags[$t])) unset($this->allowed_tags[$t]); $this->remove_tags[$t] = true; } } else { if (isset($this->allowed_tags[$tag])) unset($this->allowed_tags[$tag]); $this->remove_tags[$tag] = true; } return $this; }
[ "public", "function", "removeTag", "(", "$", "tag", ")", "{", "if", "(", "is_array", "(", "$", "tag", ")", ")", "{", "foreach", "(", "$", "tag", "as", "$", "t", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "allowed_tags", "[", "$", "t", "]", ")", ")", "unset", "(", "$", "this", "->", "allowed_tags", "[", "$", "t", "]", ")", ";", "$", "this", "->", "remove_tags", "[", "$", "t", "]", "=", "true", ";", "}", "}", "else", "{", "if", "(", "isset", "(", "$", "this", "->", "allowed_tags", "[", "$", "tag", "]", ")", ")", "unset", "(", "$", "this", "->", "allowed_tags", "[", "$", "tag", "]", ")", ";", "$", "this", "->", "remove_tags", "[", "$", "tag", "]", "=", "true", ";", "}", "return", "$", "this", ";", "}" ]
Add a tag to the list of tags to remove including all child nodes @param $tag string|array The name of the tag to add to the remove list Can also be an array to add multiple tags. @return SafeHTML Provides fluent interface
[ "Add", "a", "tag", "to", "the", "list", "of", "tags", "to", "remove", "including", "all", "child", "nodes" ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L163-L181
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.allowProtocol
public function allowProtocol($protocol) { if (is_array($protocol)) { foreach ($protocol as $proto) $this->allowed_protocols[$proto] = true; } else $this->allowed_protocols[$protocol] = true; return $this; }
php
public function allowProtocol($protocol) { if (is_array($protocol)) { foreach ($protocol as $proto) $this->allowed_protocols[$proto] = true; } else $this->allowed_protocols[$protocol] = true; return $this; }
[ "public", "function", "allowProtocol", "(", "$", "protocol", ")", "{", "if", "(", "is_array", "(", "$", "protocol", ")", ")", "{", "foreach", "(", "$", "protocol", "as", "$", "proto", ")", "$", "this", "->", "allowed_protocols", "[", "$", "proto", "]", "=", "true", ";", "}", "else", "$", "this", "->", "allowed_protocols", "[", "$", "protocol", "]", "=", "true", ";", "return", "$", "this", ";", "}" ]
Add a protocol to the list of protocols to allow linking to. @param $protocl string|array The protocol to add to the whitelist. Can also be an array to add multiple protocols. @return SafeHTML Provides fluent interface
[ "Add", "a", "protocol", "to", "the", "list", "of", "protocols", "to", "allow", "linking", "to", "." ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L189-L199
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.getHTML
public function getHTML() { $dom = new DOMDocument(); $interceptor = new ErrorInterceptor(array($dom, 'loadHTML')); $interceptor->registerError(E_WARNING, "DOMDocument::loadHTML"); $interceptor->execute($this->html); $body = $dom->getElementsByTagName('body')->item(0); $this->sanitizeNode($body); $html = ""; foreach ($body->childNodes as $n) $html .= $dom->saveHTML($n); return $html; }
php
public function getHTML() { $dom = new DOMDocument(); $interceptor = new ErrorInterceptor(array($dom, 'loadHTML')); $interceptor->registerError(E_WARNING, "DOMDocument::loadHTML"); $interceptor->execute($this->html); $body = $dom->getElementsByTagName('body')->item(0); $this->sanitizeNode($body); $html = ""; foreach ($body->childNodes as $n) $html .= $dom->saveHTML($n); return $html; }
[ "public", "function", "getHTML", "(", ")", "{", "$", "dom", "=", "new", "DOMDocument", "(", ")", ";", "$", "interceptor", "=", "new", "ErrorInterceptor", "(", "array", "(", "$", "dom", ",", "'loadHTML'", ")", ")", ";", "$", "interceptor", "->", "registerError", "(", "E_WARNING", ",", "\"DOMDocument::loadHTML\"", ")", ";", "$", "interceptor", "->", "execute", "(", "$", "this", "->", "html", ")", ";", "$", "body", "=", "$", "dom", "->", "getElementsByTagName", "(", "'body'", ")", "->", "item", "(", "0", ")", ";", "$", "this", "->", "sanitizeNode", "(", "$", "body", ")", ";", "$", "html", "=", "\"\"", ";", "foreach", "(", "$", "body", "->", "childNodes", "as", "$", "n", ")", "$", "html", ".=", "$", "dom", "->", "saveHTML", "(", "$", "n", ")", ";", "return", "$", "html", ";", "}" ]
Return the sanitized HTML, according to the set up list of tags and attributes. @return string The sanitized HTML
[ "Return", "the", "sanitized", "HTML", "according", "to", "the", "set", "up", "list", "of", "tags", "and", "attributes", "." ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L243-L260
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.sanitizeNode
private function sanitizeNode(DOMNode $node) { // Traverse the nodes, without foreach because nodes may be removed $child = (!empty($node->childNodes) && $node->childNodes->length > 0) ? $node->childNodes->item(0) : null; while ($child !== null) { $tag = $child->nodeName; // Allow text nodes if ($tag === "#text") { $child = $child->nextSibling; continue; } if (isset($this->remove_tags[$tag])) { // Tag is on the list of nodes to fully remove including child nodes $remove = $child; $child = $child->nextSibling; $node->removeChild($remove); } elseif (!isset($this->allowed_tags[$tag])) { // Add the child nodes of the disalowed tag to the parent node in its place, // and move the pointer to the first inserted child node, or the next node. $child = $this->unwrapContents($node, $child); } else { // Sanitize the attributes of an allowed tag if ($child->attributes !== null) $this->sanitizeAttributes($child); // And now process the contents $this->sanitizeNode($child); // Finally, call a callback if applicable if (isset($this->tag_callback[$tag])) $this->tag_callback[$tag]($child); $child = $child->nextSibling; } } }
php
private function sanitizeNode(DOMNode $node) { // Traverse the nodes, without foreach because nodes may be removed $child = (!empty($node->childNodes) && $node->childNodes->length > 0) ? $node->childNodes->item(0) : null; while ($child !== null) { $tag = $child->nodeName; // Allow text nodes if ($tag === "#text") { $child = $child->nextSibling; continue; } if (isset($this->remove_tags[$tag])) { // Tag is on the list of nodes to fully remove including child nodes $remove = $child; $child = $child->nextSibling; $node->removeChild($remove); } elseif (!isset($this->allowed_tags[$tag])) { // Add the child nodes of the disalowed tag to the parent node in its place, // and move the pointer to the first inserted child node, or the next node. $child = $this->unwrapContents($node, $child); } else { // Sanitize the attributes of an allowed tag if ($child->attributes !== null) $this->sanitizeAttributes($child); // And now process the contents $this->sanitizeNode($child); // Finally, call a callback if applicable if (isset($this->tag_callback[$tag])) $this->tag_callback[$tag]($child); $child = $child->nextSibling; } } }
[ "private", "function", "sanitizeNode", "(", "DOMNode", "$", "node", ")", "{", "// Traverse the nodes, without foreach because nodes may be removed", "$", "child", "=", "(", "!", "empty", "(", "$", "node", "->", "childNodes", ")", "&&", "$", "node", "->", "childNodes", "->", "length", ">", "0", ")", "?", "$", "node", "->", "childNodes", "->", "item", "(", "0", ")", ":", "null", ";", "while", "(", "$", "child", "!==", "null", ")", "{", "$", "tag", "=", "$", "child", "->", "nodeName", ";", "// Allow text nodes", "if", "(", "$", "tag", "===", "\"#text\"", ")", "{", "$", "child", "=", "$", "child", "->", "nextSibling", ";", "continue", ";", "}", "if", "(", "isset", "(", "$", "this", "->", "remove_tags", "[", "$", "tag", "]", ")", ")", "{", "// Tag is on the list of nodes to fully remove including child nodes", "$", "remove", "=", "$", "child", ";", "$", "child", "=", "$", "child", "->", "nextSibling", ";", "$", "node", "->", "removeChild", "(", "$", "remove", ")", ";", "}", "elseif", "(", "!", "isset", "(", "$", "this", "->", "allowed_tags", "[", "$", "tag", "]", ")", ")", "{", "// Add the child nodes of the disalowed tag to the parent node in its place,", "// and move the pointer to the first inserted child node, or the next node.", "$", "child", "=", "$", "this", "->", "unwrapContents", "(", "$", "node", ",", "$", "child", ")", ";", "}", "else", "{", "// Sanitize the attributes of an allowed tag", "if", "(", "$", "child", "->", "attributes", "!==", "null", ")", "$", "this", "->", "sanitizeAttributes", "(", "$", "child", ")", ";", "// And now process the contents", "$", "this", "->", "sanitizeNode", "(", "$", "child", ")", ";", "// Finally, call a callback if applicable", "if", "(", "isset", "(", "$", "this", "->", "tag_callback", "[", "$", "tag", "]", ")", ")", "$", "this", "->", "tag_callback", "[", "$", "tag", "]", "(", "$", "child", ")", ";", "$", "child", "=", "$", "child", "->", "nextSibling", ";", "}", "}", "}" ]
Helper function to recursively sanitize nodes @param $node DOMNode The node to sanitize
[ "Helper", "function", "to", "recursively", "sanitize", "nodes" ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L267-L311
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.unwrapContents
private function unwrapContents(DOMNode $node, DOMNode $child) { // Preserve the content by adding the child nodes to the parent $next = $child->nextSibling; if ($next === null) $next = $child; if ($child->childNodes !== null) { $l = $child->childNodes->length; for ($i = $l - 1; $i >= 0; --$i) { // This try/catch seems not necessary as it does not actually // check HTML rules, it will gladly accept <option> in a <p>, // or <li> in a <div> for example. // //try //{ $sub = $child->childNodes[$i]; $next = $node->insertBefore($sub, $next); //} //catch (DOMException $ex) //{} } } // Finally, remove the node $node->removeChild($child); // Next is now either: // 1) the last inserted child == the top of the list of new nodes // 2) if the unwrapped node had no children, the next node // 3) if the unwrapped node was the last node, it's the unwrapped node itself // // 1 and 2 do what is expected, in the case of 3, there is no next node, // so null should be returned, rather than the removed node. return ($next !== null && $next->isSameNode($child)) ? null : $next; }
php
private function unwrapContents(DOMNode $node, DOMNode $child) { // Preserve the content by adding the child nodes to the parent $next = $child->nextSibling; if ($next === null) $next = $child; if ($child->childNodes !== null) { $l = $child->childNodes->length; for ($i = $l - 1; $i >= 0; --$i) { // This try/catch seems not necessary as it does not actually // check HTML rules, it will gladly accept <option> in a <p>, // or <li> in a <div> for example. // //try //{ $sub = $child->childNodes[$i]; $next = $node->insertBefore($sub, $next); //} //catch (DOMException $ex) //{} } } // Finally, remove the node $node->removeChild($child); // Next is now either: // 1) the last inserted child == the top of the list of new nodes // 2) if the unwrapped node had no children, the next node // 3) if the unwrapped node was the last node, it's the unwrapped node itself // // 1 and 2 do what is expected, in the case of 3, there is no next node, // so null should be returned, rather than the removed node. return ($next !== null && $next->isSameNode($child)) ? null : $next; }
[ "private", "function", "unwrapContents", "(", "DOMNode", "$", "node", ",", "DOMNode", "$", "child", ")", "{", "// Preserve the content by adding the child nodes to the parent", "$", "next", "=", "$", "child", "->", "nextSibling", ";", "if", "(", "$", "next", "===", "null", ")", "$", "next", "=", "$", "child", ";", "if", "(", "$", "child", "->", "childNodes", "!==", "null", ")", "{", "$", "l", "=", "$", "child", "->", "childNodes", "->", "length", ";", "for", "(", "$", "i", "=", "$", "l", "-", "1", ";", "$", "i", ">=", "0", ";", "--", "$", "i", ")", "{", "// This try/catch seems not necessary as it does not actually", "// check HTML rules, it will gladly accept <option> in a <p>,", "// or <li> in a <div> for example.", "//", "//try", "//{", "$", "sub", "=", "$", "child", "->", "childNodes", "[", "$", "i", "]", ";", "$", "next", "=", "$", "node", "->", "insertBefore", "(", "$", "sub", ",", "$", "next", ")", ";", "//}", "//catch (DOMException $ex)", "//{}", "}", "}", "// Finally, remove the node", "$", "node", "->", "removeChild", "(", "$", "child", ")", ";", "// Next is now either:", "// 1) the last inserted child == the top of the list of new nodes", "// 2) if the unwrapped node had no children, the next node", "// 3) if the unwrapped node was the last node, it's the unwrapped node itself", "//", "// 1 and 2 do what is expected, in the case of 3, there is no next node,", "// so null should be returned, rather than the removed node.", "return", "(", "$", "next", "!==", "null", "&&", "$", "next", "->", "isSameNode", "(", "$", "child", ")", ")", "?", "null", ":", "$", "next", ";", "}" ]
Helper function to unwrap the contents of a node and remove the node. @param $node DOMNode The node from which to remove the child @param $child DOMNode The child to remove from the node @return The first newly added node, or if none were added, the next sibling node
[ "Helper", "function", "to", "unwrap", "the", "contents", "of", "a", "node", "and", "remove", "the", "node", "." ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L319-L356
train
Wedeto/HTML
src/SafeHTML.php
SafeHTML.sanitizeAttributes
private function sanitizeAttributes(DOMNode $child) { // Compile a list of attributes that should be removed $remove_attributes = array(); foreach ($child->attributes as $attrib) { $name = $attrib->name; if (!isset($this->allowed_attributes[$name])) { $remove_attributes[] = $attrib; } elseif ($name === "href") { $val = $attrib->nodeValue; $is_allowed = false; $proto_pos = strpos($val, ":"); if ($proto_pos !== false) { $proto = strtolower(substr($val, 0, $proto_pos)); if (isset($this->allowed_protocols[$proto])) $is_allowed = true; } elseif (substr($val, 0, 2) === '//') { // External link with same protocol if (isset($this->allowed_protocols['https'])) $is_allowed = true; } else { // Internal link $is_allowed = true; } if (!$is_allowed) $remove_attributes[] = $attrib; } } // Remove all nodes selected for removal foreach ($remove_attributes as $attrib) $child->removeAttributeNode($attrib); }
php
private function sanitizeAttributes(DOMNode $child) { // Compile a list of attributes that should be removed $remove_attributes = array(); foreach ($child->attributes as $attrib) { $name = $attrib->name; if (!isset($this->allowed_attributes[$name])) { $remove_attributes[] = $attrib; } elseif ($name === "href") { $val = $attrib->nodeValue; $is_allowed = false; $proto_pos = strpos($val, ":"); if ($proto_pos !== false) { $proto = strtolower(substr($val, 0, $proto_pos)); if (isset($this->allowed_protocols[$proto])) $is_allowed = true; } elseif (substr($val, 0, 2) === '//') { // External link with same protocol if (isset($this->allowed_protocols['https'])) $is_allowed = true; } else { // Internal link $is_allowed = true; } if (!$is_allowed) $remove_attributes[] = $attrib; } } // Remove all nodes selected for removal foreach ($remove_attributes as $attrib) $child->removeAttributeNode($attrib); }
[ "private", "function", "sanitizeAttributes", "(", "DOMNode", "$", "child", ")", "{", "// Compile a list of attributes that should be removed", "$", "remove_attributes", "=", "array", "(", ")", ";", "foreach", "(", "$", "child", "->", "attributes", "as", "$", "attrib", ")", "{", "$", "name", "=", "$", "attrib", "->", "name", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "allowed_attributes", "[", "$", "name", "]", ")", ")", "{", "$", "remove_attributes", "[", "]", "=", "$", "attrib", ";", "}", "elseif", "(", "$", "name", "===", "\"href\"", ")", "{", "$", "val", "=", "$", "attrib", "->", "nodeValue", ";", "$", "is_allowed", "=", "false", ";", "$", "proto_pos", "=", "strpos", "(", "$", "val", ",", "\":\"", ")", ";", "if", "(", "$", "proto_pos", "!==", "false", ")", "{", "$", "proto", "=", "strtolower", "(", "substr", "(", "$", "val", ",", "0", ",", "$", "proto_pos", ")", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "allowed_protocols", "[", "$", "proto", "]", ")", ")", "$", "is_allowed", "=", "true", ";", "}", "elseif", "(", "substr", "(", "$", "val", ",", "0", ",", "2", ")", "===", "'//'", ")", "{", "// External link with same protocol", "if", "(", "isset", "(", "$", "this", "->", "allowed_protocols", "[", "'https'", "]", ")", ")", "$", "is_allowed", "=", "true", ";", "}", "else", "{", "// Internal link", "$", "is_allowed", "=", "true", ";", "}", "if", "(", "!", "$", "is_allowed", ")", "$", "remove_attributes", "[", "]", "=", "$", "attrib", ";", "}", "}", "// Remove all nodes selected for removal", "foreach", "(", "$", "remove_attributes", "as", "$", "attrib", ")", "$", "child", "->", "removeAttributeNode", "(", "$", "attrib", ")", ";", "}" ]
Helper function to sanitize the attributes for the specified node. @param $child DOMNode the child to examine
[ "Helper", "function", "to", "sanitize", "the", "attributes", "for", "the", "specified", "node", "." ]
9e725288098c42d0d2953a929faebe628ff4e389
https://github.com/Wedeto/HTML/blob/9e725288098c42d0d2953a929faebe628ff4e389/src/SafeHTML.php#L362-L403
train
aegis-security/JSON
src/JSON.php
JSON._recursiveJsonExprFinder
protected static function _recursiveJsonExprFinder( &$value, array &$javascriptExpressions, $currentKey = null ) { if ($value instanceof Expr) { // TODO: Optimize with ascii keys, if performance is bad $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions)); $javascriptExpressions[] = array( //if currentKey is integer, encodeUnicodeString call is not required. "magicKey" => (is_int($currentKey)) ? $magicKey : Encoder::encodeUnicodeString($magicKey), "value" => $value->__toString(), ); $value = $magicKey; } elseif (is_array($value)) { foreach ($value as $k => $v) { $value[$k] = static::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k); } } elseif (is_object($value)) { foreach ($value as $k => $v) { $value->$k = static::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k); } } return $value; }
php
protected static function _recursiveJsonExprFinder( &$value, array &$javascriptExpressions, $currentKey = null ) { if ($value instanceof Expr) { // TODO: Optimize with ascii keys, if performance is bad $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions)); $javascriptExpressions[] = array( //if currentKey is integer, encodeUnicodeString call is not required. "magicKey" => (is_int($currentKey)) ? $magicKey : Encoder::encodeUnicodeString($magicKey), "value" => $value->__toString(), ); $value = $magicKey; } elseif (is_array($value)) { foreach ($value as $k => $v) { $value[$k] = static::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k); } } elseif (is_object($value)) { foreach ($value as $k => $v) { $value->$k = static::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k); } } return $value; }
[ "protected", "static", "function", "_recursiveJsonExprFinder", "(", "&", "$", "value", ",", "array", "&", "$", "javascriptExpressions", ",", "$", "currentKey", "=", "null", ")", "{", "if", "(", "$", "value", "instanceof", "Expr", ")", "{", "// TODO: Optimize with ascii keys, if performance is bad", "$", "magicKey", "=", "\"____\"", ".", "$", "currentKey", ".", "\"_\"", ".", "(", "count", "(", "$", "javascriptExpressions", ")", ")", ";", "$", "javascriptExpressions", "[", "]", "=", "array", "(", "//if currentKey is integer, encodeUnicodeString call is not required.", "\"magicKey\"", "=>", "(", "is_int", "(", "$", "currentKey", ")", ")", "?", "$", "magicKey", ":", "Encoder", "::", "encodeUnicodeString", "(", "$", "magicKey", ")", ",", "\"value\"", "=>", "$", "value", "->", "__toString", "(", ")", ",", ")", ";", "$", "value", "=", "$", "magicKey", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "value", "[", "$", "k", "]", "=", "static", "::", "_recursiveJsonExprFinder", "(", "$", "value", "[", "$", "k", "]", ",", "$", "javascriptExpressions", ",", "$", "k", ")", ";", "}", "}", "elseif", "(", "is_object", "(", "$", "value", ")", ")", "{", "foreach", "(", "$", "value", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "value", "->", "$", "k", "=", "static", "::", "_recursiveJsonExprFinder", "(", "$", "value", "->", "$", "k", ",", "$", "javascriptExpressions", ",", "$", "k", ")", ";", "}", "}", "return", "$", "value", ";", "}" ]
Check & Replace Aegis\JSON\Expr for tmp ids in the valueToEncode Check if the value is a Aegis\JSON\Expr, and if replace its value with a magic key and save the javascript expression in an array. NOTE this method is recursive. NOTE: This method is used internally by the encode method. @see encode @param mixed $value a string - object property to be encoded @param array $javascriptExpressions @param null|string|int $currentKey @return mixed
[ "Check", "&", "Replace", "Aegis", "\\", "JSON", "\\", "Expr", "for", "tmp", "ids", "in", "the", "valueToEncode" ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/JSON.php#L157-L182
train
aegis-security/JSON
src/JSON.php
JSON.prettyPrint
public static function prettyPrint($json, $options = array()) { $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE); $result = ""; $indent = 0; $ind = " "; if (isset($options['indent'])) { $ind = $options['indent']; } $inLiteral = false; foreach ($tokens as $token) { $token = trim($token); if ($token == "") { continue; } if (preg_match('/^("(?:.*)"):[ ]?(.*)$/', $token, $matches)) { $token = $matches[1] . ': ' . $matches[2]; } $prefix = str_repeat($ind, $indent); if (!$inLiteral && ($token == "{" || $token == "[")) { $indent++; if ($result != "" && $result[strlen($result)-1] == "\n") { $result .= $prefix; } $result .= "$token\n"; } elseif (!$inLiteral && ($token == "}" || $token == "]")) { $indent--; $prefix = str_repeat($ind, $indent); $result .= "\n$prefix$token"; } elseif (!$inLiteral && $token == ",") { $result .= "$token\n"; } else { $result .= ($inLiteral ? '' : $prefix) . $token; //remove escaped backslash sequences causing false positives in next check $token = str_replace('\\', '', $token); // Count # of unescaped double-quotes in token, subtract # of // escaped double-quotes and if the result is odd then we are // inside a string literal if ((substr_count($token, '"')-substr_count($token, '\\"')) % 2 != 0) { $inLiteral = !$inLiteral; } } } return $result; }
php
public static function prettyPrint($json, $options = array()) { $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE); $result = ""; $indent = 0; $ind = " "; if (isset($options['indent'])) { $ind = $options['indent']; } $inLiteral = false; foreach ($tokens as $token) { $token = trim($token); if ($token == "") { continue; } if (preg_match('/^("(?:.*)"):[ ]?(.*)$/', $token, $matches)) { $token = $matches[1] . ': ' . $matches[2]; } $prefix = str_repeat($ind, $indent); if (!$inLiteral && ($token == "{" || $token == "[")) { $indent++; if ($result != "" && $result[strlen($result)-1] == "\n") { $result .= $prefix; } $result .= "$token\n"; } elseif (!$inLiteral && ($token == "}" || $token == "]")) { $indent--; $prefix = str_repeat($ind, $indent); $result .= "\n$prefix$token"; } elseif (!$inLiteral && $token == ",") { $result .= "$token\n"; } else { $result .= ($inLiteral ? '' : $prefix) . $token; //remove escaped backslash sequences causing false positives in next check $token = str_replace('\\', '', $token); // Count # of unescaped double-quotes in token, subtract # of // escaped double-quotes and if the result is odd then we are // inside a string literal if ((substr_count($token, '"')-substr_count($token, '\\"')) % 2 != 0) { $inLiteral = !$inLiteral; } } } return $result; }
[ "public", "static", "function", "prettyPrint", "(", "$", "json", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "tokens", "=", "preg_split", "(", "'|([\\{\\}\\]\\[,])|'", ",", "$", "json", ",", "-", "1", ",", "PREG_SPLIT_DELIM_CAPTURE", ")", ";", "$", "result", "=", "\"\"", ";", "$", "indent", "=", "0", ";", "$", "ind", "=", "\" \"", ";", "if", "(", "isset", "(", "$", "options", "[", "'indent'", "]", ")", ")", "{", "$", "ind", "=", "$", "options", "[", "'indent'", "]", ";", "}", "$", "inLiteral", "=", "false", ";", "foreach", "(", "$", "tokens", "as", "$", "token", ")", "{", "$", "token", "=", "trim", "(", "$", "token", ")", ";", "if", "(", "$", "token", "==", "\"\"", ")", "{", "continue", ";", "}", "if", "(", "preg_match", "(", "'/^(\"(?:.*)\"):[ ]?(.*)$/'", ",", "$", "token", ",", "$", "matches", ")", ")", "{", "$", "token", "=", "$", "matches", "[", "1", "]", ".", "': '", ".", "$", "matches", "[", "2", "]", ";", "}", "$", "prefix", "=", "str_repeat", "(", "$", "ind", ",", "$", "indent", ")", ";", "if", "(", "!", "$", "inLiteral", "&&", "(", "$", "token", "==", "\"{\"", "||", "$", "token", "==", "\"[\"", ")", ")", "{", "$", "indent", "++", ";", "if", "(", "$", "result", "!=", "\"\"", "&&", "$", "result", "[", "strlen", "(", "$", "result", ")", "-", "1", "]", "==", "\"\\n\"", ")", "{", "$", "result", ".=", "$", "prefix", ";", "}", "$", "result", ".=", "\"$token\\n\"", ";", "}", "elseif", "(", "!", "$", "inLiteral", "&&", "(", "$", "token", "==", "\"}\"", "||", "$", "token", "==", "\"]\"", ")", ")", "{", "$", "indent", "--", ";", "$", "prefix", "=", "str_repeat", "(", "$", "ind", ",", "$", "indent", ")", ";", "$", "result", ".=", "\"\\n$prefix$token\"", ";", "}", "elseif", "(", "!", "$", "inLiteral", "&&", "$", "token", "==", "\",\"", ")", "{", "$", "result", ".=", "\"$token\\n\"", ";", "}", "else", "{", "$", "result", ".=", "(", "$", "inLiteral", "?", "''", ":", "$", "prefix", ")", ".", "$", "token", ";", "//remove escaped backslash sequences causing false positives in next check", "$", "token", "=", "str_replace", "(", "'\\\\'", ",", "''", ",", "$", "token", ")", ";", "// Count # of unescaped double-quotes in token, subtract # of", "// escaped double-quotes and if the result is odd then we are", "// inside a string literal", "if", "(", "(", "substr_count", "(", "$", "token", ",", "'\"'", ")", "-", "substr_count", "(", "$", "token", ",", "'\\\\\"'", ")", ")", "%", "2", "!=", "0", ")", "{", "$", "inLiteral", "=", "!", "$", "inLiteral", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Pretty-print JSON string Use 'indent' option to select indentation string - by default it's a tab @param string $json Original JSON string @param array $options Encoding options @return string
[ "Pretty", "-", "print", "JSON", "string" ]
7bc8e442e9e570ecbc480053d9aaa42a52910fbc
https://github.com/aegis-security/JSON/blob/7bc8e442e9e570ecbc480053d9aaa42a52910fbc/src/JSON.php#L193-L242
train
wcatron/Common-DB-Framework-PHP
src/DB.php
DB.getInstance
public static function getInstance($connect = true) { if (!isset(self::$instances[static::class])) { self::$instances[static::class] = new static(); } /** @var DB $instance */ $instance = self::$instances[static::class]; if ($connect) { $instance->connect(); } return $instance; }
php
public static function getInstance($connect = true) { if (!isset(self::$instances[static::class])) { self::$instances[static::class] = new static(); } /** @var DB $instance */ $instance = self::$instances[static::class]; if ($connect) { $instance->connect(); } return $instance; }
[ "public", "static", "function", "getInstance", "(", "$", "connect", "=", "true", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "instances", "[", "static", "::", "class", "]", ")", ")", "{", "self", "::", "$", "instances", "[", "static", "::", "class", "]", "=", "new", "static", "(", ")", ";", "}", "/** @var DB $instance */", "$", "instance", "=", "self", "::", "$", "instances", "[", "static", "::", "class", "]", ";", "if", "(", "$", "connect", ")", "{", "$", "instance", "->", "connect", "(", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Gets the singleton instance of the DB. Used throughout the framework. @return static Returns the singlton DB object.
[ "Gets", "the", "singleton", "instance", "of", "the", "DB", ".", "Used", "throughout", "the", "framework", "." ]
c5ca1a62499053aee2004aa4cb48d71868f41b68
https://github.com/wcatron/Common-DB-Framework-PHP/blob/c5ca1a62499053aee2004aa4cb48d71868f41b68/src/DB.php#L18-L28
train
SergioMadness/pwf-helpers
src/ArrayHelper.php
ArrayHelper.groupArray
public static function groupArray($arr, $groupField) { $result = array(); foreach ($arr as $data) { $id = $data[$groupField]; if (isset($result[$id])) { $result[$id][] = $data; } else { $result[$id] = array($data); } } return $result; }
php
public static function groupArray($arr, $groupField) { $result = array(); foreach ($arr as $data) { $id = $data[$groupField]; if (isset($result[$id])) { $result[$id][] = $data; } else { $result[$id] = array($data); } } return $result; }
[ "public", "static", "function", "groupArray", "(", "$", "arr", ",", "$", "groupField", ")", "{", "$", "result", "=", "array", "(", ")", ";", "foreach", "(", "$", "arr", "as", "$", "data", ")", "{", "$", "id", "=", "$", "data", "[", "$", "groupField", "]", ";", "if", "(", "isset", "(", "$", "result", "[", "$", "id", "]", ")", ")", "{", "$", "result", "[", "$", "id", "]", "[", "]", "=", "$", "data", ";", "}", "else", "{", "$", "result", "[", "$", "id", "]", "=", "array", "(", "$", "data", ")", ";", "}", "}", "return", "$", "result", ";", "}" ]
Groupping elements by field Example: $arr = [ [ 'groupId' => 1, 'name' => 'name11' ], [ 'groupId' => 1, 'name' => 'name12' ], [ 'groupId' => 2, 'name' => 'name21' ] ]; $result = ArrayHelper::groupArray($arr, 'groupId'); $result: [ '1' => [ [ 'groupId' => 1, 'name' => 'name11' ], [ 'groupId' => 1, 'name' => 'name12' ] ], '2' => [ [ 'groupId' => 2, 'name' => 'name21' ] ] ] @param array $arr @param string $groupField
[ "Groupping", "elements", "by", "field" ]
d6cd44807c120356d60618cb08f237841c35e293
https://github.com/SergioMadness/pwf-helpers/blob/d6cd44807c120356d60618cb08f237841c35e293/src/ArrayHelper.php#L71-L84
train
SergioMadness/pwf-helpers
src/ArrayHelper.php
ArrayHelper.recursiveArraySearch
public static function recursiveArraySearch($needleKey, $needleValue, array $haystack) { foreach ($haystack as $key => $value) { $currentKey = $key; if (($currentKey == $needleKey && ($needleValue === null || $needleValue == $value)) || ( is_array($value) && self::recursiveArraySearch($needleKey, $needleValue, $value) !== false)) { return $currentKey; } } return null; }
php
public static function recursiveArraySearch($needleKey, $needleValue, array $haystack) { foreach ($haystack as $key => $value) { $currentKey = $key; if (($currentKey == $needleKey && ($needleValue === null || $needleValue == $value)) || ( is_array($value) && self::recursiveArraySearch($needleKey, $needleValue, $value) !== false)) { return $currentKey; } } return null; }
[ "public", "static", "function", "recursiveArraySearch", "(", "$", "needleKey", ",", "$", "needleValue", ",", "array", "$", "haystack", ")", "{", "foreach", "(", "$", "haystack", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "currentKey", "=", "$", "key", ";", "if", "(", "(", "$", "currentKey", "==", "$", "needleKey", "&&", "(", "$", "needleValue", "===", "null", "||", "$", "needleValue", "==", "$", "value", ")", ")", "||", "(", "is_array", "(", "$", "value", ")", "&&", "self", "::", "recursiveArraySearch", "(", "$", "needleKey", ",", "$", "needleValue", ",", "$", "value", ")", "!==", "false", ")", ")", "{", "return", "$", "currentKey", ";", "}", "}", "return", "null", ";", "}" ]
Search in array @param mixed $needleKey @param mixed $needleValue @param array $haystack @return integer
[ "Search", "in", "array" ]
d6cd44807c120356d60618cb08f237841c35e293
https://github.com/SergioMadness/pwf-helpers/blob/d6cd44807c120356d60618cb08f237841c35e293/src/ArrayHelper.php#L151-L164
train
ekyna/PaymentBundle
Payum/Action/AbstractPaymentStateAwareAction.php
AbstractPaymentStateAwareAction.updatePaymentState
protected function updatePaymentState(PaymentInterface $payment, $nextState) { if ($payment->getState() !== $nextState) { /** @var \Ekyna\Bundle\PaymentBundle\StateMachine\StateMachineInterface $stateMachine */ $stateMachine = $this->factory->get($payment); if (null !== $transition = $stateMachine->getTransitionToState($nextState)) { $stateMachine->apply($transition); $this->objectManager->flush(); } } }
php
protected function updatePaymentState(PaymentInterface $payment, $nextState) { if ($payment->getState() !== $nextState) { /** @var \Ekyna\Bundle\PaymentBundle\StateMachine\StateMachineInterface $stateMachine */ $stateMachine = $this->factory->get($payment); if (null !== $transition = $stateMachine->getTransitionToState($nextState)) { $stateMachine->apply($transition); $this->objectManager->flush(); } } }
[ "protected", "function", "updatePaymentState", "(", "PaymentInterface", "$", "payment", ",", "$", "nextState", ")", "{", "if", "(", "$", "payment", "->", "getState", "(", ")", "!==", "$", "nextState", ")", "{", "/** @var \\Ekyna\\Bundle\\PaymentBundle\\StateMachine\\StateMachineInterface $stateMachine */", "$", "stateMachine", "=", "$", "this", "->", "factory", "->", "get", "(", "$", "payment", ")", ";", "if", "(", "null", "!==", "$", "transition", "=", "$", "stateMachine", "->", "getTransitionToState", "(", "$", "nextState", ")", ")", "{", "$", "stateMachine", "->", "apply", "(", "$", "transition", ")", ";", "$", "this", "->", "objectManager", "->", "flush", "(", ")", ";", "}", "}", "}" ]
Updates the payment state. @param PaymentInterface $payment @param string $nextState
[ "Updates", "the", "payment", "state", "." ]
1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Payum/Action/AbstractPaymentStateAwareAction.php#L44-L55
train
azhai/code-refactor
src/CodeRefactor/Printer.php
Printer.pImplode
protected function pImplode(array $nodes, $glue = '') { $strings = $this->pIterator($nodes); return implode($glue, $strings); }
php
protected function pImplode(array $nodes, $glue = '') { $strings = $this->pIterator($nodes); return implode($glue, $strings); }
[ "protected", "function", "pImplode", "(", "array", "$", "nodes", ",", "$", "glue", "=", "''", ")", "{", "$", "strings", "=", "$", "this", "->", "pIterator", "(", "$", "nodes", ")", ";", "return", "implode", "(", "$", "glue", ",", "$", "strings", ")", ";", "}" ]
Pretty prints an array of nodes and implodes the printed values.
[ "Pretty", "prints", "an", "array", "of", "nodes", "and", "implodes", "the", "printed", "values", "." ]
cddb437d72f8239957daeba8211dda5e9366d6ca
https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Printer.php#L44-L48
train
azhai/code-refactor
src/CodeRefactor/Printer.php
Printer.pCommaSeparated
protected function pCommaSeparated(array $nodes, $max_len = 80) { $result = ''; $line = ''; $strings = $this->pIterator($nodes); foreach ($strings as $node_str) { if ($line !== '' && strlen($line) + strlen($node_str) > $max_len) { $result .= $line . ",\n"; $line = ' ' . $node_str; } else { $line .= ($line !== '' ? ', ' : '') . $node_str; } } $result .= $line; return $result; }
php
protected function pCommaSeparated(array $nodes, $max_len = 80) { $result = ''; $line = ''; $strings = $this->pIterator($nodes); foreach ($strings as $node_str) { if ($line !== '' && strlen($line) + strlen($node_str) > $max_len) { $result .= $line . ",\n"; $line = ' ' . $node_str; } else { $line .= ($line !== '' ? ', ' : '') . $node_str; } } $result .= $line; return $result; }
[ "protected", "function", "pCommaSeparated", "(", "array", "$", "nodes", ",", "$", "max_len", "=", "80", ")", "{", "$", "result", "=", "''", ";", "$", "line", "=", "''", ";", "$", "strings", "=", "$", "this", "->", "pIterator", "(", "$", "nodes", ")", ";", "foreach", "(", "$", "strings", "as", "$", "node_str", ")", "{", "if", "(", "$", "line", "!==", "''", "&&", "strlen", "(", "$", "line", ")", "+", "strlen", "(", "$", "node_str", ")", ">", "$", "max_len", ")", "{", "$", "result", ".=", "$", "line", ".", "\",\\n\"", ";", "$", "line", "=", "' '", ".", "$", "node_str", ";", "}", "else", "{", "$", "line", ".=", "(", "$", "line", "!==", "''", "?", "', '", ":", "''", ")", ".", "$", "node_str", ";", "}", "}", "$", "result", ".=", "$", "line", ";", "return", "$", "result", ";", "}" ]
Pretty prints an array of nodes and implodes the printed values with commas.
[ "Pretty", "prints", "an", "array", "of", "nodes", "and", "implodes", "the", "printed", "values", "with", "commas", "." ]
cddb437d72f8239957daeba8211dda5e9366d6ca
https://github.com/azhai/code-refactor/blob/cddb437d72f8239957daeba8211dda5e9366d6ca/src/CodeRefactor/Printer.php#L53-L68
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginInstallationService.php
PluginInstallationService.scanInstall
public function scanInstall() { if(!$this->lockSystemChanges) { foreach ($this->ApplicationContext->detectPluginDirectories()->getPluginDirectories() as $pluginDir) { if (is_dir($pluginDir)) { $slug = basename($pluginDir); if (!$this->PluginService->slugExists($slug)) { $xml = $this->loadXML($pluginDir); if ($xml) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); //INSERT PLUGIN INTO DB $plugin = new Plugin(); $this->ModelMapper->defaultsOnModel($plugin); $plugin = $this->SystemXMLConverter->xmlToPlugin($plugin, $xml); $plugin->Slug = $slug; $plugin->Path = $pluginDir; $plugin->Installed = false; try { $this->PluginService->add($plugin); } catch(ValidationException $ve) { throw new Exception('Plugins: '.$ve->getMessage()); } } } } } // $triggerReload = false; foreach ($this->PluginService->findAll()->getResults() as $plugin) { if(!is_dir($plugin->Path)) { $plugin->PathInvalid = true; if($plugin->isEnabled()) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); $plugin->Enabled = false; $this->PluginService->edit($plugin); } if(!$plugin->isInstalled()) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); $this->PluginService->delete($plugin->Slug); } continue; } $this->autoupgradePlugin($plugin); } if($this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->commit(); } foreach($this->ElementService->findAll()->getResults() as $element) $this->NodeService->createDBSchema($element); // if ($triggerReload) // $this->ApplicationContext->reload(); }
php
public function scanInstall() { if(!$this->lockSystemChanges) { foreach ($this->ApplicationContext->detectPluginDirectories()->getPluginDirectories() as $pluginDir) { if (is_dir($pluginDir)) { $slug = basename($pluginDir); if (!$this->PluginService->slugExists($slug)) { $xml = $this->loadXML($pluginDir); if ($xml) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); //INSERT PLUGIN INTO DB $plugin = new Plugin(); $this->ModelMapper->defaultsOnModel($plugin); $plugin = $this->SystemXMLConverter->xmlToPlugin($plugin, $xml); $plugin->Slug = $slug; $plugin->Path = $pluginDir; $plugin->Installed = false; try { $this->PluginService->add($plugin); } catch(ValidationException $ve) { throw new Exception('Plugins: '.$ve->getMessage()); } } } } } // $triggerReload = false; foreach ($this->PluginService->findAll()->getResults() as $plugin) { if(!is_dir($plugin->Path)) { $plugin->PathInvalid = true; if($plugin->isEnabled()) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); $plugin->Enabled = false; $this->PluginService->edit($plugin); } if(!$plugin->isInstalled()) { if(!$this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->begin(); $this->PluginService->delete($plugin->Slug); } continue; } $this->autoupgradePlugin($plugin); } if($this->TransactionManager->isTransactionInProgress()) $this->TransactionManager->commit(); } foreach($this->ElementService->findAll()->getResults() as $element) $this->NodeService->createDBSchema($element); // if ($triggerReload) // $this->ApplicationContext->reload(); }
[ "public", "function", "scanInstall", "(", ")", "{", "if", "(", "!", "$", "this", "->", "lockSystemChanges", ")", "{", "foreach", "(", "$", "this", "->", "ApplicationContext", "->", "detectPluginDirectories", "(", ")", "->", "getPluginDirectories", "(", ")", "as", "$", "pluginDir", ")", "{", "if", "(", "is_dir", "(", "$", "pluginDir", ")", ")", "{", "$", "slug", "=", "basename", "(", "$", "pluginDir", ")", ";", "if", "(", "!", "$", "this", "->", "PluginService", "->", "slugExists", "(", "$", "slug", ")", ")", "{", "$", "xml", "=", "$", "this", "->", "loadXML", "(", "$", "pluginDir", ")", ";", "if", "(", "$", "xml", ")", "{", "if", "(", "!", "$", "this", "->", "TransactionManager", "->", "isTransactionInProgress", "(", ")", ")", "$", "this", "->", "TransactionManager", "->", "begin", "(", ")", ";", "//INSERT PLUGIN INTO DB", "$", "plugin", "=", "new", "Plugin", "(", ")", ";", "$", "this", "->", "ModelMapper", "->", "defaultsOnModel", "(", "$", "plugin", ")", ";", "$", "plugin", "=", "$", "this", "->", "SystemXMLConverter", "->", "xmlToPlugin", "(", "$", "plugin", ",", "$", "xml", ")", ";", "$", "plugin", "->", "Slug", "=", "$", "slug", ";", "$", "plugin", "->", "Path", "=", "$", "pluginDir", ";", "$", "plugin", "->", "Installed", "=", "false", ";", "try", "{", "$", "this", "->", "PluginService", "->", "add", "(", "$", "plugin", ")", ";", "}", "catch", "(", "ValidationException", "$", "ve", ")", "{", "throw", "new", "Exception", "(", "'Plugins: '", ".", "$", "ve", "->", "getMessage", "(", ")", ")", ";", "}", "}", "}", "}", "}", "// $triggerReload = false;", "foreach", "(", "$", "this", "->", "PluginService", "->", "findAll", "(", ")", "->", "getResults", "(", ")", "as", "$", "plugin", ")", "{", "if", "(", "!", "is_dir", "(", "$", "plugin", "->", "Path", ")", ")", "{", "$", "plugin", "->", "PathInvalid", "=", "true", ";", "if", "(", "$", "plugin", "->", "isEnabled", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "TransactionManager", "->", "isTransactionInProgress", "(", ")", ")", "$", "this", "->", "TransactionManager", "->", "begin", "(", ")", ";", "$", "plugin", "->", "Enabled", "=", "false", ";", "$", "this", "->", "PluginService", "->", "edit", "(", "$", "plugin", ")", ";", "}", "if", "(", "!", "$", "plugin", "->", "isInstalled", "(", ")", ")", "{", "if", "(", "!", "$", "this", "->", "TransactionManager", "->", "isTransactionInProgress", "(", ")", ")", "$", "this", "->", "TransactionManager", "->", "begin", "(", ")", ";", "$", "this", "->", "PluginService", "->", "delete", "(", "$", "plugin", "->", "Slug", ")", ";", "}", "continue", ";", "}", "$", "this", "->", "autoupgradePlugin", "(", "$", "plugin", ")", ";", "}", "if", "(", "$", "this", "->", "TransactionManager", "->", "isTransactionInProgress", "(", ")", ")", "$", "this", "->", "TransactionManager", "->", "commit", "(", ")", ";", "}", "foreach", "(", "$", "this", "->", "ElementService", "->", "findAll", "(", ")", "->", "getResults", "(", ")", "as", "$", "element", ")", "$", "this", "->", "NodeService", "->", "createDBSchema", "(", "$", "element", ")", ";", "// if ($triggerReload)", "// $this->ApplicationContext->reload();", "}" ]
Scans the plugin directories and installs plugins as needed @return void
[ "Scans", "the", "plugin", "directories", "and", "installs", "plugins", "as", "needed" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginInstallationService.php#L222-L297
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginInstallationService.php
PluginInstallationService.processPluginXML
public function processPluginXML(Plugin $plugin, Errors &$errors, &$log = '', $xml = false) { if(!$xml) $xml = $this->loadXML($plugin->Path); $this->processConfig($plugin, $log, $xml); $this->processPermissions($plugin, $log, $xml); $this->processCMSNavItems($plugin, $log, $xml); $this->processElements($plugin, $log, $xml); }
php
public function processPluginXML(Plugin $plugin, Errors &$errors, &$log = '', $xml = false) { if(!$xml) $xml = $this->loadXML($plugin->Path); $this->processConfig($plugin, $log, $xml); $this->processPermissions($plugin, $log, $xml); $this->processCMSNavItems($plugin, $log, $xml); $this->processElements($plugin, $log, $xml); }
[ "public", "function", "processPluginXML", "(", "Plugin", "$", "plugin", ",", "Errors", "&", "$", "errors", ",", "&", "$", "log", "=", "''", ",", "$", "xml", "=", "false", ")", "{", "if", "(", "!", "$", "xml", ")", "$", "xml", "=", "$", "this", "->", "loadXML", "(", "$", "plugin", "->", "Path", ")", ";", "$", "this", "->", "processConfig", "(", "$", "plugin", ",", "$", "log", ",", "$", "xml", ")", ";", "$", "this", "->", "processPermissions", "(", "$", "plugin", ",", "$", "log", ",", "$", "xml", ")", ";", "$", "this", "->", "processCMSNavItems", "(", "$", "plugin", ",", "$", "log", ",", "$", "xml", ")", ";", "$", "this", "->", "processElements", "(", "$", "plugin", ",", "$", "log", ",", "$", "xml", ")", ";", "}" ]
Processes the plugin's plugin.xml file @param Plugin $plugin The Plugin we're processing @param Errors &$errors An errors object to update on errors @param string &$log A log to update with status details @param SimpleXMLExtended $xml If specified, use this XML @return void
[ "Processes", "the", "plugin", "s", "plugin", ".", "xml", "file" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginInstallationService.php#L309-L322
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginInstallationService.php
PluginInstallationService.processPermissions
public function processPermissions(Plugin $plugin, &$log = '', $xml = false) { if(!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); // add permissions $perms = $xml->permissions; if(!empty($perms)) foreach ( $perms->permission as $perm_xml ) { foreach ( array('slug', 'title') as $required_attribute ) { if (!$perm_xml->attributes()->$required_attribute) throw new Exception("Required permission attribute '$required_attribute' was not found."); } if(!$this->Permissions->permissionExists($perm_xml->attributes()->slug)) { try { $this->Permissions->addPermission($plugin, $perm_xml->attributes()->slug, $perm_xml->attributes()->title); } catch(ValidationException $ve) { throw new Exception('Permissions: '.$ve->getMessage()); } } $log .= "Permission created...\n"; $log .= "Slug: " . $perm_xml->attributes()->slug . "\n"; $log .= "Title: " . $perm_xml->attributes()->title . "\n"; $log .= "\n"; } }
php
public function processPermissions(Plugin $plugin, &$log = '', $xml = false) { if(!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); // add permissions $perms = $xml->permissions; if(!empty($perms)) foreach ( $perms->permission as $perm_xml ) { foreach ( array('slug', 'title') as $required_attribute ) { if (!$perm_xml->attributes()->$required_attribute) throw new Exception("Required permission attribute '$required_attribute' was not found."); } if(!$this->Permissions->permissionExists($perm_xml->attributes()->slug)) { try { $this->Permissions->addPermission($plugin, $perm_xml->attributes()->slug, $perm_xml->attributes()->title); } catch(ValidationException $ve) { throw new Exception('Permissions: '.$ve->getMessage()); } } $log .= "Permission created...\n"; $log .= "Slug: " . $perm_xml->attributes()->slug . "\n"; $log .= "Title: " . $perm_xml->attributes()->title . "\n"; $log .= "\n"; } }
[ "public", "function", "processPermissions", "(", "Plugin", "$", "plugin", ",", "&", "$", "log", "=", "''", ",", "$", "xml", "=", "false", ")", "{", "if", "(", "!", "$", "xml", ")", "$", "xml", "=", "$", "this", "->", "loadXML", "(", "$", "plugin", "->", "Path", ")", ";", "if", "(", "!", "$", "xml", ")", "throw", "new", "Exception", "(", "'Missing plugin.xml file for plugin ['", ".", "$", "plugin", "->", "Slug", ".", "']'", ")", ";", "// add permissions", "$", "perms", "=", "$", "xml", "->", "permissions", ";", "if", "(", "!", "empty", "(", "$", "perms", ")", ")", "foreach", "(", "$", "perms", "->", "permission", "as", "$", "perm_xml", ")", "{", "foreach", "(", "array", "(", "'slug'", ",", "'title'", ")", "as", "$", "required_attribute", ")", "{", "if", "(", "!", "$", "perm_xml", "->", "attributes", "(", ")", "->", "$", "required_attribute", ")", "throw", "new", "Exception", "(", "\"Required permission attribute '$required_attribute' was not found.\"", ")", ";", "}", "if", "(", "!", "$", "this", "->", "Permissions", "->", "permissionExists", "(", "$", "perm_xml", "->", "attributes", "(", ")", "->", "slug", ")", ")", "{", "try", "{", "$", "this", "->", "Permissions", "->", "addPermission", "(", "$", "plugin", ",", "$", "perm_xml", "->", "attributes", "(", ")", "->", "slug", ",", "$", "perm_xml", "->", "attributes", "(", ")", "->", "title", ")", ";", "}", "catch", "(", "ValidationException", "$", "ve", ")", "{", "throw", "new", "Exception", "(", "'Permissions: '", ".", "$", "ve", "->", "getMessage", "(", ")", ")", ";", "}", "}", "$", "log", ".=", "\"Permission created...\\n\"", ";", "$", "log", ".=", "\"Slug: \"", ".", "$", "perm_xml", "->", "attributes", "(", ")", "->", "slug", ".", "\"\\n\"", ";", "$", "log", ".=", "\"Title: \"", ".", "$", "perm_xml", "->", "attributes", "(", ")", "->", "title", ".", "\"\\n\"", ";", "$", "log", ".=", "\"\\n\"", ";", "}", "}" ]
Add all of the Plugin's permissions from the specified XML @param Plugin $plugin The Plugin to process @param string &$log A variable to update with log details @param SimpleXMLExtended $xml If specified, process this XML, otherwise load the XML from the plugin @return void
[ "Add", "all", "of", "the", "Plugin", "s", "permissions", "from", "the", "specified", "XML" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginInstallationService.php#L367-L399
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginInstallationService.php
PluginInstallationService.processConfig
public function processConfig(Plugin $plugin, &$log = '', $xml = false) { if (!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); //process config.php if (!empty($xml->config)) { $snippet = trim(strval($xml->config)); if ($this->ConfigService->insertSnippet($plugin, $snippet, $log)) $log .= "Appended plugin config snippet to config file.\n\n"; } }
php
public function processConfig(Plugin $plugin, &$log = '', $xml = false) { if (!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); //process config.php if (!empty($xml->config)) { $snippet = trim(strval($xml->config)); if ($this->ConfigService->insertSnippet($plugin, $snippet, $log)) $log .= "Appended plugin config snippet to config file.\n\n"; } }
[ "public", "function", "processConfig", "(", "Plugin", "$", "plugin", ",", "&", "$", "log", "=", "''", ",", "$", "xml", "=", "false", ")", "{", "if", "(", "!", "$", "xml", ")", "$", "xml", "=", "$", "this", "->", "loadXML", "(", "$", "plugin", "->", "Path", ")", ";", "if", "(", "!", "$", "xml", ")", "throw", "new", "Exception", "(", "'Missing plugin.xml file for plugin ['", ".", "$", "plugin", "->", "Slug", ".", "']'", ")", ";", "//process config.php", "if", "(", "!", "empty", "(", "$", "xml", "->", "config", ")", ")", "{", "$", "snippet", "=", "trim", "(", "strval", "(", "$", "xml", "->", "config", ")", ")", ";", "if", "(", "$", "this", "->", "ConfigService", "->", "insertSnippet", "(", "$", "plugin", ",", "$", "snippet", ",", "$", "log", ")", ")", "$", "log", ".=", "\"Appended plugin config snippet to config file.\\n\\n\"", ";", "}", "}" ]
Appends the plugin's config snippet to the config file @param Plugin $plugin The plugin to process @param string &$log A var that holds logging details @param SimpleXMLExtended $xml If specified, process this XML instead of loading the plugins @return void
[ "Appends", "the", "plugin", "s", "config", "snippet", "to", "the", "config", "file" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginInstallationService.php#L410-L425
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/plugins/PluginInstallationService.php
PluginInstallationService.processCMSNavItems
public function processCMSNavItems(Plugin $plugin, &$log = '', $xml = false) { if (!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); $processedSlugs = array(); // add cmsnavitems $navitems = $xml->cmsnavitems; if (!empty($navitems)) { foreach ( $navitems->item as $xml_item ) { $cms_nav_item = new CMSNavItem(); $this->ModelMapper->defaultsOnModel($cms_nav_item); $cms_nav_item = $this->SystemXMLConverter->xmlToCMSNavItem($cms_nav_item, $xml_item); if ($this->insertCMSNavItem($cms_nav_item, $plugin)) { $log .= "CMSNavItem created...\n"; $log .= "ID: {$cms_nav_item->CMSNavItemID}\n"; $log .= "Slug: {$cms_nav_item->Slug}\n"; $log .= "Label: {$cms_nav_item->Label}\n"; $log .= "URI: {$cms_nav_item->URI}\n"; $log .= "\n"; } $processedSlugs[] = $cms_nav_item->Slug; foreach($cms_nav_item->getChildren() as $child) { if ($this->insertCMSNavItem($child, $plugin)) { $log .= "CMSNavItem created...\n"; $log .= "ID: {$child->CMSNavItemID}\n"; $log .= "Slug: {$child->Slug}\n"; $log .= "Label: {$child->Label}\n"; $log .= "URI: {$child->URI}\n"; $log .= "\n"; } $processedSlugs[] = $child->Slug; } } } if($plugin->PluginID == '') return; $existing = $this->CMSNavItemService->findAll(new DTO(array('PluginID' => $plugin->PluginID)))->getResults(); foreach($existing as $e) { if(!in_array($e->Slug, $processedSlugs)) $this->CMSNavItemService->delete($e->Slug); } }
php
public function processCMSNavItems(Plugin $plugin, &$log = '', $xml = false) { if (!$xml) $xml = $this->loadXML($plugin->Path); if(!$xml) throw new Exception('Missing plugin.xml file for plugin ['.$plugin->Slug.']'); $processedSlugs = array(); // add cmsnavitems $navitems = $xml->cmsnavitems; if (!empty($navitems)) { foreach ( $navitems->item as $xml_item ) { $cms_nav_item = new CMSNavItem(); $this->ModelMapper->defaultsOnModel($cms_nav_item); $cms_nav_item = $this->SystemXMLConverter->xmlToCMSNavItem($cms_nav_item, $xml_item); if ($this->insertCMSNavItem($cms_nav_item, $plugin)) { $log .= "CMSNavItem created...\n"; $log .= "ID: {$cms_nav_item->CMSNavItemID}\n"; $log .= "Slug: {$cms_nav_item->Slug}\n"; $log .= "Label: {$cms_nav_item->Label}\n"; $log .= "URI: {$cms_nav_item->URI}\n"; $log .= "\n"; } $processedSlugs[] = $cms_nav_item->Slug; foreach($cms_nav_item->getChildren() as $child) { if ($this->insertCMSNavItem($child, $plugin)) { $log .= "CMSNavItem created...\n"; $log .= "ID: {$child->CMSNavItemID}\n"; $log .= "Slug: {$child->Slug}\n"; $log .= "Label: {$child->Label}\n"; $log .= "URI: {$child->URI}\n"; $log .= "\n"; } $processedSlugs[] = $child->Slug; } } } if($plugin->PluginID == '') return; $existing = $this->CMSNavItemService->findAll(new DTO(array('PluginID' => $plugin->PluginID)))->getResults(); foreach($existing as $e) { if(!in_array($e->Slug, $processedSlugs)) $this->CMSNavItemService->delete($e->Slug); } }
[ "public", "function", "processCMSNavItems", "(", "Plugin", "$", "plugin", ",", "&", "$", "log", "=", "''", ",", "$", "xml", "=", "false", ")", "{", "if", "(", "!", "$", "xml", ")", "$", "xml", "=", "$", "this", "->", "loadXML", "(", "$", "plugin", "->", "Path", ")", ";", "if", "(", "!", "$", "xml", ")", "throw", "new", "Exception", "(", "'Missing plugin.xml file for plugin ['", ".", "$", "plugin", "->", "Slug", ".", "']'", ")", ";", "$", "processedSlugs", "=", "array", "(", ")", ";", "// add cmsnavitems", "$", "navitems", "=", "$", "xml", "->", "cmsnavitems", ";", "if", "(", "!", "empty", "(", "$", "navitems", ")", ")", "{", "foreach", "(", "$", "navitems", "->", "item", "as", "$", "xml_item", ")", "{", "$", "cms_nav_item", "=", "new", "CMSNavItem", "(", ")", ";", "$", "this", "->", "ModelMapper", "->", "defaultsOnModel", "(", "$", "cms_nav_item", ")", ";", "$", "cms_nav_item", "=", "$", "this", "->", "SystemXMLConverter", "->", "xmlToCMSNavItem", "(", "$", "cms_nav_item", ",", "$", "xml_item", ")", ";", "if", "(", "$", "this", "->", "insertCMSNavItem", "(", "$", "cms_nav_item", ",", "$", "plugin", ")", ")", "{", "$", "log", ".=", "\"CMSNavItem created...\\n\"", ";", "$", "log", ".=", "\"ID: {$cms_nav_item->CMSNavItemID}\\n\"", ";", "$", "log", ".=", "\"Slug: {$cms_nav_item->Slug}\\n\"", ";", "$", "log", ".=", "\"Label: {$cms_nav_item->Label}\\n\"", ";", "$", "log", ".=", "\"URI: {$cms_nav_item->URI}\\n\"", ";", "$", "log", ".=", "\"\\n\"", ";", "}", "$", "processedSlugs", "[", "]", "=", "$", "cms_nav_item", "->", "Slug", ";", "foreach", "(", "$", "cms_nav_item", "->", "getChildren", "(", ")", "as", "$", "child", ")", "{", "if", "(", "$", "this", "->", "insertCMSNavItem", "(", "$", "child", ",", "$", "plugin", ")", ")", "{", "$", "log", ".=", "\"CMSNavItem created...\\n\"", ";", "$", "log", ".=", "\"ID: {$child->CMSNavItemID}\\n\"", ";", "$", "log", ".=", "\"Slug: {$child->Slug}\\n\"", ";", "$", "log", ".=", "\"Label: {$child->Label}\\n\"", ";", "$", "log", ".=", "\"URI: {$child->URI}\\n\"", ";", "$", "log", ".=", "\"\\n\"", ";", "}", "$", "processedSlugs", "[", "]", "=", "$", "child", "->", "Slug", ";", "}", "}", "}", "if", "(", "$", "plugin", "->", "PluginID", "==", "''", ")", "return", ";", "$", "existing", "=", "$", "this", "->", "CMSNavItemService", "->", "findAll", "(", "new", "DTO", "(", "array", "(", "'PluginID'", "=>", "$", "plugin", "->", "PluginID", ")", ")", ")", "->", "getResults", "(", ")", ";", "foreach", "(", "$", "existing", "as", "$", "e", ")", "{", "if", "(", "!", "in_array", "(", "$", "e", "->", "Slug", ",", "$", "processedSlugs", ")", ")", "$", "this", "->", "CMSNavItemService", "->", "delete", "(", "$", "e", "->", "Slug", ")", ";", "}", "}" ]
Add all the CMS nav items from the plugin @param Plugin $plugin The plugin to analyze @param string &$log A string that hold logging detail @param SimpleXMLExtended $xml If specified, used this instead of the plugin's xml file @return void
[ "Add", "all", "the", "CMS", "nav", "items", "from", "the", "plugin" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/plugins/PluginInstallationService.php#L569-L621
train