repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php
ezcMailComposer.addAttachment
public function addAttachment( $fileName, $content = null, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { if ( is_null( $content ) ) { $this->addFileAttachment( $fileName, $contentType, $mimeType, $contentDisposition ); } else { $this->addStringAttachment( $fileName, $content, $contentType, $mimeType, $contentDisposition ); } }
php
public function addAttachment( $fileName, $content = null, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { if ( is_null( $content ) ) { $this->addFileAttachment( $fileName, $contentType, $mimeType, $contentDisposition ); } else { $this->addStringAttachment( $fileName, $content, $contentType, $mimeType, $contentDisposition ); } }
[ "public", "function", "addAttachment", "(", "$", "fileName", ",", "$", "content", "=", "null", ",", "$", "contentType", "=", "null", ",", "$", "mimeType", "=", "null", ",", "ezcMailContentDispositionHeader", "$", "contentDisposition", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "content", ")", ")", "{", "$", "this", "->", "addFileAttachment", "(", "$", "fileName", ",", "$", "contentType", ",", "$", "mimeType", ",", "$", "contentDisposition", ")", ";", "}", "else", "{", "$", "this", "->", "addStringAttachment", "(", "$", "fileName", ",", "$", "content", ",", "$", "contentType", ",", "$", "mimeType", ",", "$", "contentDisposition", ")", ";", "}", "}" ]
Adds the file $fileName to the list of attachments. If $content is specified, $fileName is not checked if it exists. $this->attachments will also contain in this case the $content, $contentType and $mimeType. The $contentType (default = application) and $mimeType (default = octet-stream) control the complete mime-type of the attachment. If $contentDisposition is specified, the attached file will have its Content-Disposition header set according to the $contentDisposition object and the filename of the attachment in the generated mail will be the one from the $contentDisposition object. @throws ezcBaseFileNotFoundException if $fileName does not exists. @throws ezcBaseFilePermissionProblem if $fileName could not be read. @param string $fileName @param string $content @param string $contentType @param string $mimeType @param ezcMailContentDispositionHeader $contentDisposition @apichange This function might be removed in a future iteration of the Mail component. Use addFileAttachment() and addStringAttachment() instead.
[ "Adds", "the", "file", "$fileName", "to", "the", "list", "of", "attachments", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php#L285-L295
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php
ezcMailComposer.addFileAttachment
public function addFileAttachment( $fileName, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { if ( is_readable( $fileName ) ) { $this->attachments[] = array( $fileName, null, $contentType, $mimeType, $contentDisposition ); } else { if ( file_exists( $fileName ) ) { throw new ezcBaseFilePermissionException( $fileName, ezcBaseFileException::READ ); } else { throw new ezcBaseFileNotFoundException( $fileName ); } } }
php
public function addFileAttachment( $fileName, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { if ( is_readable( $fileName ) ) { $this->attachments[] = array( $fileName, null, $contentType, $mimeType, $contentDisposition ); } else { if ( file_exists( $fileName ) ) { throw new ezcBaseFilePermissionException( $fileName, ezcBaseFileException::READ ); } else { throw new ezcBaseFileNotFoundException( $fileName ); } } }
[ "public", "function", "addFileAttachment", "(", "$", "fileName", ",", "$", "contentType", "=", "null", ",", "$", "mimeType", "=", "null", ",", "ezcMailContentDispositionHeader", "$", "contentDisposition", "=", "null", ")", "{", "if", "(", "is_readable", "(", "$", "fileName", ")", ")", "{", "$", "this", "->", "attachments", "[", "]", "=", "array", "(", "$", "fileName", ",", "null", ",", "$", "contentType", ",", "$", "mimeType", ",", "$", "contentDisposition", ")", ";", "}", "else", "{", "if", "(", "file_exists", "(", "$", "fileName", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "fileName", ",", "ezcBaseFileException", "::", "READ", ")", ";", "}", "else", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "fileName", ")", ";", "}", "}", "}" ]
Adds the file $fileName to the list of attachments. The $contentType (default = application) and $mimeType (default = octet-stream) control the complete mime-type of the attachment. If $contentDisposition is specified, the attached file will have its Content-Disposition header set according to the $contentDisposition object and the filename of the attachment in the generated mail will be the one from the $contentDisposition object. @throws ezcBaseFileNotFoundException if $fileName does not exists. @throws ezcBaseFilePermissionProblem if $fileName could not be read. @param string $fileName @param string $contentType @param string $mimeType @param ezcMailContentDispositionHeader $contentDisposition
[ "Adds", "the", "file", "$fileName", "to", "the", "list", "of", "attachments", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php#L317-L334
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php
ezcMailComposer.addStringAttachment
public function addStringAttachment( $fileName, $content, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { $this->attachments[] = array( $fileName, $content, $contentType, $mimeType, $contentDisposition ); }
php
public function addStringAttachment( $fileName, $content, $contentType = null, $mimeType = null, ezcMailContentDispositionHeader $contentDisposition = null ) { $this->attachments[] = array( $fileName, $content, $contentType, $mimeType, $contentDisposition ); }
[ "public", "function", "addStringAttachment", "(", "$", "fileName", ",", "$", "content", ",", "$", "contentType", "=", "null", ",", "$", "mimeType", "=", "null", ",", "ezcMailContentDispositionHeader", "$", "contentDisposition", "=", "null", ")", "{", "$", "this", "->", "attachments", "[", "]", "=", "array", "(", "$", "fileName", ",", "$", "content", ",", "$", "contentType", ",", "$", "mimeType", ",", "$", "contentDisposition", ")", ";", "}" ]
Adds the file $fileName to the list of attachments, with contents $content. The file $fileName is not checked if it exists. An attachment is added to the mail, with the name $fileName, and the contents $content. The $contentType (default = application) and $mimeType (default = octet-stream) control the complete mime-type of the attachment. If $contentDisposition is specified, the attached file will have its Content-Disposition header set according to the $contentDisposition object and the filename of the attachment in the generated mail will be the one from the $contentDisposition object. @param string $fileName @param string $content @param string $contentType @param string $mimeType @param ezcMailContentDispositionHeader $contentDisposition
[ "Adds", "the", "file", "$fileName", "to", "the", "list", "of", "attachments", "with", "contents", "$content", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php#L356-L359
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php
ezcMailComposer.build
public function build() { $mainPart = false; // create the text part if there is one if ( $this->plainText != '' ) { $mainPart = new ezcMailText( $this->plainText, $this->charset ); } // create the HTML part if there is one $htmlPart = false; if ( $this->htmlText != '' ) { $htmlPart = $this->generateHtmlPart(); // create a MultiPartAlternative if a text part exists if ( $mainPart != false ) { $mainPart = new ezcMailMultipartAlternative( $mainPart, $htmlPart ); } else { $mainPart = $htmlPart; } } // build all attachments // special case, mail with no text and one attachment. // A fix for issue #14220 was added by wrapping the attachment in // an ezcMailMultipartMixed part if ( $mainPart == false && count( $this->attachments ) == 1 ) { if ( isset( $this->attachments[0][1] ) ) { if ( is_resource( $this->attachments[0][1] ) ) { $mainPart = new ezcMailMultipartMixed( new ezcMailStreamFile( $this->attachments[0][0], $this->attachments[0][1], $this->attachments[0][2], $this->attachments[0][3] ) ); } else { $mainPart = new ezcMailMultipartMixed( new ezcMailVirtualFile( $this->attachments[0][0], $this->attachments[0][1], $this->attachments[0][2], $this->attachments[0][3] ) ); } } else { $mainPart = new ezcMailMultipartMixed( new ezcMailFile( $this->attachments[0][0], $this->attachments[0][2], $this->attachments[0][3] ) ); } $mainPart->contentDisposition = $this->attachments[0][4]; } else if ( count( $this->attachments ) > 0 ) { $mainPart = ( $mainPart == false ) ? new ezcMailMultipartMixed() : new ezcMailMultipartMixed( $mainPart ); // add the attachments to the mixed part foreach ( $this->attachments as $attachment ) { if ( isset( $attachment[1] ) ) { if ( is_resource( $attachment[1] ) ) { $part = new ezcMailStreamFile( $attachment[0], $attachment[1], $attachment[2], $attachment[3] ); } else { $part = new ezcMailVirtualFile( $attachment[0], $attachment[1], $attachment[2], $attachment[3] ); } } else { $part = new ezcMailFile( $attachment[0], $attachment[2], $attachment[3] ); } $part->contentDisposition = $attachment[4]; $mainPart->appendPart( $part ); } } $this->body = $mainPart; }
php
public function build() { $mainPart = false; // create the text part if there is one if ( $this->plainText != '' ) { $mainPart = new ezcMailText( $this->plainText, $this->charset ); } // create the HTML part if there is one $htmlPart = false; if ( $this->htmlText != '' ) { $htmlPart = $this->generateHtmlPart(); // create a MultiPartAlternative if a text part exists if ( $mainPart != false ) { $mainPart = new ezcMailMultipartAlternative( $mainPart, $htmlPart ); } else { $mainPart = $htmlPart; } } // build all attachments // special case, mail with no text and one attachment. // A fix for issue #14220 was added by wrapping the attachment in // an ezcMailMultipartMixed part if ( $mainPart == false && count( $this->attachments ) == 1 ) { if ( isset( $this->attachments[0][1] ) ) { if ( is_resource( $this->attachments[0][1] ) ) { $mainPart = new ezcMailMultipartMixed( new ezcMailStreamFile( $this->attachments[0][0], $this->attachments[0][1], $this->attachments[0][2], $this->attachments[0][3] ) ); } else { $mainPart = new ezcMailMultipartMixed( new ezcMailVirtualFile( $this->attachments[0][0], $this->attachments[0][1], $this->attachments[0][2], $this->attachments[0][3] ) ); } } else { $mainPart = new ezcMailMultipartMixed( new ezcMailFile( $this->attachments[0][0], $this->attachments[0][2], $this->attachments[0][3] ) ); } $mainPart->contentDisposition = $this->attachments[0][4]; } else if ( count( $this->attachments ) > 0 ) { $mainPart = ( $mainPart == false ) ? new ezcMailMultipartMixed() : new ezcMailMultipartMixed( $mainPart ); // add the attachments to the mixed part foreach ( $this->attachments as $attachment ) { if ( isset( $attachment[1] ) ) { if ( is_resource( $attachment[1] ) ) { $part = new ezcMailStreamFile( $attachment[0], $attachment[1], $attachment[2], $attachment[3] ); } else { $part = new ezcMailVirtualFile( $attachment[0], $attachment[1], $attachment[2], $attachment[3] ); } } else { $part = new ezcMailFile( $attachment[0], $attachment[2], $attachment[3] ); } $part->contentDisposition = $attachment[4]; $mainPart->appendPart( $part ); } } $this->body = $mainPart; }
[ "public", "function", "build", "(", ")", "{", "$", "mainPart", "=", "false", ";", "// create the text part if there is one", "if", "(", "$", "this", "->", "plainText", "!=", "''", ")", "{", "$", "mainPart", "=", "new", "ezcMailText", "(", "$", "this", "->", "plainText", ",", "$", "this", "->", "charset", ")", ";", "}", "// create the HTML part if there is one", "$", "htmlPart", "=", "false", ";", "if", "(", "$", "this", "->", "htmlText", "!=", "''", ")", "{", "$", "htmlPart", "=", "$", "this", "->", "generateHtmlPart", "(", ")", ";", "// create a MultiPartAlternative if a text part exists", "if", "(", "$", "mainPart", "!=", "false", ")", "{", "$", "mainPart", "=", "new", "ezcMailMultipartAlternative", "(", "$", "mainPart", ",", "$", "htmlPart", ")", ";", "}", "else", "{", "$", "mainPart", "=", "$", "htmlPart", ";", "}", "}", "// build all attachments", "// special case, mail with no text and one attachment.", "// A fix for issue #14220 was added by wrapping the attachment in", "// an ezcMailMultipartMixed part", "if", "(", "$", "mainPart", "==", "false", "&&", "count", "(", "$", "this", "->", "attachments", ")", "==", "1", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "attachments", "[", "0", "]", "[", "1", "]", ")", ")", "{", "if", "(", "is_resource", "(", "$", "this", "->", "attachments", "[", "0", "]", "[", "1", "]", ")", ")", "{", "$", "mainPart", "=", "new", "ezcMailMultipartMixed", "(", "new", "ezcMailStreamFile", "(", "$", "this", "->", "attachments", "[", "0", "]", "[", "0", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "1", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "2", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "3", "]", ")", ")", ";", "}", "else", "{", "$", "mainPart", "=", "new", "ezcMailMultipartMixed", "(", "new", "ezcMailVirtualFile", "(", "$", "this", "->", "attachments", "[", "0", "]", "[", "0", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "1", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "2", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "3", "]", ")", ")", ";", "}", "}", "else", "{", "$", "mainPart", "=", "new", "ezcMailMultipartMixed", "(", "new", "ezcMailFile", "(", "$", "this", "->", "attachments", "[", "0", "]", "[", "0", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "2", "]", ",", "$", "this", "->", "attachments", "[", "0", "]", "[", "3", "]", ")", ")", ";", "}", "$", "mainPart", "->", "contentDisposition", "=", "$", "this", "->", "attachments", "[", "0", "]", "[", "4", "]", ";", "}", "else", "if", "(", "count", "(", "$", "this", "->", "attachments", ")", ">", "0", ")", "{", "$", "mainPart", "=", "(", "$", "mainPart", "==", "false", ")", "?", "new", "ezcMailMultipartMixed", "(", ")", ":", "new", "ezcMailMultipartMixed", "(", "$", "mainPart", ")", ";", "// add the attachments to the mixed part", "foreach", "(", "$", "this", "->", "attachments", "as", "$", "attachment", ")", "{", "if", "(", "isset", "(", "$", "attachment", "[", "1", "]", ")", ")", "{", "if", "(", "is_resource", "(", "$", "attachment", "[", "1", "]", ")", ")", "{", "$", "part", "=", "new", "ezcMailStreamFile", "(", "$", "attachment", "[", "0", "]", ",", "$", "attachment", "[", "1", "]", ",", "$", "attachment", "[", "2", "]", ",", "$", "attachment", "[", "3", "]", ")", ";", "}", "else", "{", "$", "part", "=", "new", "ezcMailVirtualFile", "(", "$", "attachment", "[", "0", "]", ",", "$", "attachment", "[", "1", "]", ",", "$", "attachment", "[", "2", "]", ",", "$", "attachment", "[", "3", "]", ")", ";", "}", "}", "else", "{", "$", "part", "=", "new", "ezcMailFile", "(", "$", "attachment", "[", "0", "]", ",", "$", "attachment", "[", "2", "]", ",", "$", "attachment", "[", "3", "]", ")", ";", "}", "$", "part", "->", "contentDisposition", "=", "$", "attachment", "[", "4", "]", ";", "$", "mainPart", "->", "appendPart", "(", "$", "part", ")", ";", "}", "}", "$", "this", "->", "body", "=", "$", "mainPart", ";", "}" ]
Builds the complete email message in RFC822 format. This method must be called before the message is sent. @throws ezcBaseFileNotFoundException if any of the attachment files can not be found.
[ "Builds", "the", "complete", "email", "message", "in", "RFC822", "format", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php#L369-L449
Eresus/EresusCMS
src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php
ezcMailComposer.generateHtmlPart
private function generateHtmlPart() { $result = false; if ( $this->htmlText != '' ) { $matches = array(); if ( $this->options->automaticImageInclude === true ) { // recognize file:// and file:///, pick out the image, add it as a part and then..:) preg_match_all( '( <img \\s+[^>]* src\\s*=\\s* (?: (?# Match quoted attribute) ([\'"])file://(?P<quoted>[^>]+)\\1 (?# Match unquoted attribute, which may not contain spaces) | file://(?P<unquoted>[^>\\s]+) ) [^>]* >)ix', $this->htmlText, $matches ); // pictures/files can be added multiple times. We only need them once. $matches = array_filter( array_unique( array_merge( $matches['quoted'], $matches['unquoted'] ) ) ); } $result = new ezcMailText( $this->htmlText, $this->charset, $this->encoding ); $result->subType = "html"; if ( count( $matches ) > 0 ) { $htmlPart = $result; // wrap already existing message in an alternative part $result = new ezcMailMultipartRelated( $result ); // create a filepart and add it to the related part // also store the ID for each part since we need those // when we replace the originals in the HTML message. foreach ( $matches as $fileName ) { if ( is_readable( $fileName ) ) { // @todo waiting for fix of the fileinfo extension // $contents = file_get_contents( $fileName ); $mimeType = null; $contentType = null; if ( ezcBaseFeatures::hasExtensionSupport( 'fileinfo' ) ) { // if fileinfo extension is available $filePart = new ezcMailFile( $fileName ); } elseif ( ezcMailTools::guessContentType( $fileName, $contentType, $mimeType ) ) { // if fileinfo extension is not available try to get content/mime type // from the file extension $filePart = new ezcMailFile( $fileName, $contentType, $mimeType ); } else { // fallback in case fileinfo is not available and could not get content/mime // type from file extension $filePart = new ezcMailFile( $fileName, "application", "octet-stream" ); } $cid = $result->addRelatedPart( $filePart ); // replace the original file reference with a reference to the cid $this->htmlText = str_replace( 'file://' . $fileName, 'cid:' . $cid, $this->htmlText ); } else { if ( file_exists( $fileName ) ) { throw new ezcBaseFilePermissionException( $fileName, ezcBaseFileException::READ ); } else { throw new ezcBaseFileNotFoundException( $fileName ); } // throw } } // update mail, with replaced URLs $htmlPart->text = $this->htmlText; } } return $result; }
php
private function generateHtmlPart() { $result = false; if ( $this->htmlText != '' ) { $matches = array(); if ( $this->options->automaticImageInclude === true ) { // recognize file:// and file:///, pick out the image, add it as a part and then..:) preg_match_all( '( <img \\s+[^>]* src\\s*=\\s* (?: (?# Match quoted attribute) ([\'"])file://(?P<quoted>[^>]+)\\1 (?# Match unquoted attribute, which may not contain spaces) | file://(?P<unquoted>[^>\\s]+) ) [^>]* >)ix', $this->htmlText, $matches ); // pictures/files can be added multiple times. We only need them once. $matches = array_filter( array_unique( array_merge( $matches['quoted'], $matches['unquoted'] ) ) ); } $result = new ezcMailText( $this->htmlText, $this->charset, $this->encoding ); $result->subType = "html"; if ( count( $matches ) > 0 ) { $htmlPart = $result; // wrap already existing message in an alternative part $result = new ezcMailMultipartRelated( $result ); // create a filepart and add it to the related part // also store the ID for each part since we need those // when we replace the originals in the HTML message. foreach ( $matches as $fileName ) { if ( is_readable( $fileName ) ) { // @todo waiting for fix of the fileinfo extension // $contents = file_get_contents( $fileName ); $mimeType = null; $contentType = null; if ( ezcBaseFeatures::hasExtensionSupport( 'fileinfo' ) ) { // if fileinfo extension is available $filePart = new ezcMailFile( $fileName ); } elseif ( ezcMailTools::guessContentType( $fileName, $contentType, $mimeType ) ) { // if fileinfo extension is not available try to get content/mime type // from the file extension $filePart = new ezcMailFile( $fileName, $contentType, $mimeType ); } else { // fallback in case fileinfo is not available and could not get content/mime // type from file extension $filePart = new ezcMailFile( $fileName, "application", "octet-stream" ); } $cid = $result->addRelatedPart( $filePart ); // replace the original file reference with a reference to the cid $this->htmlText = str_replace( 'file://' . $fileName, 'cid:' . $cid, $this->htmlText ); } else { if ( file_exists( $fileName ) ) { throw new ezcBaseFilePermissionException( $fileName, ezcBaseFileException::READ ); } else { throw new ezcBaseFileNotFoundException( $fileName ); } // throw } } // update mail, with replaced URLs $htmlPart->text = $this->htmlText; } } return $result; }
[ "private", "function", "generateHtmlPart", "(", ")", "{", "$", "result", "=", "false", ";", "if", "(", "$", "this", "->", "htmlText", "!=", "''", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "options", "->", "automaticImageInclude", "===", "true", ")", "{", "// recognize file:// and file:///, pick out the image, add it as a part and then..:)", "preg_match_all", "(", "'(\n <img \\\\s+[^>]*\n src\\\\s*=\\\\s*\n (?:\n (?# Match quoted attribute)\n ([\\'\"])file://(?P<quoted>[^>]+)\\\\1\n\n (?# Match unquoted attribute, which may not contain spaces)\n | file://(?P<unquoted>[^>\\\\s]+)\n )\n [^>]* >)ix'", ",", "$", "this", "->", "htmlText", ",", "$", "matches", ")", ";", "// pictures/files can be added multiple times. We only need them once.", "$", "matches", "=", "array_filter", "(", "array_unique", "(", "array_merge", "(", "$", "matches", "[", "'quoted'", "]", ",", "$", "matches", "[", "'unquoted'", "]", ")", ")", ")", ";", "}", "$", "result", "=", "new", "ezcMailText", "(", "$", "this", "->", "htmlText", ",", "$", "this", "->", "charset", ",", "$", "this", "->", "encoding", ")", ";", "$", "result", "->", "subType", "=", "\"html\"", ";", "if", "(", "count", "(", "$", "matches", ")", ">", "0", ")", "{", "$", "htmlPart", "=", "$", "result", ";", "// wrap already existing message in an alternative part", "$", "result", "=", "new", "ezcMailMultipartRelated", "(", "$", "result", ")", ";", "// create a filepart and add it to the related part", "// also store the ID for each part since we need those", "// when we replace the originals in the HTML message.", "foreach", "(", "$", "matches", "as", "$", "fileName", ")", "{", "if", "(", "is_readable", "(", "$", "fileName", ")", ")", "{", "// @todo waiting for fix of the fileinfo extension", "// $contents = file_get_contents( $fileName );", "$", "mimeType", "=", "null", ";", "$", "contentType", "=", "null", ";", "if", "(", "ezcBaseFeatures", "::", "hasExtensionSupport", "(", "'fileinfo'", ")", ")", "{", "// if fileinfo extension is available", "$", "filePart", "=", "new", "ezcMailFile", "(", "$", "fileName", ")", ";", "}", "elseif", "(", "ezcMailTools", "::", "guessContentType", "(", "$", "fileName", ",", "$", "contentType", ",", "$", "mimeType", ")", ")", "{", "// if fileinfo extension is not available try to get content/mime type", "// from the file extension", "$", "filePart", "=", "new", "ezcMailFile", "(", "$", "fileName", ",", "$", "contentType", ",", "$", "mimeType", ")", ";", "}", "else", "{", "// fallback in case fileinfo is not available and could not get content/mime", "// type from file extension", "$", "filePart", "=", "new", "ezcMailFile", "(", "$", "fileName", ",", "\"application\"", ",", "\"octet-stream\"", ")", ";", "}", "$", "cid", "=", "$", "result", "->", "addRelatedPart", "(", "$", "filePart", ")", ";", "// replace the original file reference with a reference to the cid", "$", "this", "->", "htmlText", "=", "str_replace", "(", "'file://'", ".", "$", "fileName", ",", "'cid:'", ".", "$", "cid", ",", "$", "this", "->", "htmlText", ")", ";", "}", "else", "{", "if", "(", "file_exists", "(", "$", "fileName", ")", ")", "{", "throw", "new", "ezcBaseFilePermissionException", "(", "$", "fileName", ",", "ezcBaseFileException", "::", "READ", ")", ";", "}", "else", "{", "throw", "new", "ezcBaseFileNotFoundException", "(", "$", "fileName", ")", ";", "}", "// throw", "}", "}", "// update mail, with replaced URLs", "$", "htmlPart", "->", "text", "=", "$", "this", "->", "htmlText", ";", "}", "}", "return", "$", "result", ";", "}" ]
Returns an ezcMailPart based on the HTML provided. This method adds local files/images to the mail itself using a {@link ezcMailMultipartRelated} object. @throws ezcBaseFileNotFoundException if $fileName does not exists. @throws ezcBaseFilePermissionProblem if $fileName could not be read. @return ezcMailPart
[ "Returns", "an", "ezcMailPart", "based", "on", "the", "HTML", "provided", "." ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/Mail/src/composer.php#L463-L545
WellCommerce/AppBundle
Manager/DictionaryManager.php
DictionaryManager.syncDictionary
public function syncDictionary() { $this->kernel = $this->get('kernel'); $this->locales = $this->getLocales(); $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); $this->filesystem = new Filesystem(); foreach ($this->locales as $locale) { $this->updateFilesystemTranslationsForLocale($locale); } $this->synchronizeDatabaseTranslations(); }
php
public function syncDictionary() { $this->kernel = $this->get('kernel'); $this->locales = $this->getLocales(); $this->propertyAccessor = PropertyAccess::createPropertyAccessor(); $this->filesystem = new Filesystem(); foreach ($this->locales as $locale) { $this->updateFilesystemTranslationsForLocale($locale); } $this->synchronizeDatabaseTranslations(); }
[ "public", "function", "syncDictionary", "(", ")", "{", "$", "this", "->", "kernel", "=", "$", "this", "->", "get", "(", "'kernel'", ")", ";", "$", "this", "->", "locales", "=", "$", "this", "->", "getLocales", "(", ")", ";", "$", "this", "->", "propertyAccessor", "=", "PropertyAccess", "::", "createPropertyAccessor", "(", ")", ";", "$", "this", "->", "filesystem", "=", "new", "Filesystem", "(", ")", ";", "foreach", "(", "$", "this", "->", "locales", "as", "$", "locale", ")", "{", "$", "this", "->", "updateFilesystemTranslationsForLocale", "(", "$", "locale", ")", ";", "}", "$", "this", "->", "synchronizeDatabaseTranslations", "(", ")", ";", "}" ]
Synchronizes database and filesystem translations
[ "Synchronizes", "database", "and", "filesystem", "translations" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Manager/DictionaryManager.php#L58-L70
WellCommerce/AppBundle
Manager/DictionaryManager.php
DictionaryManager.getDatabaseTranslations
protected function getDatabaseTranslations(Locale $locale) { $messages = []; $collection = $this->repository->getCollection(); $collection->map(function (Dictionary $dictionary) use ($locale, &$messages) { $messages[$dictionary->getIdentifier()] = $dictionary->translate($locale->getCode())->getValue(); }); return $messages; }
php
protected function getDatabaseTranslations(Locale $locale) { $messages = []; $collection = $this->repository->getCollection(); $collection->map(function (Dictionary $dictionary) use ($locale, &$messages) { $messages[$dictionary->getIdentifier()] = $dictionary->translate($locale->getCode())->getValue(); }); return $messages; }
[ "protected", "function", "getDatabaseTranslations", "(", "Locale", "$", "locale", ")", "{", "$", "messages", "=", "[", "]", ";", "$", "collection", "=", "$", "this", "->", "repository", "->", "getCollection", "(", ")", ";", "$", "collection", "->", "map", "(", "function", "(", "Dictionary", "$", "dictionary", ")", "use", "(", "$", "locale", ",", "&", "$", "messages", ")", "{", "$", "messages", "[", "$", "dictionary", "->", "getIdentifier", "(", ")", "]", "=", "$", "dictionary", "->", "translate", "(", "$", "locale", "->", "getCode", "(", ")", ")", "->", "getValue", "(", ")", ";", "}", ")", ";", "return", "$", "messages", ";", "}" ]
Returns an array containing all previously imported translations @param Locale $locale @return array
[ "Returns", "an", "array", "containing", "all", "previously", "imported", "translations" ]
train
https://github.com/WellCommerce/AppBundle/blob/2add687d1c898dd0b24afd611d896e3811a0eac3/Manager/DictionaryManager.php#L133-L143
WellCommerce/StandardEditionBundle
DataFixtures/ORM/LoadAvailabilityData.php
LoadAvailabilityData.load
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } foreach (self::$samples as $name) { $availability = new Availability(); foreach ($this->getLocales() as $locale) { $availability->translate($locale->getCode())->setName($name); } $availability->mergeNewTranslations(); $manager->persist($availability); $this->setReference('availability_' . $name, $availability); } $manager->flush(); }
php
public function load(ObjectManager $manager) { if (!$this->isEnabled()) { return; } foreach (self::$samples as $name) { $availability = new Availability(); foreach ($this->getLocales() as $locale) { $availability->translate($locale->getCode())->setName($name); } $availability->mergeNewTranslations(); $manager->persist($availability); $this->setReference('availability_' . $name, $availability); } $manager->flush(); }
[ "public", "function", "load", "(", "ObjectManager", "$", "manager", ")", "{", "if", "(", "!", "$", "this", "->", "isEnabled", "(", ")", ")", "{", "return", ";", "}", "foreach", "(", "self", "::", "$", "samples", "as", "$", "name", ")", "{", "$", "availability", "=", "new", "Availability", "(", ")", ";", "foreach", "(", "$", "this", "->", "getLocales", "(", ")", "as", "$", "locale", ")", "{", "$", "availability", "->", "translate", "(", "$", "locale", "->", "getCode", "(", ")", ")", "->", "setName", "(", "$", "name", ")", ";", "}", "$", "availability", "->", "mergeNewTranslations", "(", ")", ";", "$", "manager", "->", "persist", "(", "$", "availability", ")", ";", "$", "this", "->", "setReference", "(", "'availability_'", ".", "$", "name", ",", "$", "availability", ")", ";", "}", "$", "manager", "->", "flush", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/WellCommerce/StandardEditionBundle/blob/6367bd20bbb6bde37c710a6ba87ae72b5f05f61e/DataFixtures/ORM/LoadAvailabilityData.php#L31-L48
hametuha/wpametu
src/WPametu/UI/Field/GeoChecker.php
GeoChecker.get_field
protected function get_field( \WP_Post $post ){ $html = parent::get_field($post); return $html.sprintf('<p class="inline-error"><i class="dashicons dashicons-location-alt"></i> %s</p>', $this->__('Can\'t find map point. Try another string')); }
php
protected function get_field( \WP_Post $post ){ $html = parent::get_field($post); return $html.sprintf('<p class="inline-error"><i class="dashicons dashicons-location-alt"></i> %s</p>', $this->__('Can\'t find map point. Try another string')); }
[ "protected", "function", "get_field", "(", "\\", "WP_Post", "$", "post", ")", "{", "$", "html", "=", "parent", "::", "get_field", "(", "$", "post", ")", ";", "return", "$", "html", ".", "sprintf", "(", "'<p class=\"inline-error\"><i class=\"dashicons dashicons-location-alt\"></i> %s</p>'", ",", "$", "this", "->", "__", "(", "'Can\\'t find map point. Try another string'", ")", ")", ";", "}" ]
Add error message. @param \WP_Post $post @return string
[ "Add", "error", "message", "." ]
train
https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/UI/Field/GeoChecker.php#L37-L40
digipolisgent/robo-digipolis-package
src/Utility/NpmFindExecutable.php
NpmFindExecutable.findExecutable
protected function findExecutable($cmd) { $pathToCmd = $this->searchForExecutable($cmd); if ($pathToCmd) { return $this->useCallOnWindows($pathToCmd); } return false; }
php
protected function findExecutable($cmd) { $pathToCmd = $this->searchForExecutable($cmd); if ($pathToCmd) { return $this->useCallOnWindows($pathToCmd); } return false; }
[ "protected", "function", "findExecutable", "(", "$", "cmd", ")", "{", "$", "pathToCmd", "=", "$", "this", "->", "searchForExecutable", "(", "$", "cmd", ")", ";", "if", "(", "$", "pathToCmd", ")", "{", "return", "$", "this", "->", "useCallOnWindows", "(", "$", "pathToCmd", ")", ";", "}", "return", "false", ";", "}" ]
Return the best path to the executable program with the provided name. Favor vendor/bin in the current project. If not found there, use whatever is on the $PATH. @param string $cmd The executable to find. @return bool|string
[ "Return", "the", "best", "path", "to", "the", "executable", "program", "with", "the", "provided", "name", ".", "Favor", "vendor", "/", "bin", "in", "the", "current", "project", ".", "If", "not", "found", "there", "use", "whatever", "is", "on", "the", "$PATH", "." ]
train
https://github.com/digipolisgent/robo-digipolis-package/blob/6f206f32d910992d27b2a1b4dda1c5e7d8259b75/src/Utility/NpmFindExecutable.php#L21-L28
digipolisgent/robo-digipolis-package
src/Utility/NpmFindExecutable.php
NpmFindExecutable.searchForExecutable
private function searchForExecutable($cmd) { $nodeModules = $this->findNodeModules(); if ($nodeModules) { $finder = new Finder(); $finder->files()->in($nodeModules)->name($cmd); foreach ($finder as $executable) { return $executable->getRealPath(); } } $execFinder = new ExecutableFinder(); return $execFinder->find($cmd, null, []); }
php
private function searchForExecutable($cmd) { $nodeModules = $this->findNodeModules(); if ($nodeModules) { $finder = new Finder(); $finder->files()->in($nodeModules)->name($cmd); foreach ($finder as $executable) { return $executable->getRealPath(); } } $execFinder = new ExecutableFinder(); return $execFinder->find($cmd, null, []); }
[ "private", "function", "searchForExecutable", "(", "$", "cmd", ")", "{", "$", "nodeModules", "=", "$", "this", "->", "findNodeModules", "(", ")", ";", "if", "(", "$", "nodeModules", ")", "{", "$", "finder", "=", "new", "Finder", "(", ")", ";", "$", "finder", "->", "files", "(", ")", "->", "in", "(", "$", "nodeModules", ")", "->", "name", "(", "$", "cmd", ")", ";", "foreach", "(", "$", "finder", "as", "$", "executable", ")", "{", "return", "$", "executable", "->", "getRealPath", "(", ")", ";", "}", "}", "$", "execFinder", "=", "new", "ExecutableFinder", "(", ")", ";", "return", "$", "execFinder", "->", "find", "(", "$", "cmd", ",", "null", ",", "[", "]", ")", ";", "}" ]
@param string $cmd @return string
[ "@param", "string", "$cmd" ]
train
https://github.com/digipolisgent/robo-digipolis-package/blob/6f206f32d910992d27b2a1b4dda1c5e7d8259b75/src/Utility/NpmFindExecutable.php#L35-L47
surebert/surebert-framework
src/sb/JS.php
JS.setHTML
public static function setHTML($id, $html) { $js = '$("'.$id.'").html('.json_encode($html).');'; return self::execHeader($js); }
php
public static function setHTML($id, $html) { $js = '$("'.$id.'").html('.json_encode($html).');'; return self::execHeader($js); }
[ "public", "static", "function", "setHTML", "(", "$", "id", ",", "$", "html", ")", "{", "$", "js", "=", "'$(\"'", ".", "$", "id", ".", "'\").html('", ".", "json_encode", "(", "$", "html", ")", ".", "');'", ";", "return", "self", "::", "execHeader", "(", "$", "js", ")", ";", "}" ]
Uses jsexec_header to set the innerHTML of an element by id @param integer $id the HTML element id @param string $html The innerHTML to set @return string
[ "Uses", "jsexec_header", "to", "set", "the", "innerHTML", "of", "an", "element", "by", "id" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/JS.php#L23-L27
surebert/surebert-framework
src/sb/JS.php
JS.execScript
public static function execScript($script_path, $context=null) { header('Content-type: text/javascript'); if(!is_null($context)){ if(is_object($context)){ $context = get_object_vars($context); } if(is_array($context)){ extract($context); } } require($script_path); }
php
public static function execScript($script_path, $context=null) { header('Content-type: text/javascript'); if(!is_null($context)){ if(is_object($context)){ $context = get_object_vars($context); } if(is_array($context)){ extract($context); } } require($script_path); }
[ "public", "static", "function", "execScript", "(", "$", "script_path", ",", "$", "context", "=", "null", ")", "{", "header", "(", "'Content-type: text/javascript'", ")", ";", "if", "(", "!", "is_null", "(", "$", "context", ")", ")", "{", "if", "(", "is_object", "(", "$", "context", ")", ")", "{", "$", "context", "=", "get_object_vars", "(", "$", "context", ")", ";", "}", "if", "(", "is_array", "(", "$", "context", ")", ")", "{", "extract", "(", "$", "context", ")", ";", "}", "}", "require", "(", "$", "script_path", ")", ";", "}" ]
Executes a script at a certain path @param string $script_path full path
[ "Executes", "a", "script", "at", "a", "certain", "path" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/JS.php#L33-L46
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processMetadataDrivers
private function processMetadataDrivers() { $builder = $this->getContainerBuilder(); // At the moment, only Docblock annotations are supported, XML and YAML are not. $annotationReader = $builder->addDefinition($this->prefix('metadata.annotationReader')) ->setClass(AnnotationReader::class); $cachedReader = $builder->addDefinition($this->prefix('metadata.cachedReader')) ->setClass(CachedReader::class) ->setFactory(CachedReader::class, [ '@' . $this->prefix('metadata.annotationReader'), '@' . $this->prefix('cache.annotations'), $this->debugMode ]); $driverChain = $builder->addDefinition($this->prefix('metadata.driver')) ->setClass(MappingDriverChain::class); foreach ($this->config['metadata'] as $namespace => $directory) { $driver = $builder->addDefinition($this->prefix('driver.' . $this->createServiceName($namespace))) ->setClass(MappingDriver::class) ->setFactory(AnnotationDriver::class, [ '@' . $this->prefix('metadata.cachedReader'), $directory ]); $driverChain->addSetup('$service->addDriver(?, ?)', [ '@' . $this->prefix('driver.' . $this->createServiceName($namespace)), $namespace ]); } }
php
private function processMetadataDrivers() { $builder = $this->getContainerBuilder(); // At the moment, only Docblock annotations are supported, XML and YAML are not. $annotationReader = $builder->addDefinition($this->prefix('metadata.annotationReader')) ->setClass(AnnotationReader::class); $cachedReader = $builder->addDefinition($this->prefix('metadata.cachedReader')) ->setClass(CachedReader::class) ->setFactory(CachedReader::class, [ '@' . $this->prefix('metadata.annotationReader'), '@' . $this->prefix('cache.annotations'), $this->debugMode ]); $driverChain = $builder->addDefinition($this->prefix('metadata.driver')) ->setClass(MappingDriverChain::class); foreach ($this->config['metadata'] as $namespace => $directory) { $driver = $builder->addDefinition($this->prefix('driver.' . $this->createServiceName($namespace))) ->setClass(MappingDriver::class) ->setFactory(AnnotationDriver::class, [ '@' . $this->prefix('metadata.cachedReader'), $directory ]); $driverChain->addSetup('$service->addDriver(?, ?)', [ '@' . $this->prefix('driver.' . $this->createServiceName($namespace)), $namespace ]); } }
[ "private", "function", "processMetadataDrivers", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "// At the moment, only Docblock annotations are supported, XML and YAML are not.\t\t", "$", "annotationReader", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'metadata.annotationReader'", ")", ")", "->", "setClass", "(", "AnnotationReader", "::", "class", ")", ";", "$", "cachedReader", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'metadata.cachedReader'", ")", ")", "->", "setClass", "(", "CachedReader", "::", "class", ")", "->", "setFactory", "(", "CachedReader", "::", "class", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'metadata.annotationReader'", ")", ",", "'@'", ".", "$", "this", "->", "prefix", "(", "'cache.annotations'", ")", ",", "$", "this", "->", "debugMode", "]", ")", ";", "$", "driverChain", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'metadata.driver'", ")", ")", "->", "setClass", "(", "MappingDriverChain", "::", "class", ")", ";", "foreach", "(", "$", "this", "->", "config", "[", "'metadata'", "]", "as", "$", "namespace", "=>", "$", "directory", ")", "{", "$", "driver", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'driver.'", ".", "$", "this", "->", "createServiceName", "(", "$", "namespace", ")", ")", ")", "->", "setClass", "(", "MappingDriver", "::", "class", ")", "->", "setFactory", "(", "AnnotationDriver", "::", "class", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'metadata.cachedReader'", ")", ",", "$", "directory", "]", ")", ";", "$", "driverChain", "->", "addSetup", "(", "'$service->addDriver(?, ?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'driver.'", ".", "$", "this", "->", "createServiceName", "(", "$", "namespace", ")", ")", ",", "$", "namespace", "]", ")", ";", "}", "}" ]
Registers metadata drivers.
[ "Registers", "metadata", "drivers", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L106-L136
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.createServiceName
private function createServiceName(string $namespace) { $parts = explode('\\', $namespace); foreach ($parts as $k => $part) { $parts[$k] = lcfirst($part); } return trim(implode('.', $parts), '.'); }
php
private function createServiceName(string $namespace) { $parts = explode('\\', $namespace); foreach ($parts as $k => $part) { $parts[$k] = lcfirst($part); } return trim(implode('.', $parts), '.'); }
[ "private", "function", "createServiceName", "(", "string", "$", "namespace", ")", "{", "$", "parts", "=", "explode", "(", "'\\\\'", ",", "$", "namespace", ")", ";", "foreach", "(", "$", "parts", "as", "$", "k", "=>", "$", "part", ")", "{", "$", "parts", "[", "$", "k", "]", "=", "lcfirst", "(", "$", "part", ")", ";", "}", "return", "trim", "(", "implode", "(", "'.'", ",", "$", "parts", ")", ",", "'.'", ")", ";", "}" ]
Converts PHP namespace to service name.
[ "Converts", "PHP", "namespace", "to", "service", "name", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L142-L149
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processConnection
private function processConnection() { $builder = $this->getContainerBuilder(); $connection = $builder->addDefinition($this->prefix('connection')) ->setClass(Connection::class) ->setFactory(DriverManager::class . '::getConnection', [$this->config['connection']]); }
php
private function processConnection() { $builder = $this->getContainerBuilder(); $connection = $builder->addDefinition($this->prefix('connection')) ->setClass(Connection::class) ->setFactory(DriverManager::class . '::getConnection', [$this->config['connection']]); }
[ "private", "function", "processConnection", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "connection", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'connection'", ")", ")", "->", "setClass", "(", "Connection", "::", "class", ")", "->", "setFactory", "(", "DriverManager", "::", "class", ".", "'::getConnection'", ",", "[", "$", "this", "->", "config", "[", "'connection'", "]", "]", ")", ";", "}" ]
Registers DBAL connection.
[ "Registers", "DBAL", "connection", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L155-L162
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processEvents
private function processEvents() { $builder = $this->getContainerBuilder(); $eventManager = $builder->addDefinition($this->prefix('eventManager')) ->setClass(EventManager::class); $entityListenerResolver = $builder->addDefinition($this->prefix('entityListenerResolver')) ->setClass(ContainerEntityListenerResolver::class); $rc = new \ReflectionClass(Events::class); $events = $rc->getConstants(); foreach ($this->config['listeners'] as $event => $listeners) { if (!isset($events[$event])) { throw new InvalidStateException("Event '$event' is not valid doctrine event. See class " . Events::class . ' for list of available events.'); } foreach ((array) $listeners as $listener) { $builder->getDefinition($this->prefix('eventManager'))->addSetup('$service->addEventListener([' . Events::class . '::?], ?)', [$event, $listener]); } } }
php
private function processEvents() { $builder = $this->getContainerBuilder(); $eventManager = $builder->addDefinition($this->prefix('eventManager')) ->setClass(EventManager::class); $entityListenerResolver = $builder->addDefinition($this->prefix('entityListenerResolver')) ->setClass(ContainerEntityListenerResolver::class); $rc = new \ReflectionClass(Events::class); $events = $rc->getConstants(); foreach ($this->config['listeners'] as $event => $listeners) { if (!isset($events[$event])) { throw new InvalidStateException("Event '$event' is not valid doctrine event. See class " . Events::class . ' for list of available events.'); } foreach ((array) $listeners as $listener) { $builder->getDefinition($this->prefix('eventManager'))->addSetup('$service->addEventListener([' . Events::class . '::?], ?)', [$event, $listener]); } } }
[ "private", "function", "processEvents", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "eventManager", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'eventManager'", ")", ")", "->", "setClass", "(", "EventManager", "::", "class", ")", ";", "$", "entityListenerResolver", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'entityListenerResolver'", ")", ")", "->", "setClass", "(", "ContainerEntityListenerResolver", "::", "class", ")", ";", "$", "rc", "=", "new", "\\", "ReflectionClass", "(", "Events", "::", "class", ")", ";", "$", "events", "=", "$", "rc", "->", "getConstants", "(", ")", ";", "foreach", "(", "$", "this", "->", "config", "[", "'listeners'", "]", "as", "$", "event", "=>", "$", "listeners", ")", "{", "if", "(", "!", "isset", "(", "$", "events", "[", "$", "event", "]", ")", ")", "{", "throw", "new", "InvalidStateException", "(", "\"Event '$event' is not valid doctrine event. See class \"", ".", "Events", "::", "class", ".", "' for list of available events.'", ")", ";", "}", "foreach", "(", "(", "array", ")", "$", "listeners", "as", "$", "listener", ")", "{", "$", "builder", "->", "getDefinition", "(", "$", "this", "->", "prefix", "(", "'eventManager'", ")", ")", "->", "addSetup", "(", "'$service->addEventListener(['", ".", "Events", "::", "class", ".", "'::?], ?)'", ",", "[", "$", "event", ",", "$", "listener", "]", ")", ";", "}", "}", "}" ]
Registers Event Manager.
[ "Registers", "Event", "Manager", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L168-L191
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processEntityManager
private function processEntityManager() { $builder = $this->getContainerBuilder(); $configuration = $builder->addDefinition($this->prefix('configuration')) ->setClass(Configuration::class) ->addSetup('$service->setMetadataDriverImpl($this->getService(?))', [$this->prefix('metadata.driver')]) ->addSetup('$service->setMetadataCacheImpl(?)', ['@' . $this->prefix('cache.metadata')]) ->addSetup('$service->setQueryCacheImpl(?)', ['@' . $this->prefix('cache.query')]) ->addSetup('$service->setResultCacheImpl(?)', ['@' . $this->prefix('cache.result')]) ->addSetup('$service->setHydrationCacheImpl(?)', ['@' . $this->prefix('cache.hydration')]) ->addSetup('$service->setProxyDir(?)', [$this->config['proxyDir']]) ->addSetup('$service->setProxyNamespace(?)', [$this->config['proxyNamespace']]) ->addSetup('$service->setNamingStrategy(?)', [new \Nette\DI\Statement('Doctrine\ORM\Mapping\UnderscoreNamingStrategy')]) ->addSetup('$service->setQuoteStrategy(?)', [new \Nette\DI\Statement('Doctrine\ORM\Mapping\DefaultQuoteStrategy')]) ->addSetup('$service->setAutoGenerateProxyClasses(?)', [1]) ->addSetup('$service->setEntityListenerResolver(?)', ['@' . $this->prefix('entityListenerResolver')]); $entityManager = $builder->addDefinition($this->prefix('entityManager')) ->setClass(EntityManager::class) ->setFactory(EntityManager::class . '::create', [ '@' . $this->prefix('connection'), '@' . $this->prefix('configuration'), '@' . $this->prefix('eventManager') ]); }
php
private function processEntityManager() { $builder = $this->getContainerBuilder(); $configuration = $builder->addDefinition($this->prefix('configuration')) ->setClass(Configuration::class) ->addSetup('$service->setMetadataDriverImpl($this->getService(?))', [$this->prefix('metadata.driver')]) ->addSetup('$service->setMetadataCacheImpl(?)', ['@' . $this->prefix('cache.metadata')]) ->addSetup('$service->setQueryCacheImpl(?)', ['@' . $this->prefix('cache.query')]) ->addSetup('$service->setResultCacheImpl(?)', ['@' . $this->prefix('cache.result')]) ->addSetup('$service->setHydrationCacheImpl(?)', ['@' . $this->prefix('cache.hydration')]) ->addSetup('$service->setProxyDir(?)', [$this->config['proxyDir']]) ->addSetup('$service->setProxyNamespace(?)', [$this->config['proxyNamespace']]) ->addSetup('$service->setNamingStrategy(?)', [new \Nette\DI\Statement('Doctrine\ORM\Mapping\UnderscoreNamingStrategy')]) ->addSetup('$service->setQuoteStrategy(?)', [new \Nette\DI\Statement('Doctrine\ORM\Mapping\DefaultQuoteStrategy')]) ->addSetup('$service->setAutoGenerateProxyClasses(?)', [1]) ->addSetup('$service->setEntityListenerResolver(?)', ['@' . $this->prefix('entityListenerResolver')]); $entityManager = $builder->addDefinition($this->prefix('entityManager')) ->setClass(EntityManager::class) ->setFactory(EntityManager::class . '::create', [ '@' . $this->prefix('connection'), '@' . $this->prefix('configuration'), '@' . $this->prefix('eventManager') ]); }
[ "private", "function", "processEntityManager", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "configuration", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'configuration'", ")", ")", "->", "setClass", "(", "Configuration", "::", "class", ")", "->", "addSetup", "(", "'$service->setMetadataDriverImpl($this->getService(?))'", ",", "[", "$", "this", "->", "prefix", "(", "'metadata.driver'", ")", "]", ")", "->", "addSetup", "(", "'$service->setMetadataCacheImpl(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'cache.metadata'", ")", "]", ")", "->", "addSetup", "(", "'$service->setQueryCacheImpl(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'cache.query'", ")", "]", ")", "->", "addSetup", "(", "'$service->setResultCacheImpl(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'cache.result'", ")", "]", ")", "->", "addSetup", "(", "'$service->setHydrationCacheImpl(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'cache.hydration'", ")", "]", ")", "->", "addSetup", "(", "'$service->setProxyDir(?)'", ",", "[", "$", "this", "->", "config", "[", "'proxyDir'", "]", "]", ")", "->", "addSetup", "(", "'$service->setProxyNamespace(?)'", ",", "[", "$", "this", "->", "config", "[", "'proxyNamespace'", "]", "]", ")", "->", "addSetup", "(", "'$service->setNamingStrategy(?)'", ",", "[", "new", "\\", "Nette", "\\", "DI", "\\", "Statement", "(", "'Doctrine\\ORM\\Mapping\\UnderscoreNamingStrategy'", ")", "]", ")", "->", "addSetup", "(", "'$service->setQuoteStrategy(?)'", ",", "[", "new", "\\", "Nette", "\\", "DI", "\\", "Statement", "(", "'Doctrine\\ORM\\Mapping\\DefaultQuoteStrategy'", ")", "]", ")", "->", "addSetup", "(", "'$service->setAutoGenerateProxyClasses(?)'", ",", "[", "1", "]", ")", "->", "addSetup", "(", "'$service->setEntityListenerResolver(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'entityListenerResolver'", ")", "]", ")", ";", "$", "entityManager", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'entityManager'", ")", ")", "->", "setClass", "(", "EntityManager", "::", "class", ")", "->", "setFactory", "(", "EntityManager", "::", "class", ".", "'::create'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'connection'", ")", ",", "'@'", ".", "$", "this", "->", "prefix", "(", "'configuration'", ")", ",", "'@'", ".", "$", "this", "->", "prefix", "(", "'eventManager'", ")", "]", ")", ";", "}" ]
Registers Entity Manager.
[ "Registers", "Entity", "Manager", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L197-L222
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processCachingServices
private function processCachingServices() { $this->createCache('annotations'); $this->createCache('metadata'); $this->createCache('query'); $this->createCache('result'); $this->createCache('hydration'); }
php
private function processCachingServices() { $this->createCache('annotations'); $this->createCache('metadata'); $this->createCache('query'); $this->createCache('result'); $this->createCache('hydration'); }
[ "private", "function", "processCachingServices", "(", ")", "{", "$", "this", "->", "createCache", "(", "'annotations'", ")", ";", "$", "this", "->", "createCache", "(", "'metadata'", ")", ";", "$", "this", "->", "createCache", "(", "'query'", ")", ";", "$", "this", "->", "createCache", "(", "'result'", ")", ";", "$", "this", "->", "createCache", "(", "'hydration'", ")", ";", "}" ]
Registers caching services.
[ "Registers", "caching", "services", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L228-L235
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.createCache
private function createCache(string $name) { $builder = $this->getContainerBuilder(); $cache = $builder->addDefinition($this->prefix('cache.' . $name)) ->setClass(Cache::class) ->setArguments(['@Nette\Caching\IStorage', $this->debugMode]) ->addSetup('$service->setNamespace(?)', [$this->prefix('cache.' . $name)]); return $cache; }
php
private function createCache(string $name) { $builder = $this->getContainerBuilder(); $cache = $builder->addDefinition($this->prefix('cache.' . $name)) ->setClass(Cache::class) ->setArguments(['@Nette\Caching\IStorage', $this->debugMode]) ->addSetup('$service->setNamespace(?)', [$this->prefix('cache.' . $name)]); return $cache; }
[ "private", "function", "createCache", "(", "string", "$", "name", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "cache", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'cache.'", ".", "$", "name", ")", ")", "->", "setClass", "(", "Cache", "::", "class", ")", "->", "setArguments", "(", "[", "'@Nette\\Caching\\IStorage'", ",", "$", "this", "->", "debugMode", "]", ")", "->", "addSetup", "(", "'$service->setNamespace(?)'", ",", "[", "$", "this", "->", "prefix", "(", "'cache.'", ".", "$", "name", ")", "]", ")", ";", "return", "$", "cache", ";", "}" ]
Creates a caching service.
[ "Creates", "a", "caching", "service", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L241-L251
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processConsole
private function processConsole() { $builder = $this->getContainerBuilder(); $console = $builder->addDefinition($this->prefix('console')) ->setClass(Application::class) ->setArguments(['Doctrine Command Line Interface', \Doctrine\ORM\Version::VERSION]) ->addSetup('?->setCatchExceptions(TRUE)', ['@self']) ->addSetup('$helperSet = ' . ConsoleRunner::class . '::createHelperSet(?)', ['@' . $this->prefix('entityManager')]) ->addSetup('$helperSet->set(new \Andromeda\Doctrine\Console\Helpers\ContainerHelper(?), ?)', ['@Nette\DI\Container', 'container']) ->addSetup('?->setHelperSet($helperSet)', ['@self']) ->addSetup(ConsoleRunner::class . '::addCommands(?)', ['@self']); $commands = array_merge([ Commands\SchemaCreateCommand::class, Commands\SchemaUpdateCommand::class, Commands\SchemaDropCommand::class ], $this->config['commands']); foreach ($commands as $command) { $console->addSetup('?->add(?)', ['@self', new Nette\DI\Statement($command)]); } }
php
private function processConsole() { $builder = $this->getContainerBuilder(); $console = $builder->addDefinition($this->prefix('console')) ->setClass(Application::class) ->setArguments(['Doctrine Command Line Interface', \Doctrine\ORM\Version::VERSION]) ->addSetup('?->setCatchExceptions(TRUE)', ['@self']) ->addSetup('$helperSet = ' . ConsoleRunner::class . '::createHelperSet(?)', ['@' . $this->prefix('entityManager')]) ->addSetup('$helperSet->set(new \Andromeda\Doctrine\Console\Helpers\ContainerHelper(?), ?)', ['@Nette\DI\Container', 'container']) ->addSetup('?->setHelperSet($helperSet)', ['@self']) ->addSetup(ConsoleRunner::class . '::addCommands(?)', ['@self']); $commands = array_merge([ Commands\SchemaCreateCommand::class, Commands\SchemaUpdateCommand::class, Commands\SchemaDropCommand::class ], $this->config['commands']); foreach ($commands as $command) { $console->addSetup('?->add(?)', ['@self', new Nette\DI\Statement($command)]); } }
[ "private", "function", "processConsole", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "console", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'console'", ")", ")", "->", "setClass", "(", "Application", "::", "class", ")", "->", "setArguments", "(", "[", "'Doctrine Command Line Interface'", ",", "\\", "Doctrine", "\\", "ORM", "\\", "Version", "::", "VERSION", "]", ")", "->", "addSetup", "(", "'?->setCatchExceptions(TRUE)'", ",", "[", "'@self'", "]", ")", "->", "addSetup", "(", "'$helperSet = '", ".", "ConsoleRunner", "::", "class", ".", "'::createHelperSet(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'entityManager'", ")", "]", ")", "->", "addSetup", "(", "'$helperSet->set(new \\Andromeda\\Doctrine\\Console\\Helpers\\ContainerHelper(?), ?)'", ",", "[", "'@Nette\\DI\\Container'", ",", "'container'", "]", ")", "->", "addSetup", "(", "'?->setHelperSet($helperSet)'", ",", "[", "'@self'", "]", ")", "->", "addSetup", "(", "ConsoleRunner", "::", "class", ".", "'::addCommands(?)'", ",", "[", "'@self'", "]", ")", ";", "$", "commands", "=", "array_merge", "(", "[", "Commands", "\\", "SchemaCreateCommand", "::", "class", ",", "Commands", "\\", "SchemaUpdateCommand", "::", "class", ",", "Commands", "\\", "SchemaDropCommand", "::", "class", "]", ",", "$", "this", "->", "config", "[", "'commands'", "]", ")", ";", "foreach", "(", "$", "commands", "as", "$", "command", ")", "{", "$", "console", "->", "addSetup", "(", "'?->add(?)'", ",", "[", "'@self'", ",", "new", "Nette", "\\", "DI", "\\", "Statement", "(", "$", "command", ")", "]", ")", ";", "}", "}" ]
Registers Doctrine Console.
[ "Registers", "Doctrine", "Console", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L257-L279
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.processTracy
private function processTracy() { $builder = $this->getContainerBuilder(); $tracyPanel = $builder->addDefinition($this->prefix('tracyPanel')) ->setClass(Panel::class); $builder->getDefinition($this->prefix('entityManager')) ->addSetup('?->setEntityManager(?)', ['@' . $this->prefix('tracyPanel'), '@self']); }
php
private function processTracy() { $builder = $this->getContainerBuilder(); $tracyPanel = $builder->addDefinition($this->prefix('tracyPanel')) ->setClass(Panel::class); $builder->getDefinition($this->prefix('entityManager')) ->addSetup('?->setEntityManager(?)', ['@' . $this->prefix('tracyPanel'), '@self']); }
[ "private", "function", "processTracy", "(", ")", "{", "$", "builder", "=", "$", "this", "->", "getContainerBuilder", "(", ")", ";", "$", "tracyPanel", "=", "$", "builder", "->", "addDefinition", "(", "$", "this", "->", "prefix", "(", "'tracyPanel'", ")", ")", "->", "setClass", "(", "Panel", "::", "class", ")", ";", "$", "builder", "->", "getDefinition", "(", "$", "this", "->", "prefix", "(", "'entityManager'", ")", ")", "->", "addSetup", "(", "'?->setEntityManager(?)'", ",", "[", "'@'", ".", "$", "this", "->", "prefix", "(", "'tracyPanel'", ")", ",", "'@self'", "]", ")", ";", "}" ]
Registers debug panel.
[ "Registers", "debug", "panel", "." ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L285-L294
andromeda-framework/doctrine
src/Doctrine/DI/DoctrineExtension.php
DoctrineExtension.afterCompile
public function afterCompile(ClassType $class) { $initialize = $class->getMethod('initialize'); $initialize->addBody('$proxyAutolader = (new Doctrine\Common\Proxy\Autoloader)->register(?, ?);', [ $this->config['proxyDir'], $this->config['proxyNamespace'] ]); $initialize->addBody('Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(\'class_exists\');'); $initialize->addBody('$subscribers = $this->findByType(?);', ['\Doctrine\Common\EventSubscriber']); $initialize->addBody('foreach ($subscribers as $subscriber) { $this->getService(?)->addEventSubscriber($this->getService($subscriber)); }', [$this->prefix('eventManager')]); }
php
public function afterCompile(ClassType $class) { $initialize = $class->getMethod('initialize'); $initialize->addBody('$proxyAutolader = (new Doctrine\Common\Proxy\Autoloader)->register(?, ?);', [ $this->config['proxyDir'], $this->config['proxyNamespace'] ]); $initialize->addBody('Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(\'class_exists\');'); $initialize->addBody('$subscribers = $this->findByType(?);', ['\Doctrine\Common\EventSubscriber']); $initialize->addBody('foreach ($subscribers as $subscriber) { $this->getService(?)->addEventSubscriber($this->getService($subscriber)); }', [$this->prefix('eventManager')]); }
[ "public", "function", "afterCompile", "(", "ClassType", "$", "class", ")", "{", "$", "initialize", "=", "$", "class", "->", "getMethod", "(", "'initialize'", ")", ";", "$", "initialize", "->", "addBody", "(", "'$proxyAutolader = (new Doctrine\\Common\\Proxy\\Autoloader)->register(?, ?);'", ",", "[", "$", "this", "->", "config", "[", "'proxyDir'", "]", ",", "$", "this", "->", "config", "[", "'proxyNamespace'", "]", "]", ")", ";", "$", "initialize", "->", "addBody", "(", "'Doctrine\\Common\\Annotations\\AnnotationRegistry::registerLoader(\\'class_exists\\');'", ")", ";", "$", "initialize", "->", "addBody", "(", "'$subscribers = $this->findByType(?);'", ",", "[", "'\\Doctrine\\Common\\EventSubscriber'", "]", ")", ";", "$", "initialize", "->", "addBody", "(", "'foreach ($subscribers as $subscriber) { $this->getService(?)->addEventSubscriber($this->getService($subscriber)); }'", ",", "[", "$", "this", "->", "prefix", "(", "'eventManager'", ")", "]", ")", ";", "}" ]
@param ClassType $class @return void
[ "@param", "ClassType", "$class" ]
train
https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/DI/DoctrineExtension.php#L302-L313
antaresproject/notifications
src/Processor/LogsProcessor.php
LogsProcessor.preview
public function preview($id) { $item = app(StackRepository::class)->fetchOne((int) $id)->firstOrFail(); if (in_array($item->notification->type->name, ['email', 'sms'])) { $classname = $item->notification->type->name === 'email' ? EmailNotification::class : SmsNotification::class; $notification = app($classname); $notification->setModel($item); return view('antares/notifications::admin.logs.preview', ['content' => $notification->render()]); } $decorator = app(SidebarItemDecorator::class); $decorated = $decorator->item($item, config('antares/notifications::templates.notification')); return new JsonResponse(['content' => $decorated], 200); }
php
public function preview($id) { $item = app(StackRepository::class)->fetchOne((int) $id)->firstOrFail(); if (in_array($item->notification->type->name, ['email', 'sms'])) { $classname = $item->notification->type->name === 'email' ? EmailNotification::class : SmsNotification::class; $notification = app($classname); $notification->setModel($item); return view('antares/notifications::admin.logs.preview', ['content' => $notification->render()]); } $decorator = app(SidebarItemDecorator::class); $decorated = $decorator->item($item, config('antares/notifications::templates.notification')); return new JsonResponse(['content' => $decorated], 200); }
[ "public", "function", "preview", "(", "$", "id", ")", "{", "$", "item", "=", "app", "(", "StackRepository", "::", "class", ")", "->", "fetchOne", "(", "(", "int", ")", "$", "id", ")", "->", "firstOrFail", "(", ")", ";", "if", "(", "in_array", "(", "$", "item", "->", "notification", "->", "type", "->", "name", ",", "[", "'email'", ",", "'sms'", "]", ")", ")", "{", "$", "classname", "=", "$", "item", "->", "notification", "->", "type", "->", "name", "===", "'email'", "?", "EmailNotification", "::", "class", ":", "SmsNotification", "::", "class", ";", "$", "notification", "=", "app", "(", "$", "classname", ")", ";", "$", "notification", "->", "setModel", "(", "$", "item", ")", ";", "return", "view", "(", "'antares/notifications::admin.logs.preview'", ",", "[", "'content'", "=>", "$", "notification", "->", "render", "(", ")", "]", ")", ";", "}", "$", "decorator", "=", "app", "(", "SidebarItemDecorator", "::", "class", ")", ";", "$", "decorated", "=", "$", "decorator", "->", "item", "(", "$", "item", ",", "config", "(", "'antares/notifications::templates.notification'", ")", ")", ";", "return", "new", "JsonResponse", "(", "[", "'content'", "=>", "$", "decorated", "]", ",", "200", ")", ";", "}" ]
Preview notification log @param mixed $id @return View
[ "Preview", "notification", "log" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Processor/LogsProcessor.php#L92-L106
antaresproject/notifications
src/Processor/LogsProcessor.php
LogsProcessor.delete
public function delete(LogsListener $listener, $id = null): RedirectResponse { $stack = !empty($ids = input('attr')) ? $this->stack->newQuery()->whereIn('id', $ids) : $this->stack->newQuery()->findOrFail($id); if ($stack->delete()) { return $listener->deleteSuccess(); } return $listener->deleteFailed(); }
php
public function delete(LogsListener $listener, $id = null): RedirectResponse { $stack = !empty($ids = input('attr')) ? $this->stack->newQuery()->whereIn('id', $ids) : $this->stack->newQuery()->findOrFail($id); if ($stack->delete()) { return $listener->deleteSuccess(); } return $listener->deleteFailed(); }
[ "public", "function", "delete", "(", "LogsListener", "$", "listener", ",", "$", "id", "=", "null", ")", ":", "RedirectResponse", "{", "$", "stack", "=", "!", "empty", "(", "$", "ids", "=", "input", "(", "'attr'", ")", ")", "?", "$", "this", "->", "stack", "->", "newQuery", "(", ")", "->", "whereIn", "(", "'id'", ",", "$", "ids", ")", ":", "$", "this", "->", "stack", "->", "newQuery", "(", ")", "->", "findOrFail", "(", "$", "id", ")", ";", "if", "(", "$", "stack", "->", "delete", "(", ")", ")", "{", "return", "$", "listener", "->", "deleteSuccess", "(", ")", ";", "}", "return", "$", "listener", "->", "deleteFailed", "(", ")", ";", "}" ]
Deletes notification log @param LogsListener $listener @param mixed $id @return RedirectResponse
[ "Deletes", "notification", "log" ]
train
https://github.com/antaresproject/notifications/blob/60de743477b7e9cbb51de66da5fd9461adc9dd8a/src/Processor/LogsProcessor.php#L115-L122
InfiniteSoftware/ISEcommpayPayum
Action/NotifyAction.php
NotifyAction.execute
public function execute($request) { RequestNotSupportedException::assertSupports($this, $request); $this->logger->info("Ecommpay order #{$request->getFirstModel()->getOrder()->getNumber()} have paid"); throw new HttpResponse('OK'); }
php
public function execute($request) { RequestNotSupportedException::assertSupports($this, $request); $this->logger->info("Ecommpay order #{$request->getFirstModel()->getOrder()->getNumber()} have paid"); throw new HttpResponse('OK'); }
[ "public", "function", "execute", "(", "$", "request", ")", "{", "RequestNotSupportedException", "::", "assertSupports", "(", "$", "this", ",", "$", "request", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "\"Ecommpay order #{$request->getFirstModel()->getOrder()->getNumber()} have paid\"", ")", ";", "throw", "new", "HttpResponse", "(", "'OK'", ")", ";", "}" ]
{@inheritDoc} @param Notify $request
[ "{", "@inheritDoc", "}" ]
train
https://github.com/InfiniteSoftware/ISEcommpayPayum/blob/44a073e3d885d9007aa54d6ff13aea93a9e52e7c/Action/NotifyAction.php#L30-L35
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/Builder/Reflector/Tags/ExampleAssembler.php
ExampleAssembler.create
public function create($data) { if (! $data instanceof ExampleTag) { throw new \InvalidArgumentException( 'The ExampleAssembler expected an ExampleTag object to base the descriptor on' ); } $descriptor = new ExampleDescriptor($data->getName()); $descriptor->setFilePath((string) $data->getFilePath()); $descriptor->setStartingLine($data->getStartingLine()); $descriptor->setLineCount($data->getLineCount()); $descriptor->setDescription($data->getDescription()); $descriptor->setExample($this->finder->find($descriptor)); return $descriptor; }
php
public function create($data) { if (! $data instanceof ExampleTag) { throw new \InvalidArgumentException( 'The ExampleAssembler expected an ExampleTag object to base the descriptor on' ); } $descriptor = new ExampleDescriptor($data->getName()); $descriptor->setFilePath((string) $data->getFilePath()); $descriptor->setStartingLine($data->getStartingLine()); $descriptor->setLineCount($data->getLineCount()); $descriptor->setDescription($data->getDescription()); $descriptor->setExample($this->finder->find($descriptor)); return $descriptor; }
[ "public", "function", "create", "(", "$", "data", ")", "{", "if", "(", "!", "$", "data", "instanceof", "ExampleTag", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The ExampleAssembler expected an ExampleTag object to base the descriptor on'", ")", ";", "}", "$", "descriptor", "=", "new", "ExampleDescriptor", "(", "$", "data", "->", "getName", "(", ")", ")", ";", "$", "descriptor", "->", "setFilePath", "(", "(", "string", ")", "$", "data", "->", "getFilePath", "(", ")", ")", ";", "$", "descriptor", "->", "setStartingLine", "(", "$", "data", "->", "getStartingLine", "(", ")", ")", ";", "$", "descriptor", "->", "setLineCount", "(", "$", "data", "->", "getLineCount", "(", ")", ")", ";", "$", "descriptor", "->", "setDescription", "(", "$", "data", "->", "getDescription", "(", ")", ")", ";", "$", "descriptor", "->", "setExample", "(", "$", "this", "->", "finder", "->", "find", "(", "$", "descriptor", ")", ")", ";", "return", "$", "descriptor", ";", "}" ]
Creates a new Descriptor from the given Reflector. @param ExampleTag $data @throws \InvalidArgumentException if the provided parameter is not of type ExampleTag; the interface won't let up typehint the signature. @return ExampleDescriptor
[ "Creates", "a", "new", "Descriptor", "from", "the", "given", "Reflector", "." ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/Builder/Reflector/Tags/ExampleAssembler.php#L48-L64
znck/countries
src/CountriesServiceProvider.php
CountriesServiceProvider.register
public function register() { $this->mergeConfigFrom(dirname(__DIR__).'/config/countries.php', 'countries'); $this->app->singleton('command.countries.update', UpdateCountriesCommand::class); $this->app->singleton( 'translator.countries', function () { $locale = $this->app['config']['app.locale']; $loader = new FileLoader($this->app['files'], dirname(__DIR__).'/data'); $trans = new Translator($loader, $locale); return $trans; } ); $this->commands('command.countries.update'); }
php
public function register() { $this->mergeConfigFrom(dirname(__DIR__).'/config/countries.php', 'countries'); $this->app->singleton('command.countries.update', UpdateCountriesCommand::class); $this->app->singleton( 'translator.countries', function () { $locale = $this->app['config']['app.locale']; $loader = new FileLoader($this->app['files'], dirname(__DIR__).'/data'); $trans = new Translator($loader, $locale); return $trans; } ); $this->commands('command.countries.update'); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "mergeConfigFrom", "(", "dirname", "(", "__DIR__", ")", ".", "'/config/countries.php'", ",", "'countries'", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "'command.countries.update'", ",", "UpdateCountriesCommand", "::", "class", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "'translator.countries'", ",", "function", "(", ")", "{", "$", "locale", "=", "$", "this", "->", "app", "[", "'config'", "]", "[", "'app.locale'", "]", ";", "$", "loader", "=", "new", "FileLoader", "(", "$", "this", "->", "app", "[", "'files'", "]", ",", "dirname", "(", "__DIR__", ")", ".", "'/data'", ")", ";", "$", "trans", "=", "new", "Translator", "(", "$", "loader", ",", "$", "locale", ")", ";", "return", "$", "trans", ";", "}", ")", ";", "$", "this", "->", "commands", "(", "'command.countries.update'", ")", ";", "}" ]
Register the application services.
[ "Register", "the", "application", "services", "." ]
train
https://github.com/znck/countries/blob/a78a2b302dfa8eacab8fe0c06127dbb37fa98fd3/src/CountriesServiceProvider.php#L22-L39
dave-redfern/somnambulist-value-objects
src/Types/Money/CurrencyCodeMappings.php
CurrencyCodeMappings.precision
public static function precision(CurrencyCode $code) { if (array_key_exists($code->value(), static::$precision)) { return static::$precision[$code->value()]; } return 2; }
php
public static function precision(CurrencyCode $code) { if (array_key_exists($code->value(), static::$precision)) { return static::$precision[$code->value()]; } return 2; }
[ "public", "static", "function", "precision", "(", "CurrencyCode", "$", "code", ")", "{", "if", "(", "array_key_exists", "(", "$", "code", "->", "value", "(", ")", ",", "static", "::", "$", "precision", ")", ")", "{", "return", "static", "::", "$", "precision", "[", "$", "code", "->", "value", "(", ")", "]", ";", "}", "return", "2", ";", "}" ]
@param CurrencyCode $code @return int
[ "@param", "CurrencyCode", "$code" ]
train
https://github.com/dave-redfern/somnambulist-value-objects/blob/dbae7fea7140b36e105ed3f5e21a42316ea3061f/src/Types/Money/CurrencyCodeMappings.php#L47-L54
heidelpay/PhpDoc
src/phpDocumentor/Descriptor/PropertyDescriptor.php
PropertyDescriptor.getTypes
public function getTypes() { if (!$this->types) { $this->types = new Collection(); /** @var VarDescriptor $var */ $var = $this->getVar()->getIterator()->current(); if ($var) { $this->types = $var->getTypes(); } } return $this->types; }
php
public function getTypes() { if (!$this->types) { $this->types = new Collection(); /** @var VarDescriptor $var */ $var = $this->getVar()->getIterator()->current(); if ($var) { $this->types = $var->getTypes(); } } return $this->types; }
[ "public", "function", "getTypes", "(", ")", "{", "if", "(", "!", "$", "this", "->", "types", ")", "{", "$", "this", "->", "types", "=", "new", "Collection", "(", ")", ";", "/** @var VarDescriptor $var */", "$", "var", "=", "$", "this", "->", "getVar", "(", ")", "->", "getIterator", "(", ")", "->", "current", "(", ")", ";", "if", "(", "$", "var", ")", "{", "$", "this", "->", "types", "=", "$", "var", "->", "getTypes", "(", ")", ";", "}", "}", "return", "$", "this", "->", "types", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Descriptor/PropertyDescriptor.php#L101-L114
surebert/surebert-framework
src/sb/PDO/Mysql/Backup.php
Backup.connectToDb
protected function connectToDb() { try { $this->db = new PDO("mysql:dbname=;" . $this->db_host, $this->db_user, $this->db_pass); $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (\Exception $e) { $this->log("Cannot connect to database. Are the credentials correct?"); $this->log(print_r($e), 1); exit; } }
php
protected function connectToDb() { try { $this->db = new PDO("mysql:dbname=;" . $this->db_host, $this->db_user, $this->db_pass); $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (\Exception $e) { $this->log("Cannot connect to database. Are the credentials correct?"); $this->log(print_r($e), 1); exit; } }
[ "protected", "function", "connectToDb", "(", ")", "{", "try", "{", "$", "this", "->", "db", "=", "new", "PDO", "(", "\"mysql:dbname=;\"", ".", "$", "this", "->", "db_host", ",", "$", "this", "->", "db_user", ",", "$", "this", "->", "db_pass", ")", ";", "$", "this", "->", "db", "->", "setAttribute", "(", "PDO", "::", "ATTR_DEFAULT_FETCH_MODE", ",", "PDO", "::", "FETCH_OBJ", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "log", "(", "\"Cannot connect to database. Are the credentials correct?\"", ")", ";", "$", "this", "->", "log", "(", "print_r", "(", "$", "e", ")", ",", "1", ")", ";", "exit", ";", "}", "}" ]
Connects to the database
[ "Connects", "to", "the", "database" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Mysql/Backup.php#L114-L124
surebert/surebert-framework
src/sb/PDO/Mysql/Backup.php
Backup.checkDumpDir
protected function checkDumpDir() { if (!is_dir($this->dump_dir)) { mkdir($this->dump_dir, 0700, true); } foreach (\range($this->max_version, 1) as $version) { $dir = $this->dump_dir . $version; if (is_dir($dir)) { if ($version == $this->max_version) { $this->recursiveDelete($dir, 1); $this->log('Deleting backup ' . $this->max_version); } else { $new_version = $version + 1; rename($dir, $this->dump_dir . $new_version); $this->log('Moving backup ' . $version . ' to version ' . $new_version); } } } if (!is_dir($this->dump_dir . '1')) { mkdir($this->dump_dir . '1', 0700, true); } }
php
protected function checkDumpDir() { if (!is_dir($this->dump_dir)) { mkdir($this->dump_dir, 0700, true); } foreach (\range($this->max_version, 1) as $version) { $dir = $this->dump_dir . $version; if (is_dir($dir)) { if ($version == $this->max_version) { $this->recursiveDelete($dir, 1); $this->log('Deleting backup ' . $this->max_version); } else { $new_version = $version + 1; rename($dir, $this->dump_dir . $new_version); $this->log('Moving backup ' . $version . ' to version ' . $new_version); } } } if (!is_dir($this->dump_dir . '1')) { mkdir($this->dump_dir . '1', 0700, true); } }
[ "protected", "function", "checkDumpDir", "(", ")", "{", "if", "(", "!", "is_dir", "(", "$", "this", "->", "dump_dir", ")", ")", "{", "mkdir", "(", "$", "this", "->", "dump_dir", ",", "0700", ",", "true", ")", ";", "}", "foreach", "(", "\\", "range", "(", "$", "this", "->", "max_version", ",", "1", ")", "as", "$", "version", ")", "{", "$", "dir", "=", "$", "this", "->", "dump_dir", ".", "$", "version", ";", "if", "(", "is_dir", "(", "$", "dir", ")", ")", "{", "if", "(", "$", "version", "==", "$", "this", "->", "max_version", ")", "{", "$", "this", "->", "recursiveDelete", "(", "$", "dir", ",", "1", ")", ";", "$", "this", "->", "log", "(", "'Deleting backup '", ".", "$", "this", "->", "max_version", ")", ";", "}", "else", "{", "$", "new_version", "=", "$", "version", "+", "1", ";", "rename", "(", "$", "dir", ",", "$", "this", "->", "dump_dir", ".", "$", "new_version", ")", ";", "$", "this", "->", "log", "(", "'Moving backup '", ".", "$", "version", ".", "' to version '", ".", "$", "new_version", ")", ";", "}", "}", "}", "if", "(", "!", "is_dir", "(", "$", "this", "->", "dump_dir", ".", "'1'", ")", ")", "{", "mkdir", "(", "$", "this", "->", "dump_dir", ".", "'1'", ",", "0700", ",", "true", ")", ";", "}", "}" ]
check to make sure dump directory exists and if not create it
[ "check", "to", "make", "sure", "dump", "directory", "exists", "and", "if", "not", "create", "it" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Mysql/Backup.php#L129-L155
surebert/surebert-framework
src/sb/PDO/Mysql/Backup.php
Backup.dumpDatabases
protected function dumpDatabases() { foreach ($this->db->query("SHOW DATABASES") as $list) { $database = $list->Database; if (!in_array($database, $this->ignore) || preg_match("~_no_backup$~", $database)) { $start = microtime(true); $dir = $this->dump_dir . '1/'; $filename = $dir . $database; $this->log("Dumping Database: " . $database); $command = "mysqldump -u " . $this->db_user . " -h " . $this->db_host . " -p" . $this->db_pass . " " . $database . ">" . $filename . ".sql"; exec($command); $command = "tar -zcvf " . $filename . ".gz " . $filename . ".sql"; exec($command); $ms = round((microtime(true) - $start) * 1000, 2); clearstatcache(); $size = round((filesize($filename . '.gz') / 1024), 2) . 'kb'; $this->log($list->Database . " was backed up in " . $ms . ' ms and is ' . $size . ' bytes'); unlink($filename . '.sql'); } } }
php
protected function dumpDatabases() { foreach ($this->db->query("SHOW DATABASES") as $list) { $database = $list->Database; if (!in_array($database, $this->ignore) || preg_match("~_no_backup$~", $database)) { $start = microtime(true); $dir = $this->dump_dir . '1/'; $filename = $dir . $database; $this->log("Dumping Database: " . $database); $command = "mysqldump -u " . $this->db_user . " -h " . $this->db_host . " -p" . $this->db_pass . " " . $database . ">" . $filename . ".sql"; exec($command); $command = "tar -zcvf " . $filename . ".gz " . $filename . ".sql"; exec($command); $ms = round((microtime(true) - $start) * 1000, 2); clearstatcache(); $size = round((filesize($filename . '.gz') / 1024), 2) . 'kb'; $this->log($list->Database . " was backed up in " . $ms . ' ms and is ' . $size . ' bytes'); unlink($filename . '.sql'); } } }
[ "protected", "function", "dumpDatabases", "(", ")", "{", "foreach", "(", "$", "this", "->", "db", "->", "query", "(", "\"SHOW DATABASES\"", ")", "as", "$", "list", ")", "{", "$", "database", "=", "$", "list", "->", "Database", ";", "if", "(", "!", "in_array", "(", "$", "database", ",", "$", "this", "->", "ignore", ")", "||", "preg_match", "(", "\"~_no_backup$~\"", ",", "$", "database", ")", ")", "{", "$", "start", "=", "microtime", "(", "true", ")", ";", "$", "dir", "=", "$", "this", "->", "dump_dir", ".", "'1/'", ";", "$", "filename", "=", "$", "dir", ".", "$", "database", ";", "$", "this", "->", "log", "(", "\"Dumping Database: \"", ".", "$", "database", ")", ";", "$", "command", "=", "\"mysqldump -u \"", ".", "$", "this", "->", "db_user", ".", "\" -h \"", ".", "$", "this", "->", "db_host", ".", "\" -p\"", ".", "$", "this", "->", "db_pass", ".", "\" \"", ".", "$", "database", ".", "\">\"", ".", "$", "filename", ".", "\".sql\"", ";", "exec", "(", "$", "command", ")", ";", "$", "command", "=", "\"tar -zcvf \"", ".", "$", "filename", ".", "\".gz \"", ".", "$", "filename", ".", "\".sql\"", ";", "exec", "(", "$", "command", ")", ";", "$", "ms", "=", "round", "(", "(", "microtime", "(", "true", ")", "-", "$", "start", ")", "*", "1000", ",", "2", ")", ";", "clearstatcache", "(", ")", ";", "$", "size", "=", "round", "(", "(", "filesize", "(", "$", "filename", ".", "'.gz'", ")", "/", "1024", ")", ",", "2", ")", ".", "'kb'", ";", "$", "this", "->", "log", "(", "$", "list", "->", "Database", ".", "\" was backed up in \"", ".", "$", "ms", ".", "' ms and is '", ".", "$", "size", ".", "' bytes'", ")", ";", "unlink", "(", "$", "filename", ".", "'.sql'", ")", ";", "}", "}", "}" ]
Dump the database files and gzip, add version number
[ "Dump", "the", "database", "files", "and", "gzip", "add", "version", "number" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Mysql/Backup.php#L160-L191
surebert/surebert-framework
src/sb/PDO/Mysql/Backup.php
Backup.log
protected function log($message) { if ($this->debug == true) { file_put_contents("php://stdout", $message . "\n"); } file_put_contents($this->dump_dir . 'dump.log', $message . "\n", \FILE_APPEND); }
php
protected function log($message) { if ($this->debug == true) { file_put_contents("php://stdout", $message . "\n"); } file_put_contents($this->dump_dir . 'dump.log', $message . "\n", \FILE_APPEND); }
[ "protected", "function", "log", "(", "$", "message", ")", "{", "if", "(", "$", "this", "->", "debug", "==", "true", ")", "{", "file_put_contents", "(", "\"php://stdout\"", ",", "$", "message", ".", "\"\\n\"", ")", ";", "}", "file_put_contents", "(", "$", "this", "->", "dump_dir", ".", "'dump.log'", ",", "$", "message", ".", "\"\\n\"", ",", "\\", "FILE_APPEND", ")", ";", "}" ]
Send messages to stdout @param string $message
[ "Send", "messages", "to", "stdout" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Mysql/Backup.php#L197-L205
surebert/surebert-framework
src/sb/PDO/Mysql/Backup.php
Backup.recursiveDelete
protected function recursiveDelete($dir, $del = 0) { if (substr($dir, 0, 1) == '/') { throw new \Exception("You cannot delete root directories"); } $iterator = new \RecursiveDirectoryIterator($dir); foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) { $name = $file->getFilename(); if ($file->isDir() && $name != '.' && $name != '..') { rmdir($file->getPathname()); } elseif ($file->isFile()) { unlink($file->getPathname()); } } if ($del == 1) { rmdir($dir); } }
php
protected function recursiveDelete($dir, $del = 0) { if (substr($dir, 0, 1) == '/') { throw new \Exception("You cannot delete root directories"); } $iterator = new \RecursiveDirectoryIterator($dir); foreach (new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST) as $file) { $name = $file->getFilename(); if ($file->isDir() && $name != '.' && $name != '..') { rmdir($file->getPathname()); } elseif ($file->isFile()) { unlink($file->getPathname()); } } if ($del == 1) { rmdir($dir); } }
[ "protected", "function", "recursiveDelete", "(", "$", "dir", ",", "$", "del", "=", "0", ")", "{", "if", "(", "substr", "(", "$", "dir", ",", "0", ",", "1", ")", "==", "'/'", ")", "{", "throw", "new", "\\", "Exception", "(", "\"You cannot delete root directories\"", ")", ";", "}", "$", "iterator", "=", "new", "\\", "RecursiveDirectoryIterator", "(", "$", "dir", ")", ";", "foreach", "(", "new", "\\", "RecursiveIteratorIterator", "(", "$", "iterator", ",", "\\", "RecursiveIteratorIterator", "::", "CHILD_FIRST", ")", "as", "$", "file", ")", "{", "$", "name", "=", "$", "file", "->", "getFilename", "(", ")", ";", "if", "(", "$", "file", "->", "isDir", "(", ")", "&&", "$", "name", "!=", "'.'", "&&", "$", "name", "!=", "'..'", ")", "{", "rmdir", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "}", "elseif", "(", "$", "file", "->", "isFile", "(", ")", ")", "{", "unlink", "(", "$", "file", "->", "getPathname", "(", ")", ")", ";", "}", "}", "if", "(", "$", "del", "==", "1", ")", "{", "rmdir", "(", "$", "dir", ")", ";", "}", "}" ]
Recursively deletes the files in a diretory @param string $dir The directory path @param boolean $del Should directory itself be deleted upon completion @return boolean
[ "Recursively", "deletes", "the", "files", "in", "a", "diretory" ]
train
https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/PDO/Mysql/Backup.php#L214-L234
Isset/pushnotification
src/PushNotification/NotificationCenter.php
NotificationCenter.send
public function send(Message $message, string $connectionName = null): MessageEnvelope { return $this->getNotifierForMessage($message)->send($message, $connectionName); }
php
public function send(Message $message, string $connectionName = null): MessageEnvelope { return $this->getNotifierForMessage($message)->send($message, $connectionName); }
[ "public", "function", "send", "(", "Message", "$", "message", ",", "string", "$", "connectionName", "=", "null", ")", ":", "MessageEnvelope", "{", "return", "$", "this", "->", "getNotifierForMessage", "(", "$", "message", ")", "->", "send", "(", "$", "message", ",", "$", "connectionName", ")", ";", "}" ]
@param Message $message @param string $connectionName @throws NotifierNotFoundException @throws NotifyFailedException @return MessageEnvelope
[ "@param", "Message", "$message", "@param", "string", "$connectionName" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/NotificationCenter.php#L35-L38
Isset/pushnotification
src/PushNotification/NotificationCenter.php
NotificationCenter.flushQueue
public function flushQueue(string $connectionName = null) { foreach ($this->notifiers as $notifier) { $notifier->flushQueue($connectionName); } }
php
public function flushQueue(string $connectionName = null) { foreach ($this->notifiers as $notifier) { $notifier->flushQueue($connectionName); } }
[ "public", "function", "flushQueue", "(", "string", "$", "connectionName", "=", "null", ")", "{", "foreach", "(", "$", "this", "->", "notifiers", "as", "$", "notifier", ")", "{", "$", "notifier", "->", "flushQueue", "(", "$", "connectionName", ")", ";", "}", "}" ]
Flushes the queue to the notifier queues. @param string $connectionName
[ "Flushes", "the", "queue", "to", "the", "notifier", "queues", "." ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/NotificationCenter.php#L58-L63
Isset/pushnotification
src/PushNotification/NotificationCenter.php
NotificationCenter.handles
public function handles(Message $message): bool { try { $this->getNotifierForMessage($message); return true; } catch (NotifierNotFoundException $e) { return false; } }
php
public function handles(Message $message): bool { try { $this->getNotifierForMessage($message); return true; } catch (NotifierNotFoundException $e) { return false; } }
[ "public", "function", "handles", "(", "Message", "$", "message", ")", ":", "bool", "{", "try", "{", "$", "this", "->", "getNotifierForMessage", "(", "$", "message", ")", ";", "return", "true", ";", "}", "catch", "(", "NotifierNotFoundException", "$", "e", ")", "{", "return", "false", ";", "}", "}" ]
@param Message $message @return bool
[ "@param", "Message", "$message" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/NotificationCenter.php#L70-L79
Isset/pushnotification
src/PushNotification/NotificationCenter.php
NotificationCenter.addNotifier
public function addNotifier(Notifier $notifier, bool $setLogger = true) { if ($notifier instanceof self) { throw new LogicException('Cannot add self'); } if ($setLogger) { $notifier->setLogger($this->getLogger()); } $this->notifiers[] = $notifier; }
php
public function addNotifier(Notifier $notifier, bool $setLogger = true) { if ($notifier instanceof self) { throw new LogicException('Cannot add self'); } if ($setLogger) { $notifier->setLogger($this->getLogger()); } $this->notifiers[] = $notifier; }
[ "public", "function", "addNotifier", "(", "Notifier", "$", "notifier", ",", "bool", "$", "setLogger", "=", "true", ")", "{", "if", "(", "$", "notifier", "instanceof", "self", ")", "{", "throw", "new", "LogicException", "(", "'Cannot add self'", ")", ";", "}", "if", "(", "$", "setLogger", ")", "{", "$", "notifier", "->", "setLogger", "(", "$", "this", "->", "getLogger", "(", ")", ")", ";", "}", "$", "this", "->", "notifiers", "[", "]", "=", "$", "notifier", ";", "}" ]
Add a notifier to the Notification center. @param Notifier $notifier @param bool $setLogger if false the default logger will not be set to the notifier @throws LogicException
[ "Add", "a", "notifier", "to", "the", "Notification", "center", "." ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/NotificationCenter.php#L89-L99
Isset/pushnotification
src/PushNotification/NotificationCenter.php
NotificationCenter.getNotifierForMessage
public function getNotifierForMessage(Message $message): Notifier { foreach ($this->notifiers as $notifier) { if ($notifier->handles($message)) { return $notifier; } } throw new NotifierNotFoundException(); }
php
public function getNotifierForMessage(Message $message): Notifier { foreach ($this->notifiers as $notifier) { if ($notifier->handles($message)) { return $notifier; } } throw new NotifierNotFoundException(); }
[ "public", "function", "getNotifierForMessage", "(", "Message", "$", "message", ")", ":", "Notifier", "{", "foreach", "(", "$", "this", "->", "notifiers", "as", "$", "notifier", ")", "{", "if", "(", "$", "notifier", "->", "handles", "(", "$", "message", ")", ")", "{", "return", "$", "notifier", ";", "}", "}", "throw", "new", "NotifierNotFoundException", "(", ")", ";", "}" ]
@param Message $message @throws NotifierNotFoundException @return Notifier
[ "@param", "Message", "$message" ]
train
https://github.com/Isset/pushnotification/blob/5e7634dc6b1cf4f7c371d1890243a25252db0d85/src/PushNotification/NotificationCenter.php#L108-L116
ajant/SimpleArrayLibrary
src/Categories/Changers.php
Changers.addConfigRow
public static function addConfigRow(array $config, array $keys, $value) { // validation if (self::isAssociative($keys)) { throw new UnexpectedValueException('Array of config keys must be numeric'); } $row = $value; for ($i = count($keys) - 1; $i >= 0; $i--) { $row = [$keys[$i] => $row]; } $config = self::insertSubArray($config, $row); return $config; }
php
public static function addConfigRow(array $config, array $keys, $value) { // validation if (self::isAssociative($keys)) { throw new UnexpectedValueException('Array of config keys must be numeric'); } $row = $value; for ($i = count($keys) - 1; $i >= 0; $i--) { $row = [$keys[$i] => $row]; } $config = self::insertSubArray($config, $row); return $config; }
[ "public", "static", "function", "addConfigRow", "(", "array", "$", "config", ",", "array", "$", "keys", ",", "$", "value", ")", "{", "// validation", "if", "(", "self", "::", "isAssociative", "(", "$", "keys", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Array of config keys must be numeric'", ")", ";", "}", "$", "row", "=", "$", "value", ";", "for", "(", "$", "i", "=", "count", "(", "$", "keys", ")", "-", "1", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "$", "row", "=", "[", "$", "keys", "[", "$", "i", "]", "=>", "$", "row", "]", ";", "}", "$", "config", "=", "self", "::", "insertSubArray", "(", "$", "config", ",", "$", "row", ")", ";", "return", "$", "config", ";", "}" ]
@param array $config @param array $keys @param mixed $value @return array
[ "@param", "array", "$config", "@param", "array", "$keys", "@param", "mixed", "$value" ]
train
https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Changers.php#L17-L31
ajant/SimpleArrayLibrary
src/Categories/Changers.php
Changers.castColumns
public static function castColumns(array $matrix, array $castMap, $allKeysMustBePresent = true) { if (!is_bool($allKeysMustBePresent)) { throw new InvalidArgumentException('Third parameter must be a boolean'); } if (empty($matrix)) { return $matrix; } if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not cast columns on one dimensional array'); } foreach ($matrix as $key => $row) { foreach ($castMap as $column => $type) { if (isset($row[$column]) || array_key_exists($column, $row)) { switch ($type) { case self::TYPE_INT: $matrix[$key][$column] = (int)$row[$column]; break; case self::TYPE_STRING: $matrix[$key][$column] = (string)$row[$column]; break; case self::TYPE_FLOAT: $matrix[$key][$column] = (float)$row[$column]; break; case self::TYPE_BOOL: $matrix[$key][$column] = (bool)$row[$column]; break; case self::TYPE_ARRAY: $matrix[$key][$column] = (array)$row[$column]; break; case self::TYPE_OBJECT: $matrix[$key][$column] = (object)$row[$column]; break; default: throw new UnexpectedValueException('Invalid type: ' . $type); } } elseif ($allKeysMustBePresent) { throw new UnexpectedValueException('Column: ' . $column . ' missing in row: ' . $key); } } } return $matrix; }
php
public static function castColumns(array $matrix, array $castMap, $allKeysMustBePresent = true) { if (!is_bool($allKeysMustBePresent)) { throw new InvalidArgumentException('Third parameter must be a boolean'); } if (empty($matrix)) { return $matrix; } if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not cast columns on one dimensional array'); } foreach ($matrix as $key => $row) { foreach ($castMap as $column => $type) { if (isset($row[$column]) || array_key_exists($column, $row)) { switch ($type) { case self::TYPE_INT: $matrix[$key][$column] = (int)$row[$column]; break; case self::TYPE_STRING: $matrix[$key][$column] = (string)$row[$column]; break; case self::TYPE_FLOAT: $matrix[$key][$column] = (float)$row[$column]; break; case self::TYPE_BOOL: $matrix[$key][$column] = (bool)$row[$column]; break; case self::TYPE_ARRAY: $matrix[$key][$column] = (array)$row[$column]; break; case self::TYPE_OBJECT: $matrix[$key][$column] = (object)$row[$column]; break; default: throw new UnexpectedValueException('Invalid type: ' . $type); } } elseif ($allKeysMustBePresent) { throw new UnexpectedValueException('Column: ' . $column . ' missing in row: ' . $key); } } } return $matrix; }
[ "public", "static", "function", "castColumns", "(", "array", "$", "matrix", ",", "array", "$", "castMap", ",", "$", "allKeysMustBePresent", "=", "true", ")", "{", "if", "(", "!", "is_bool", "(", "$", "allKeysMustBePresent", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Third parameter must be a boolean'", ")", ";", "}", "if", "(", "empty", "(", "$", "matrix", ")", ")", "{", "return", "$", "matrix", ";", "}", "if", "(", "self", "::", "countMinDepth", "(", "$", "matrix", ")", "<", "2", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not cast columns on one dimensional array'", ")", ";", "}", "foreach", "(", "$", "matrix", "as", "$", "key", "=>", "$", "row", ")", "{", "foreach", "(", "$", "castMap", "as", "$", "column", "=>", "$", "type", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "$", "column", "]", ")", "||", "array_key_exists", "(", "$", "column", ",", "$", "row", ")", ")", "{", "switch", "(", "$", "type", ")", "{", "case", "self", "::", "TYPE_INT", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "int", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "case", "self", "::", "TYPE_STRING", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "string", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "case", "self", "::", "TYPE_FLOAT", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "float", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "case", "self", "::", "TYPE_BOOL", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "bool", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "case", "self", "::", "TYPE_ARRAY", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "array", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "case", "self", "::", "TYPE_OBJECT", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "object", ")", "$", "row", "[", "$", "column", "]", ";", "break", ";", "default", ":", "throw", "new", "UnexpectedValueException", "(", "'Invalid type: '", ".", "$", "type", ")", ";", "}", "}", "elseif", "(", "$", "allKeysMustBePresent", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Column: '", ".", "$", "column", ".", "' missing in row: '", ".", "$", "key", ")", ";", "}", "}", "}", "return", "$", "matrix", ";", "}" ]
@param array $matrix @param array $castMap @param bool $allKeysMustBePresent @return array
[ "@param", "array", "$matrix", "@param", "array", "$castMap", "@param", "bool", "$allKeysMustBePresent" ]
train
https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Changers.php#L40-L84
ajant/SimpleArrayLibrary
src/Categories/Changers.php
Changers.deleteColumns
public static function deleteColumns(array $matrix, array $columns) { // validate input if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not delete columns on one dimensional array'); } if (self::countMinDepth($columns) != 1) { throw new InvalidArgumentException('Invalid column'); } // remove columns in every row foreach ($matrix as $key => $row) { foreach ($columns as $column) { unset($matrix[$key][$column]); } } return $matrix; }
php
public static function deleteColumns(array $matrix, array $columns) { // validate input if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not delete columns on one dimensional array'); } if (self::countMinDepth($columns) != 1) { throw new InvalidArgumentException('Invalid column'); } // remove columns in every row foreach ($matrix as $key => $row) { foreach ($columns as $column) { unset($matrix[$key][$column]); } } return $matrix; }
[ "public", "static", "function", "deleteColumns", "(", "array", "$", "matrix", ",", "array", "$", "columns", ")", "{", "// validate input", "if", "(", "self", "::", "countMinDepth", "(", "$", "matrix", ")", "<", "2", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not delete columns on one dimensional array'", ")", ";", "}", "if", "(", "self", "::", "countMinDepth", "(", "$", "columns", ")", "!=", "1", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid column'", ")", ";", "}", "// remove columns in every row", "foreach", "(", "$", "matrix", "as", "$", "key", "=>", "$", "row", ")", "{", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "unset", "(", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", ")", ";", "}", "}", "return", "$", "matrix", ";", "}" ]
@param array $matrix @param mixed $columns @return array
[ "@param", "array", "$matrix", "@param", "mixed", "$columns" ]
train
https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Changers.php#L92-L110
ajant/SimpleArrayLibrary
src/Categories/Changers.php
Changers.insertSubArray
public static function insertSubArray($array, $subArray, $overwrite = false, $ignoreIfExists = false) { // validate if (!is_bool($overwrite)) { throw new InvalidArgumentException('Overwrite indicator must be a boolean'); } if (!is_bool($ignoreIfExists)) { throw new InvalidArgumentException('Ignore if exists indicator must be a boolean'); } if (!is_array($subArray) || !is_array($array)) { // $subArray[$key] is leaf of the array if ($overwrite) { $array = $subArray; } elseif (!$ignoreIfExists) { throw new UnexpectedValueException('Sub-array already exists'); } } else { $key = key($subArray); if (isset($array[$key]) || array_key_exists($key, $array)) { $array[$key] = self::insertSubArray($array[$key], $subArray[$key], $overwrite, $ignoreIfExists); } else { $array[$key] = $subArray[$key]; } } return $array; }
php
public static function insertSubArray($array, $subArray, $overwrite = false, $ignoreIfExists = false) { // validate if (!is_bool($overwrite)) { throw new InvalidArgumentException('Overwrite indicator must be a boolean'); } if (!is_bool($ignoreIfExists)) { throw new InvalidArgumentException('Ignore if exists indicator must be a boolean'); } if (!is_array($subArray) || !is_array($array)) { // $subArray[$key] is leaf of the array if ($overwrite) { $array = $subArray; } elseif (!$ignoreIfExists) { throw new UnexpectedValueException('Sub-array already exists'); } } else { $key = key($subArray); if (isset($array[$key]) || array_key_exists($key, $array)) { $array[$key] = self::insertSubArray($array[$key], $subArray[$key], $overwrite, $ignoreIfExists); } else { $array[$key] = $subArray[$key]; } } return $array; }
[ "public", "static", "function", "insertSubArray", "(", "$", "array", ",", "$", "subArray", ",", "$", "overwrite", "=", "false", ",", "$", "ignoreIfExists", "=", "false", ")", "{", "// validate", "if", "(", "!", "is_bool", "(", "$", "overwrite", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Overwrite indicator must be a boolean'", ")", ";", "}", "if", "(", "!", "is_bool", "(", "$", "ignoreIfExists", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Ignore if exists indicator must be a boolean'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "subArray", ")", "||", "!", "is_array", "(", "$", "array", ")", ")", "{", "// $subArray[$key] is leaf of the array", "if", "(", "$", "overwrite", ")", "{", "$", "array", "=", "$", "subArray", ";", "}", "elseif", "(", "!", "$", "ignoreIfExists", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Sub-array already exists'", ")", ";", "}", "}", "else", "{", "$", "key", "=", "key", "(", "$", "subArray", ")", ";", "if", "(", "isset", "(", "$", "array", "[", "$", "key", "]", ")", "||", "array_key_exists", "(", "$", "key", ",", "$", "array", ")", ")", "{", "$", "array", "[", "$", "key", "]", "=", "self", "::", "insertSubArray", "(", "$", "array", "[", "$", "key", "]", ",", "$", "subArray", "[", "$", "key", "]", ",", "$", "overwrite", ",", "$", "ignoreIfExists", ")", ";", "}", "else", "{", "$", "array", "[", "$", "key", "]", "=", "$", "subArray", "[", "$", "key", "]", ";", "}", "}", "return", "$", "array", ";", "}" ]
@param mixed $array @param mixed $subArray @param bool $overwrite @param bool $ignoreIfExists @return array
[ "@param", "mixed", "$array", "@param", "mixed", "$subArray", "@param", "bool", "$overwrite", "@param", "bool", "$ignoreIfExists" ]
train
https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Changers.php#L120-L147
ajant/SimpleArrayLibrary
src/Categories/Changers.php
Changers.setColumn
public static function setColumn(array $matrix, $column, $value, $insertIfMissing = true, $overwrite = true) { // validate input if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not set columns on one dimensional array'); } if (!is_scalar($column)) { throw new InvalidArgumentException('Invalid column'); } if (!is_bool($insertIfMissing)) { throw new InvalidArgumentException('Insert if missing indicator must be a boolean'); } if (!is_bool($overwrite)) { throw new InvalidArgumentException('Overwrite indicator must be a boolean'); } foreach ($matrix as $key => $row) { if (isset($row[$column]) || array_key_exists($column, $row)) { $matrix[$key][$column] = ($overwrite ? $value : $matrix[$key][$column]); } elseif ($insertIfMissing) { $matrix[$key][$column] = $value; } } return $matrix; }
php
public static function setColumn(array $matrix, $column, $value, $insertIfMissing = true, $overwrite = true) { // validate input if (self::countMinDepth($matrix) < 2) { throw new UnexpectedValueException('Can not set columns on one dimensional array'); } if (!is_scalar($column)) { throw new InvalidArgumentException('Invalid column'); } if (!is_bool($insertIfMissing)) { throw new InvalidArgumentException('Insert if missing indicator must be a boolean'); } if (!is_bool($overwrite)) { throw new InvalidArgumentException('Overwrite indicator must be a boolean'); } foreach ($matrix as $key => $row) { if (isset($row[$column]) || array_key_exists($column, $row)) { $matrix[$key][$column] = ($overwrite ? $value : $matrix[$key][$column]); } elseif ($insertIfMissing) { $matrix[$key][$column] = $value; } } return $matrix; }
[ "public", "static", "function", "setColumn", "(", "array", "$", "matrix", ",", "$", "column", ",", "$", "value", ",", "$", "insertIfMissing", "=", "true", ",", "$", "overwrite", "=", "true", ")", "{", "// validate input", "if", "(", "self", "::", "countMinDepth", "(", "$", "matrix", ")", "<", "2", ")", "{", "throw", "new", "UnexpectedValueException", "(", "'Can not set columns on one dimensional array'", ")", ";", "}", "if", "(", "!", "is_scalar", "(", "$", "column", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Invalid column'", ")", ";", "}", "if", "(", "!", "is_bool", "(", "$", "insertIfMissing", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Insert if missing indicator must be a boolean'", ")", ";", "}", "if", "(", "!", "is_bool", "(", "$", "overwrite", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Overwrite indicator must be a boolean'", ")", ";", "}", "foreach", "(", "$", "matrix", "as", "$", "key", "=>", "$", "row", ")", "{", "if", "(", "isset", "(", "$", "row", "[", "$", "column", "]", ")", "||", "array_key_exists", "(", "$", "column", ",", "$", "row", ")", ")", "{", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "(", "$", "overwrite", "?", "$", "value", ":", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", ")", ";", "}", "elseif", "(", "$", "insertIfMissing", ")", "{", "$", "matrix", "[", "$", "key", "]", "[", "$", "column", "]", "=", "$", "value", ";", "}", "}", "return", "$", "matrix", ";", "}" ]
@param array $matrix @param mixed $column @param mixed $value @param bool $insertIfMissing @param bool $overwrite @return array
[ "@param", "array", "$matrix", "@param", "mixed", "$column", "@param", "mixed", "$value", "@param", "bool", "$insertIfMissing", "@param", "bool", "$overwrite" ]
train
https://github.com/ajant/SimpleArrayLibrary/blob/374877c0f20a22a914eb3680eb1cf39e424071be/src/Categories/Changers.php#L158-L183
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.compile
public function compile() { $this->loadXML(); $this->id = $this->xml->firstChild->nextSibling->getAttribute('id'); $this->sessionRestore(); $this->detectAutoValidate(); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $page->linkScripts(Eresus_Kernel::app()->getLegacyKernel()->root . 'core/EresusForm.js'); $html = $this->parseExtended(); return $html; }
php
public function compile() { $this->loadXML(); $this->id = $this->xml->firstChild->nextSibling->getAttribute('id'); $this->sessionRestore(); $this->detectAutoValidate(); /** @var TAdminUI $page */ $page = Eresus_Kernel::app()->getPage(); $page->linkScripts(Eresus_Kernel::app()->getLegacyKernel()->root . 'core/EresusForm.js'); $html = $this->parseExtended(); return $html; }
[ "public", "function", "compile", "(", ")", "{", "$", "this", "->", "loadXML", "(", ")", ";", "$", "this", "->", "id", "=", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "getAttribute", "(", "'id'", ")", ";", "$", "this", "->", "sessionRestore", "(", ")", ";", "$", "this", "->", "detectAutoValidate", "(", ")", ";", "/** @var TAdminUI $page */", "$", "page", "=", "Eresus_Kernel", "::", "app", "(", ")", "->", "getPage", "(", ")", ";", "$", "page", "->", "linkScripts", "(", "Eresus_Kernel", "::", "app", "(", ")", "->", "getLegacyKernel", "(", ")", "->", "root", ".", "'core/EresusForm.js'", ")", ";", "$", "html", "=", "$", "this", "->", "parseExtended", "(", ")", ";", "return", "$", "html", ";", "}" ]
Компиляция формы @return string HTML
[ "Компиляция", "формы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L512-L526
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.unpackData
protected function unpackData($data) { $this->values = $data['values']; $this->isInvalid = $data['isInvalid']; $this->messages = $data['messages']; }
php
protected function unpackData($data) { $this->values = $data['values']; $this->isInvalid = $data['isInvalid']; $this->messages = $data['messages']; }
[ "protected", "function", "unpackData", "(", "$", "data", ")", "{", "$", "this", "->", "values", "=", "$", "data", "[", "'values'", "]", ";", "$", "this", "->", "isInvalid", "=", "$", "data", "[", "'isInvalid'", "]", ";", "$", "this", "->", "messages", "=", "$", "data", "[", "'messages'", "]", ";", "}" ]
Распаковать данные, полученные из сессии @param array $data
[ "Распаковать", "данные", "полученные", "из", "сессии" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L548-L553
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.sessionRestore
protected function sessionRestore() { if (isset($_SESSION[get_class($this)][$this->id])) { $this->unpackData($_SESSION[get_class($this)][$this->id]); unset($_SESSION[get_class($this)][$this->id]); } }
php
protected function sessionRestore() { if (isset($_SESSION[get_class($this)][$this->id])) { $this->unpackData($_SESSION[get_class($this)][$this->id]); unset($_SESSION[get_class($this)][$this->id]); } }
[ "protected", "function", "sessionRestore", "(", ")", "{", "if", "(", "isset", "(", "$", "_SESSION", "[", "get_class", "(", "$", "this", ")", "]", "[", "$", "this", "->", "id", "]", ")", ")", "{", "$", "this", "->", "unpackData", "(", "$", "_SESSION", "[", "get_class", "(", "$", "this", ")", "]", "[", "$", "this", "->", "id", "]", ")", ";", "unset", "(", "$", "_SESSION", "[", "get_class", "(", "$", "this", ")", "]", "[", "$", "this", "->", "id", "]", ")", ";", "}", "}" ]
Восстановление данных из сессии
[ "Восстановление", "данных", "из", "сессии" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L559-L566
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.parseExtended
protected function parseExtended() { $this->addFormMessagesNode(); $this->xml->firstChild->nextSibling->setAttribute('method', 'post'); $this->processBranch($this->xml->firstChild->nextSibling); /* * Обработка тегов: * 1. Удаление расширенных атрибутов * 2. Предотвращение схлопывания пустых тегов */ $tags = $this->xml->getElementsByTagName('*'); $collapsable = array('br', 'hr', 'input'); for ($i = 0; $i < $tags->length; $i++) { $node = $tags->item($i); $isElement = $node->nodeType == XML_ELEMENT_NODE; if ($isElement) { $hasAttributes = $isElement && $node->hasAttributes(); if ($hasAttributes) { $attrs = $node->attributes; for ($j = 0; $j < $attrs->length; $j++) { /* @var DOMAttr $attr */ $attr = $attrs->item($j); if ($attr->namespaceURI == self::NS) { $this->extendedAttr($node, $attr); /* * в extendedAttr текущий атрибут удаляется, поэтому следующим шагом рассматривается * элемент с тем же индексом */ $j--; } } } if ($node->textContent === '' && !in_array($node->nodeName, $collapsable)) { $cdata = $this->xml->createCDATASection(''); $node->appendChild($cdata); } } } $id = $this->xml->firstChild->nextSibling->getAttribute('id'); // инициализация объекта формы $scriptContents = "\n\$(document).ready(function () {window.$id = new EresusForm('$id');\n"; /* * Если в сессии установлен флаг isInvalid, вызываем перепроверку формы */ if ($this->mode == self::INPUT && $this->isInvalid) { $this->js []= 'validate(true);'; } // необходимо для отображения сообщений об ошибках, найденных на сервере $this->js []= 'showFormMessages();'; if ($this->js) { foreach ($this->js as $command) { $scriptContents .= "$id.$command\n"; } } $scriptContents .= "});"; $script = $this->xml->createElement('script', $scriptContents); $script->setAttribute('type', 'text/javascript'); $this->xml->firstChild->nextSibling->appendChild($script); $this->xml->formatOutput = true; $html = $this->xml->saveXML($this->xml->firstChild->nextSibling); # This exclude xml declaration $html = preg_replace('/\s*xmlns:\w+=("|\').*?("|\')/', '', $html); # Remove ns attrs /*$html = preg_replace('/<\?.*\?>/', '', $html);*/ $html = str_replace('<![CDATA[]]>', '', $html); # Remove empty <![CDATA[]]> sections return $html; }
php
protected function parseExtended() { $this->addFormMessagesNode(); $this->xml->firstChild->nextSibling->setAttribute('method', 'post'); $this->processBranch($this->xml->firstChild->nextSibling); /* * Обработка тегов: * 1. Удаление расширенных атрибутов * 2. Предотвращение схлопывания пустых тегов */ $tags = $this->xml->getElementsByTagName('*'); $collapsable = array('br', 'hr', 'input'); for ($i = 0; $i < $tags->length; $i++) { $node = $tags->item($i); $isElement = $node->nodeType == XML_ELEMENT_NODE; if ($isElement) { $hasAttributes = $isElement && $node->hasAttributes(); if ($hasAttributes) { $attrs = $node->attributes; for ($j = 0; $j < $attrs->length; $j++) { /* @var DOMAttr $attr */ $attr = $attrs->item($j); if ($attr->namespaceURI == self::NS) { $this->extendedAttr($node, $attr); /* * в extendedAttr текущий атрибут удаляется, поэтому следующим шагом рассматривается * элемент с тем же индексом */ $j--; } } } if ($node->textContent === '' && !in_array($node->nodeName, $collapsable)) { $cdata = $this->xml->createCDATASection(''); $node->appendChild($cdata); } } } $id = $this->xml->firstChild->nextSibling->getAttribute('id'); // инициализация объекта формы $scriptContents = "\n\$(document).ready(function () {window.$id = new EresusForm('$id');\n"; /* * Если в сессии установлен флаг isInvalid, вызываем перепроверку формы */ if ($this->mode == self::INPUT && $this->isInvalid) { $this->js []= 'validate(true);'; } // необходимо для отображения сообщений об ошибках, найденных на сервере $this->js []= 'showFormMessages();'; if ($this->js) { foreach ($this->js as $command) { $scriptContents .= "$id.$command\n"; } } $scriptContents .= "});"; $script = $this->xml->createElement('script', $scriptContents); $script->setAttribute('type', 'text/javascript'); $this->xml->firstChild->nextSibling->appendChild($script); $this->xml->formatOutput = true; $html = $this->xml->saveXML($this->xml->firstChild->nextSibling); # This exclude xml declaration $html = preg_replace('/\s*xmlns:\w+=("|\').*?("|\')/', '', $html); # Remove ns attrs /*$html = preg_replace('/<\?.*\?>/', '', $html);*/ $html = str_replace('<![CDATA[]]>', '', $html); # Remove empty <![CDATA[]]> sections return $html; }
[ "protected", "function", "parseExtended", "(", ")", "{", "$", "this", "->", "addFormMessagesNode", "(", ")", ";", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "setAttribute", "(", "'method'", ",", "'post'", ")", ";", "$", "this", "->", "processBranch", "(", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", ")", ";", "/*\n\t\t * Обработка тегов:\n\t\t * 1. Удаление расширенных атрибутов\n\t\t * 2. Предотвращение схлопывания пустых тегов\n\t\t */", "$", "tags", "=", "$", "this", "->", "xml", "->", "getElementsByTagName", "(", "'*'", ")", ";", "$", "collapsable", "=", "array", "(", "'br'", ",", "'hr'", ",", "'input'", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "tags", "->", "length", ";", "$", "i", "++", ")", "{", "$", "node", "=", "$", "tags", "->", "item", "(", "$", "i", ")", ";", "$", "isElement", "=", "$", "node", "->", "nodeType", "==", "XML_ELEMENT_NODE", ";", "if", "(", "$", "isElement", ")", "{", "$", "hasAttributes", "=", "$", "isElement", "&&", "$", "node", "->", "hasAttributes", "(", ")", ";", "if", "(", "$", "hasAttributes", ")", "{", "$", "attrs", "=", "$", "node", "->", "attributes", ";", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "$", "attrs", "->", "length", ";", "$", "j", "++", ")", "{", "/* @var DOMAttr $attr */", "$", "attr", "=", "$", "attrs", "->", "item", "(", "$", "j", ")", ";", "if", "(", "$", "attr", "->", "namespaceURI", "==", "self", "::", "NS", ")", "{", "$", "this", "->", "extendedAttr", "(", "$", "node", ",", "$", "attr", ")", ";", "/*\n\t\t\t\t\t\t\t * в extendedAttr текущий атрибут удаляется, поэтому следующим шагом рассматривается\n\t\t\t\t\t\t\t * элемент с тем же индексом\n\t\t\t\t\t\t\t */", "$", "j", "--", ";", "}", "}", "}", "if", "(", "$", "node", "->", "textContent", "===", "''", "&&", "!", "in_array", "(", "$", "node", "->", "nodeName", ",", "$", "collapsable", ")", ")", "{", "$", "cdata", "=", "$", "this", "->", "xml", "->", "createCDATASection", "(", "''", ")", ";", "$", "node", "->", "appendChild", "(", "$", "cdata", ")", ";", "}", "}", "}", "$", "id", "=", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "getAttribute", "(", "'id'", ")", ";", "// инициализация объекта формы", "$", "scriptContents", "=", "\"\\n\\$(document).ready(function () {window.$id = new EresusForm('$id');\\n\"", ";", "/*\n\t\t * Если в сессии установлен флаг isInvalid, вызываем перепроверку формы\n\t\t */", "if", "(", "$", "this", "->", "mode", "==", "self", "::", "INPUT", "&&", "$", "this", "->", "isInvalid", ")", "{", "$", "this", "->", "js", "[", "]", "=", "'validate(true);'", ";", "}", "// необходимо для отображения сообщений об ошибках, найденных на сервере", "$", "this", "->", "js", "[", "]", "=", "'showFormMessages();'", ";", "if", "(", "$", "this", "->", "js", ")", "{", "foreach", "(", "$", "this", "->", "js", "as", "$", "command", ")", "{", "$", "scriptContents", ".=", "\"$id.$command\\n\"", ";", "}", "}", "$", "scriptContents", ".=", "\"});\"", ";", "$", "script", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'script'", ",", "$", "scriptContents", ")", ";", "$", "script", "->", "setAttribute", "(", "'type'", ",", "'text/javascript'", ")", ";", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "appendChild", "(", "$", "script", ")", ";", "$", "this", "->", "xml", "->", "formatOutput", "=", "true", ";", "$", "html", "=", "$", "this", "->", "xml", "->", "saveXML", "(", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", ")", ";", "# This exclude xml declaration", "$", "html", "=", "preg_replace", "(", "'/\\s*xmlns:\\w+=(\"|\\').*?(\"|\\')/'", ",", "''", ",", "$", "html", ")", ";", "# Remove ns attrs", "/*$html = preg_replace('/<\\?.*\\?>/', '', $html);*/", "$", "html", "=", "str_replace", "(", "'<![CDATA[]]>'", ",", "''", ",", "$", "html", ")", ";", "# Remove empty <![CDATA[]]> sections", "return", "$", "html", ";", "}" ]
Обработка расширенного синтаксиса @return string
[ "Обработка", "расширенного", "синтаксиса" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L574-L660
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.addFormMessagesNode
protected function addFormMessagesNode() { $node = $this->xml->createElement('div'); $node->setAttribute('class', 'form-messages'); $this->xml->firstChild->nextSibling-> insertBefore($node, $this->xml->firstChild->nextSibling->firstChild); }
php
protected function addFormMessagesNode() { $node = $this->xml->createElement('div'); $node->setAttribute('class', 'form-messages'); $this->xml->firstChild->nextSibling-> insertBefore($node, $this->xml->firstChild->nextSibling->firstChild); }
[ "protected", "function", "addFormMessagesNode", "(", ")", "{", "$", "node", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'div'", ")", ";", "$", "node", "->", "setAttribute", "(", "'class'", ",", "'form-messages'", ")", ";", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "insertBefore", "(", "$", "node", ",", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "firstChild", ")", ";", "}" ]
Добавление области сообщений формы
[ "Добавление", "области", "сообщений", "формы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L666-L672
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.processBranch
protected function processBranch(DOMNode $branch) { $list = $this->childrenAsArray($branch->childNodes); for ($i = 0; $i < count($list); $i++) { $node = $list[$i]; if ($node->namespaceURI == self::NS) { $node = $this->processExtendedNode($node); } if ($node && in_array($node->nodeName, $this->inputs)) { $node = $this->processInput($node); } if ($node) { $this->processBranch($node); } //$this->processExtendedAttributes($node); } }
php
protected function processBranch(DOMNode $branch) { $list = $this->childrenAsArray($branch->childNodes); for ($i = 0; $i < count($list); $i++) { $node = $list[$i]; if ($node->namespaceURI == self::NS) { $node = $this->processExtendedNode($node); } if ($node && in_array($node->nodeName, $this->inputs)) { $node = $this->processInput($node); } if ($node) { $this->processBranch($node); } //$this->processExtendedAttributes($node); } }
[ "protected", "function", "processBranch", "(", "DOMNode", "$", "branch", ")", "{", "$", "list", "=", "$", "this", "->", "childrenAsArray", "(", "$", "branch", "->", "childNodes", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "list", ")", ";", "$", "i", "++", ")", "{", "$", "node", "=", "$", "list", "[", "$", "i", "]", ";", "if", "(", "$", "node", "->", "namespaceURI", "==", "self", "::", "NS", ")", "{", "$", "node", "=", "$", "this", "->", "processExtendedNode", "(", "$", "node", ")", ";", "}", "if", "(", "$", "node", "&&", "in_array", "(", "$", "node", "->", "nodeName", ",", "$", "this", "->", "inputs", ")", ")", "{", "$", "node", "=", "$", "this", "->", "processInput", "(", "$", "node", ")", ";", "}", "if", "(", "$", "node", ")", "{", "$", "this", "->", "processBranch", "(", "$", "node", ")", ";", "}", "//$this->processExtendedAttributes($node);", "}", "}" ]
Обработка ветки документа Метод рекурсивно перебирает все дочерние узлы $branch @param DOMNode $branch Ветка документа
[ "Обработка", "ветки", "документа" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L682-L706
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.processInput
protected function processInput($node) { $name = $node->getAttribute('name'); /* * Подставляем предопределённые значения */ if ($name) { if (isset($this->values[$name])) { switch ($node->nodeName) { case 'input': switch ($node->getAttribute('type')) { case 'password': break; case 'checkbox': if ($this->values[$name]) { $node->setAttribute('checked', 'checked'); } break; case 'radio': if ($node->getAttribute('value') == $this->values[$name]) { $node->setAttribute('checked', 'checked'); } break; default: $node->setAttribute('value', $this->values[$name]); } break; } } } return $node; }
php
protected function processInput($node) { $name = $node->getAttribute('name'); /* * Подставляем предопределённые значения */ if ($name) { if (isset($this->values[$name])) { switch ($node->nodeName) { case 'input': switch ($node->getAttribute('type')) { case 'password': break; case 'checkbox': if ($this->values[$name]) { $node->setAttribute('checked', 'checked'); } break; case 'radio': if ($node->getAttribute('value') == $this->values[$name]) { $node->setAttribute('checked', 'checked'); } break; default: $node->setAttribute('value', $this->values[$name]); } break; } } } return $node; }
[ "protected", "function", "processInput", "(", "$", "node", ")", "{", "$", "name", "=", "$", "node", "->", "getAttribute", "(", "'name'", ")", ";", "/*\n\t\t * Подставляем предопределённые значения\n\t\t */", "if", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "values", "[", "$", "name", "]", ")", ")", "{", "switch", "(", "$", "node", "->", "nodeName", ")", "{", "case", "'input'", ":", "switch", "(", "$", "node", "->", "getAttribute", "(", "'type'", ")", ")", "{", "case", "'password'", ":", "break", ";", "case", "'checkbox'", ":", "if", "(", "$", "this", "->", "values", "[", "$", "name", "]", ")", "{", "$", "node", "->", "setAttribute", "(", "'checked'", ",", "'checked'", ")", ";", "}", "break", ";", "case", "'radio'", ":", "if", "(", "$", "node", "->", "getAttribute", "(", "'value'", ")", "==", "$", "this", "->", "values", "[", "$", "name", "]", ")", "{", "$", "node", "->", "setAttribute", "(", "'checked'", ",", "'checked'", ")", ";", "}", "break", ";", "default", ":", "$", "node", "->", "setAttribute", "(", "'value'", ",", "$", "this", "->", "values", "[", "$", "name", "]", ")", ";", "}", "break", ";", "}", "}", "}", "return", "$", "node", ";", "}" ]
Обработка поля ввода @param DOMNode $node @return DOMNode
[ "Обработка", "поля", "ввода" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L714-L761
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.processExtendedNode
protected function processExtendedNode(DOMNode $node) { $handler = 'extendedNode' . $node->localName; if (method_exists($this, $handler)) { return $this->$handler($node); } else { Eresus_Kernel::log(__METHOD__, LOG_WARNING, 'Unsupported EresusForm tag "%s"', $node->localName); return $node; } }
php
protected function processExtendedNode(DOMNode $node) { $handler = 'extendedNode' . $node->localName; if (method_exists($this, $handler)) { return $this->$handler($node); } else { Eresus_Kernel::log(__METHOD__, LOG_WARNING, 'Unsupported EresusForm tag "%s"', $node->localName); return $node; } }
[ "protected", "function", "processExtendedNode", "(", "DOMNode", "$", "node", ")", "{", "$", "handler", "=", "'extendedNode'", ".", "$", "node", "->", "localName", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "handler", ")", ")", "{", "return", "$", "this", "->", "$", "handler", "(", "$", "node", ")", ";", "}", "else", "{", "Eresus_Kernel", "::", "log", "(", "__METHOD__", ",", "LOG_WARNING", ",", "'Unsupported EresusForm tag \"%s\"'", ",", "$", "node", "->", "localName", ")", ";", "return", "$", "node", ";", "}", "}" ]
Обработка расширенных тегов @param DOMNode $node Элемент @return DOMNode $node или его замена
[ "Обработка", "расширенных", "тегов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L771-L784
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeWysiwyg
protected function extendedNodeWysiwyg(DOMElement $node) { $parent = $node->parentNode; //$id = $node->getAttribute('id'); /* Создаём замену для тега wysiwyg */ $textarea = $this->xml->createElement('textarea'); $this->copyElement($node, $textarea); //$tabDiv->setAttribute('id', $id); $textarea->setAttribute('class', 'wysiwyg'); $parent->replaceChild($textarea, $node); // инициализация вкладок, проводится перед обработкой ошибок //array_unshift($this->js, 'initTabWidget("'.$node->getAttribute('id').'")'); return $textarea; }
php
protected function extendedNodeWysiwyg(DOMElement $node) { $parent = $node->parentNode; //$id = $node->getAttribute('id'); /* Создаём замену для тега wysiwyg */ $textarea = $this->xml->createElement('textarea'); $this->copyElement($node, $textarea); //$tabDiv->setAttribute('id', $id); $textarea->setAttribute('class', 'wysiwyg'); $parent->replaceChild($textarea, $node); // инициализация вкладок, проводится перед обработкой ошибок //array_unshift($this->js, 'initTabWidget("'.$node->getAttribute('id').'")'); return $textarea; }
[ "protected", "function", "extendedNodeWysiwyg", "(", "DOMElement", "$", "node", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "//$id = $node->getAttribute('id');", "/* Создаём замену для тега wysiwyg */", "$", "textarea", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'textarea'", ")", ";", "$", "this", "->", "copyElement", "(", "$", "node", ",", "$", "textarea", ")", ";", "//$tabDiv->setAttribute('id', $id);", "$", "textarea", "->", "setAttribute", "(", "'class'", ",", "'wysiwyg'", ")", ";", "$", "parent", "->", "replaceChild", "(", "$", "textarea", ",", "$", "node", ")", ";", "// инициализация вкладок, проводится перед обработкой ошибок", "//array_unshift($this->js, 'initTabWidget(\"'.$node->getAttribute('id').'\")');", "return", "$", "textarea", ";", "}" ]
Обработка тега "wysiwyg" @param DOMElement $node Элемент @return DOMElement
[ "Обработка", "тега", "wysiwyg" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L794-L811
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeTabWidget
protected function extendedNodeTabWidget(DOMNode $node) { $parent = $node->parentNode; $id = $node->getAttribute('id'); /* Создаём замену для тега tabwidget */ $tabDiv = $this->xml->createElement('div'); /* Копируем в него содержимое tabwidget */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $tabDiv->appendChild($child->cloneNode(true)); } $tabDiv->setAttribute('id', $id); $tabDiv->setAttribute('class', 'tab-widget'); $parent->replaceChild($tabDiv, $node); $tabControls = $tabDiv->getElementsByTagNameNS(self::NS, 'tabcontrol'); for ($i = 0; $i < 1; $i++) { $this->extendedNodeTabControl($tabControls->item($i), $id); } $tabs = $tabDiv->getElementsByTagNameNS(self::NS, 'tabs'); for ($i = 0; $i < 1; $i++) { $this->extendedNodeTabs($tabs->item($i), $id); } // инициализация вкладок, проводится перед обработкой ошибок array_unshift($this->js, 'initTabWidget("'.$node->getAttribute('id').'")'); return $tabDiv; }
php
protected function extendedNodeTabWidget(DOMNode $node) { $parent = $node->parentNode; $id = $node->getAttribute('id'); /* Создаём замену для тега tabwidget */ $tabDiv = $this->xml->createElement('div'); /* Копируем в него содержимое tabwidget */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $tabDiv->appendChild($child->cloneNode(true)); } $tabDiv->setAttribute('id', $id); $tabDiv->setAttribute('class', 'tab-widget'); $parent->replaceChild($tabDiv, $node); $tabControls = $tabDiv->getElementsByTagNameNS(self::NS, 'tabcontrol'); for ($i = 0; $i < 1; $i++) { $this->extendedNodeTabControl($tabControls->item($i), $id); } $tabs = $tabDiv->getElementsByTagNameNS(self::NS, 'tabs'); for ($i = 0; $i < 1; $i++) { $this->extendedNodeTabs($tabs->item($i), $id); } // инициализация вкладок, проводится перед обработкой ошибок array_unshift($this->js, 'initTabWidget("'.$node->getAttribute('id').'")'); return $tabDiv; }
[ "protected", "function", "extendedNodeTabWidget", "(", "DOMNode", "$", "node", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "$", "id", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "/* Создаём замену для тега tabwidget */", "$", "tabDiv", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'div'", ")", ";", "/* Копируем в него содержимое tabwidget */", "$", "childNodes", "=", "$", "this", "->", "childrenAsArray", "(", "$", "node", "->", "childNodes", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "childNodes", ")", ";", "$", "i", "++", ")", "{", "$", "child", "=", "$", "childNodes", "[", "$", "i", "]", ";", "$", "tabDiv", "->", "appendChild", "(", "$", "child", "->", "cloneNode", "(", "true", ")", ")", ";", "}", "$", "tabDiv", "->", "setAttribute", "(", "'id'", ",", "$", "id", ")", ";", "$", "tabDiv", "->", "setAttribute", "(", "'class'", ",", "'tab-widget'", ")", ";", "$", "parent", "->", "replaceChild", "(", "$", "tabDiv", ",", "$", "node", ")", ";", "$", "tabControls", "=", "$", "tabDiv", "->", "getElementsByTagNameNS", "(", "self", "::", "NS", ",", "'tabcontrol'", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "1", ";", "$", "i", "++", ")", "{", "$", "this", "->", "extendedNodeTabControl", "(", "$", "tabControls", "->", "item", "(", "$", "i", ")", ",", "$", "id", ")", ";", "}", "$", "tabs", "=", "$", "tabDiv", "->", "getElementsByTagNameNS", "(", "self", "::", "NS", ",", "'tabs'", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "1", ";", "$", "i", "++", ")", "{", "$", "this", "->", "extendedNodeTabs", "(", "$", "tabs", "->", "item", "(", "$", "i", ")", ",", "$", "id", ")", ";", "}", "// инициализация вкладок, проводится перед обработкой ошибок", "array_unshift", "(", "$", "this", "->", "js", ",", "'initTabWidget(\"'", ".", "$", "node", "->", "getAttribute", "(", "'id'", ")", ".", "'\")'", ")", ";", "return", "$", "tabDiv", ";", "}" ]
Обработка тега "tabwidget" @param DOMNode $node Элемент
[ "Обработка", "тега", "tabwidget" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L819-L853
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeTabControl
protected function extendedNodeTabControl(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tabcontrol */ $newNode = $this->xml->createElement('ul'); /* Копируем в него содержимое tabcontrol */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $newNode->appendChild($child->cloneNode(true)); } $parent->replaceChild($newNode, $node); $tabs = $this->childrenAsArray($newNode->getElementsByTagNameNS(self::NS, 'tab')); for ($i = 0; $i < count($tabs); $i++) { $this->extendedNodeTab($tabs[$i], $id); } return $newNode; }
php
protected function extendedNodeTabControl(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tabcontrol */ $newNode = $this->xml->createElement('ul'); /* Копируем в него содержимое tabcontrol */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $newNode->appendChild($child->cloneNode(true)); } $parent->replaceChild($newNode, $node); $tabs = $this->childrenAsArray($newNode->getElementsByTagNameNS(self::NS, 'tab')); for ($i = 0; $i < count($tabs); $i++) { $this->extendedNodeTab($tabs[$i], $id); } return $newNode; }
[ "protected", "function", "extendedNodeTabControl", "(", "DOMNode", "$", "node", ",", "$", "id", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "/* Создаём замену для тега tabcontrol */", "$", "newNode", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'ul'", ")", ";", "/* Копируем в него содержимое tabcontrol */", "$", "childNodes", "=", "$", "this", "->", "childrenAsArray", "(", "$", "node", "->", "childNodes", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "childNodes", ")", ";", "$", "i", "++", ")", "{", "$", "child", "=", "$", "childNodes", "[", "$", "i", "]", ";", "$", "newNode", "->", "appendChild", "(", "$", "child", "->", "cloneNode", "(", "true", ")", ")", ";", "}", "$", "parent", "->", "replaceChild", "(", "$", "newNode", ",", "$", "node", ")", ";", "$", "tabs", "=", "$", "this", "->", "childrenAsArray", "(", "$", "newNode", "->", "getElementsByTagNameNS", "(", "self", "::", "NS", ",", "'tab'", ")", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "tabs", ")", ";", "$", "i", "++", ")", "{", "$", "this", "->", "extendedNodeTab", "(", "$", "tabs", "[", "$", "i", "]", ",", "$", "id", ")", ";", "}", "return", "$", "newNode", ";", "}" ]
Обработка тега "tabcontrol" @param DOMNode $node Элемент @param string $id Идентификатор виджета вкладок
[ "Обработка", "тега", "tabcontrol" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L862-L884
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeTab
protected function extendedNodeTab(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tab */ $newNode = $this->xml->createElement('li'); $newNode->setAttribute('id', $id.'-btn-'.$node->getAttribute('name')); $a = $this->xml->createElement('a', $node->textContent); $a->setAttribute('href', '#'.$id.'-'.$node->getAttribute('name')); $newNode->appendChild($a); $parent->replaceChild($newNode, $node); return $newNode; }
php
protected function extendedNodeTab(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tab */ $newNode = $this->xml->createElement('li'); $newNode->setAttribute('id', $id.'-btn-'.$node->getAttribute('name')); $a = $this->xml->createElement('a', $node->textContent); $a->setAttribute('href', '#'.$id.'-'.$node->getAttribute('name')); $newNode->appendChild($a); $parent->replaceChild($newNode, $node); return $newNode; }
[ "protected", "function", "extendedNodeTab", "(", "DOMNode", "$", "node", ",", "$", "id", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "/* Создаём замену для тега tab */", "$", "newNode", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'li'", ")", ";", "$", "newNode", "->", "setAttribute", "(", "'id'", ",", "$", "id", ".", "'-btn-'", ".", "$", "node", "->", "getAttribute", "(", "'name'", ")", ")", ";", "$", "a", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'a'", ",", "$", "node", "->", "textContent", ")", ";", "$", "a", "->", "setAttribute", "(", "'href'", ",", "'#'", ".", "$", "id", ".", "'-'", ".", "$", "node", "->", "getAttribute", "(", "'name'", ")", ")", ";", "$", "newNode", "->", "appendChild", "(", "$", "a", ")", ";", "$", "parent", "->", "replaceChild", "(", "$", "newNode", ",", "$", "node", ")", ";", "return", "$", "newNode", ";", "}" ]
Обработка тега "tab" в tabcontrol @param DOMNode $node Элемент @param string $id Идентификатор виджета вкладок
[ "Обработка", "тега", "tab", "в", "tabcontrol" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L925-L938
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeTabContent
protected function extendedNodeTabContent(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tab */ $newNode = $this->xml->createElement('div'); $msgNode = $this->xml->createElement('div'); $msgNode->setAttribute('class', 'tab-messages box error hidden'); $newNode->appendChild($msgNode); /* Копируем в него содержимое tab */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $newNode->appendChild($child->cloneNode(true)); } $newNode->setAttribute('id', $id.'-'.$node->getAttribute('name')); $parent->replaceChild($newNode, $node); return $newNode; }
php
protected function extendedNodeTabContent(DOMNode $node, $id) { $parent = $node->parentNode; /* Создаём замену для тега tab */ $newNode = $this->xml->createElement('div'); $msgNode = $this->xml->createElement('div'); $msgNode->setAttribute('class', 'tab-messages box error hidden'); $newNode->appendChild($msgNode); /* Копируем в него содержимое tab */ $childNodes = $this->childrenAsArray($node->childNodes); for ($i = 0; $i < count($childNodes); $i++) { $child = $childNodes[$i]; $newNode->appendChild($child->cloneNode(true)); } $newNode->setAttribute('id', $id.'-'.$node->getAttribute('name')); $parent->replaceChild($newNode, $node); return $newNode; }
[ "protected", "function", "extendedNodeTabContent", "(", "DOMNode", "$", "node", ",", "$", "id", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "/* Создаём замену для тега tab */", "$", "newNode", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'div'", ")", ";", "$", "msgNode", "=", "$", "this", "->", "xml", "->", "createElement", "(", "'div'", ")", ";", "$", "msgNode", "->", "setAttribute", "(", "'class'", ",", "'tab-messages box error hidden'", ")", ";", "$", "newNode", "->", "appendChild", "(", "$", "msgNode", ")", ";", "/* Копируем в него содержимое tab */", "$", "childNodes", "=", "$", "this", "->", "childrenAsArray", "(", "$", "node", "->", "childNodes", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "childNodes", ")", ";", "$", "i", "++", ")", "{", "$", "child", "=", "$", "childNodes", "[", "$", "i", "]", ";", "$", "newNode", "->", "appendChild", "(", "$", "child", "->", "cloneNode", "(", "true", ")", ")", ";", "}", "$", "newNode", "->", "setAttribute", "(", "'id'", ",", "$", "id", ".", "'-'", ".", "$", "node", "->", "getAttribute", "(", "'name'", ")", ")", ";", "$", "parent", "->", "replaceChild", "(", "$", "newNode", ",", "$", "node", ")", ";", "return", "$", "newNode", ";", "}" ]
Обработка тега "tab" в tabs @param DOMNode $node Элемент @param string $id Идентификатор виджета вкладок
[ "Обработка", "тега", "tab", "в", "tabs" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L947-L967
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedNodeAttach
protected function extendedNodeAttach(DOMNode $node) { $parent = $node->parentNode; $to = $node->getAttribute('to'); /* Атрибут required */ $required = $node->getAttribute('required'); if ($required) { $this->js []= "addValidator('required', '$to', '$required');"; } /* Удаляём тег */ $parent->removeChild($node); return null; }
php
protected function extendedNodeAttach(DOMNode $node) { $parent = $node->parentNode; $to = $node->getAttribute('to'); /* Атрибут required */ $required = $node->getAttribute('required'); if ($required) { $this->js []= "addValidator('required', '$to', '$required');"; } /* Удаляём тег */ $parent->removeChild($node); return null; }
[ "protected", "function", "extendedNodeAttach", "(", "DOMNode", "$", "node", ")", "{", "$", "parent", "=", "$", "node", "->", "parentNode", ";", "$", "to", "=", "$", "node", "->", "getAttribute", "(", "'to'", ")", ";", "/* Атрибут required */", "$", "required", "=", "$", "node", "->", "getAttribute", "(", "'required'", ")", ";", "if", "(", "$", "required", ")", "{", "$", "this", "->", "js", "[", "]", "=", "\"addValidator('required', '$to', '$required');\"", ";", "}", "/* Удаляём тег */", "$", "parent", "->", "removeChild", "(", "$", "node", ")", ";", "return", "null", ";", "}" ]
Обработка тега "attach" @param DOMNode $node Элемент
[ "Обработка", "тега", "attach" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L975-L991
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedAttr
protected function extendedAttr(DOMNode $node, DOMAttr $attr) { $handler = 'extendedAttr' . $attr->name; if (method_exists($this, $handler)) { $this->$handler($node, $attr); } else { Eresus_Kernel::log(__METHOD__, LOG_WARNING, 'Unsupported EresusForm attribute "%s"', $attr->name); } $node->removeAttributeNode($attr); }
php
protected function extendedAttr(DOMNode $node, DOMAttr $attr) { $handler = 'extendedAttr' . $attr->name; if (method_exists($this, $handler)) { $this->$handler($node, $attr); } else { Eresus_Kernel::log(__METHOD__, LOG_WARNING, 'Unsupported EresusForm attribute "%s"', $attr->name); } $node->removeAttributeNode($attr); }
[ "protected", "function", "extendedAttr", "(", "DOMNode", "$", "node", ",", "DOMAttr", "$", "attr", ")", "{", "$", "handler", "=", "'extendedAttr'", ".", "$", "attr", "->", "name", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "handler", ")", ")", "{", "$", "this", "->", "$", "handler", "(", "$", "node", ",", "$", "attr", ")", ";", "}", "else", "{", "Eresus_Kernel", "::", "log", "(", "__METHOD__", ",", "LOG_WARNING", ",", "'Unsupported EresusForm attribute \"%s\"'", ",", "$", "attr", "->", "name", ")", ";", "}", "$", "node", "->", "removeAttributeNode", "(", "$", "attr", ")", ";", "}" ]
Обработка расширенных атрибутов @param DOMNode $node Элемент @param DOMAttr $attr Атрибут
[ "Обработка", "расширенных", "атрибутов" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1000-L1014
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedAttrRequired
protected function extendedAttrRequired(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $message = $attr->value; $this->js []= "addValidator('required', '#$id', '$message');"; }
php
protected function extendedAttrRequired(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $message = $attr->value; $this->js []= "addValidator('required', '#$id', '$message');"; }
[ "protected", "function", "extendedAttrRequired", "(", "DOMNode", "$", "node", ",", "DOMAttr", "$", "attr", ")", "{", "$", "id", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "$", "message", "=", "$", "attr", "->", "value", ";", "$", "this", "->", "js", "[", "]", "=", "\"addValidator('required', '#$id', '$message');\"", ";", "}" ]
Обработка атрибута "required" @param DOMNode $node Элемент @param DOMAttr $attr Атрибут
[ "Обработка", "атрибута", "required" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1023-L1030
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedAttrPassword
protected function extendedAttrPassword(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $passwordId = $attr->value; $this->js []= "addValidator('password', '#$id', '$passwordId');"; }
php
protected function extendedAttrPassword(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $passwordId = $attr->value; $this->js []= "addValidator('password', '#$id', '$passwordId');"; }
[ "protected", "function", "extendedAttrPassword", "(", "DOMNode", "$", "node", ",", "DOMAttr", "$", "attr", ")", "{", "$", "id", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "$", "passwordId", "=", "$", "attr", "->", "value", ";", "$", "this", "->", "js", "[", "]", "=", "\"addValidator('password', '#$id', '$passwordId');\"", ";", "}" ]
Обработка атрибута "password" @param DOMNode $node Элемент @param DOMAttr $attr Атрибут
[ "Обработка", "атрибута", "password" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1039-L1044
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.extendedAttrMatch
protected function extendedAttrMatch(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $pattern = $attr->value; /* Для Dwoo нужно экранировать фигурные скобки. Почему-то они передаются и сюда */ $pattern = str_replace(array('\{', '\}'), array('{', '}'), $pattern); $this->js []= "addValidator('regexp', '#$id', $pattern);"; }
php
protected function extendedAttrMatch(DOMNode $node, DOMAttr $attr) { $id = $node->getAttribute('id'); $pattern = $attr->value; /* Для Dwoo нужно экранировать фигурные скобки. Почему-то они передаются и сюда */ $pattern = str_replace(array('\{', '\}'), array('{', '}'), $pattern); $this->js []= "addValidator('regexp', '#$id', $pattern);"; }
[ "protected", "function", "extendedAttrMatch", "(", "DOMNode", "$", "node", ",", "DOMAttr", "$", "attr", ")", "{", "$", "id", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "$", "pattern", "=", "$", "attr", "->", "value", ";", "/* Для Dwoo нужно экранировать фигурные скобки. Почему-то они передаются и сюда */", "$", "pattern", "=", "str_replace", "(", "array", "(", "'\\{'", ",", "'\\}'", ")", ",", "array", "(", "'{'", ",", "'}'", ")", ",", "$", "pattern", ")", ";", "$", "this", "->", "js", "[", "]", "=", "\"addValidator('regexp', '#$id', $pattern);\"", ";", "}" ]
Обработка атрибута "match" @param DOMNode $node Элемент @param DOMAttr $attr Атрибут
[ "Обработка", "атрибута", "match" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1053-L1060
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.validate
protected function validate() { $this->loadXML(); $this->id = $this->xml->firstChild->nextSibling->getAttribute('id'); $this->detectAutoValidate(); $this->validateInputs($this->xml->firstChild->nextSibling); }
php
protected function validate() { $this->loadXML(); $this->id = $this->xml->firstChild->nextSibling->getAttribute('id'); $this->detectAutoValidate(); $this->validateInputs($this->xml->firstChild->nextSibling); }
[ "protected", "function", "validate", "(", ")", "{", "$", "this", "->", "loadXML", "(", ")", ";", "$", "this", "->", "id", "=", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "getAttribute", "(", "'id'", ")", ";", "$", "this", "->", "detectAutoValidate", "(", ")", ";", "$", "this", "->", "validateInputs", "(", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", ")", ";", "}" ]
Проверить данные формы
[ "Проверить", "данные", "формы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1088-L1095
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.validateInputs
protected function validateInputs(DOMNode $branch) { $list = $this->childrenAsArray($branch->childNodes); for ($i = 0; $i < count($list); $i++) { $node = $list[$i]; if (in_array($node->nodeName, $this->inputs)) { $this->validateInput($node); } elseif ($node->nodeName == 'fc:attach') { $this->validateAttach($node); } $this->validateInputs($node); } }
php
protected function validateInputs(DOMNode $branch) { $list = $this->childrenAsArray($branch->childNodes); for ($i = 0; $i < count($list); $i++) { $node = $list[$i]; if (in_array($node->nodeName, $this->inputs)) { $this->validateInput($node); } elseif ($node->nodeName == 'fc:attach') { $this->validateAttach($node); } $this->validateInputs($node); } }
[ "protected", "function", "validateInputs", "(", "DOMNode", "$", "branch", ")", "{", "$", "list", "=", "$", "this", "->", "childrenAsArray", "(", "$", "branch", "->", "childNodes", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "list", ")", ";", "$", "i", "++", ")", "{", "$", "node", "=", "$", "list", "[", "$", "i", "]", ";", "if", "(", "in_array", "(", "$", "node", "->", "nodeName", ",", "$", "this", "->", "inputs", ")", ")", "{", "$", "this", "->", "validateInput", "(", "$", "node", ")", ";", "}", "elseif", "(", "$", "node", "->", "nodeName", "==", "'fc:attach'", ")", "{", "$", "this", "->", "validateAttach", "(", "$", "node", ")", ";", "}", "$", "this", "->", "validateInputs", "(", "$", "node", ")", ";", "}", "}" ]
Проверка полей ввода в ветке документа на сервере Метод рекурсивно перебирает все дочерние узлы $branch @param DOMNode $branch Ветка документа
[ "Проверка", "полей", "ввода", "в", "ветке", "документа", "на", "сервере" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1105-L1125
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.validateInput
protected function validateInput($node) { $hasAttributes = $node->hasAttributes(); if ($hasAttributes) { $name = $node->getAttribute('name'); $attrs = $node->attributes; for ($i = 0; $i < $attrs->length; $i++) { $attr = $attrs->item($i); if ($attr->namespaceURI == self::NS) { switch ($attr->localName) { case 'required': $value = $this->getValue($name); if ($value === '' || is_null($value)) { if ($node->nodeName == 'input' && $node->getAttribute('type') == 'radio') { // для радиокнопок // проверить (и пометить, если нужно) это поле $this->invalidValue('input[name='.$name.']', 'required'); } else { $id = $node->getAttribute('id'); // проверить (и пометить, если нужно) это поле $this->invalidValue('#'.$id, 'required'); } } break; } } } } }
php
protected function validateInput($node) { $hasAttributes = $node->hasAttributes(); if ($hasAttributes) { $name = $node->getAttribute('name'); $attrs = $node->attributes; for ($i = 0; $i < $attrs->length; $i++) { $attr = $attrs->item($i); if ($attr->namespaceURI == self::NS) { switch ($attr->localName) { case 'required': $value = $this->getValue($name); if ($value === '' || is_null($value)) { if ($node->nodeName == 'input' && $node->getAttribute('type') == 'radio') { // для радиокнопок // проверить (и пометить, если нужно) это поле $this->invalidValue('input[name='.$name.']', 'required'); } else { $id = $node->getAttribute('id'); // проверить (и пометить, если нужно) это поле $this->invalidValue('#'.$id, 'required'); } } break; } } } } }
[ "protected", "function", "validateInput", "(", "$", "node", ")", "{", "$", "hasAttributes", "=", "$", "node", "->", "hasAttributes", "(", ")", ";", "if", "(", "$", "hasAttributes", ")", "{", "$", "name", "=", "$", "node", "->", "getAttribute", "(", "'name'", ")", ";", "$", "attrs", "=", "$", "node", "->", "attributes", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "attrs", "->", "length", ";", "$", "i", "++", ")", "{", "$", "attr", "=", "$", "attrs", "->", "item", "(", "$", "i", ")", ";", "if", "(", "$", "attr", "->", "namespaceURI", "==", "self", "::", "NS", ")", "{", "switch", "(", "$", "attr", "->", "localName", ")", "{", "case", "'required'", ":", "$", "value", "=", "$", "this", "->", "getValue", "(", "$", "name", ")", ";", "if", "(", "$", "value", "===", "''", "||", "is_null", "(", "$", "value", ")", ")", "{", "if", "(", "$", "node", "->", "nodeName", "==", "'input'", "&&", "$", "node", "->", "getAttribute", "(", "'type'", ")", "==", "'radio'", ")", "{", "// для радиокнопок", "// проверить (и пометить, если нужно) это поле", "$", "this", "->", "invalidValue", "(", "'input[name='", ".", "$", "name", ".", "']'", ",", "'required'", ")", ";", "}", "else", "{", "$", "id", "=", "$", "node", "->", "getAttribute", "(", "'id'", ")", ";", "// проверить (и пометить, если нужно) это поле", "$", "this", "->", "invalidValue", "(", "'#'", ".", "$", "id", ",", "'required'", ")", ";", "}", "}", "break", ";", "}", "}", "}", "}", "}" ]
Проверка поля ввода на сервере Дает клиенту комманду проверить элементы при загрузке страницы @param DOMNode $node
[ "Проверка", "поля", "ввода", "на", "сервере", "Дает", "клиенту", "комманду", "проверить", "элементы", "при", "загрузке", "страницы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1133-L1172
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.getValue
public function getValue($name) { if (! isset($this->values[$name])) { $this->values[$name] = arg($name); } return $this->values[$name]; }
php
public function getValue($name) { if (! isset($this->values[$name])) { $this->values[$name] = arg($name); } return $this->values[$name]; }
[ "public", "function", "getValue", "(", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "values", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "values", "[", "$", "name", "]", "=", "arg", "(", "$", "name", ")", ";", "}", "return", "$", "this", "->", "values", "[", "$", "name", "]", ";", "}" ]
Получить значение поля @param string $name @return mixed
[ "Получить", "значение", "поля" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1212-L1220
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.invalidValue
public function invalidValue($name, $description) { $this->invalidData[$name] = true; $this->addMessage($name, $description); }
php
public function invalidValue($name, $description) { $this->invalidData[$name] = true; $this->addMessage($name, $description); }
[ "public", "function", "invalidValue", "(", "$", "name", ",", "$", "description", ")", "{", "$", "this", "->", "invalidData", "[", "$", "name", "]", "=", "true", ";", "$", "this", "->", "addMessage", "(", "$", "name", ",", "$", "description", ")", ";", "}" ]
Отметить неправильное значение Устанавливает флаг invalidData @param string $name Имя значения @param string $description Описание ошибки @see invalidData
[ "Отметить", "неправильное", "значение" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1233-L1237
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.loadXML
protected function loadXML() { $tmpl = new Eresus_Template($this->template); $html = $tmpl->compile($this->values); $imp = new DOMImplementation; $dtd = $imp->createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', null); $this->xml = $imp->createDocument(null, 'html', $dtd); $html = "<!DOCTYPE root [\n" . file_get_contents(dirname(__FILE__) . '/xhtml-lat1.ent') . file_get_contents(dirname(__FILE__) . '/xhtml-special.ent') . "\n]>\n" . $html; $this->xml->loadXML($html); $this->xml->encoding = 'utf-8'; $this->xml->normalize(); }
php
protected function loadXML() { $tmpl = new Eresus_Template($this->template); $html = $tmpl->compile($this->values); $imp = new DOMImplementation; $dtd = $imp->createDocumentType('html', '-//W3C//DTD XHTML 1.0 Strict//EN', null); $this->xml = $imp->createDocument(null, 'html', $dtd); $html = "<!DOCTYPE root [\n" . file_get_contents(dirname(__FILE__) . '/xhtml-lat1.ent') . file_get_contents(dirname(__FILE__) . '/xhtml-special.ent') . "\n]>\n" . $html; $this->xml->loadXML($html); $this->xml->encoding = 'utf-8'; $this->xml->normalize(); }
[ "protected", "function", "loadXML", "(", ")", "{", "$", "tmpl", "=", "new", "Eresus_Template", "(", "$", "this", "->", "template", ")", ";", "$", "html", "=", "$", "tmpl", "->", "compile", "(", "$", "this", "->", "values", ")", ";", "$", "imp", "=", "new", "DOMImplementation", ";", "$", "dtd", "=", "$", "imp", "->", "createDocumentType", "(", "'html'", ",", "'-//W3C//DTD XHTML 1.0 Strict//EN'", ",", "null", ")", ";", "$", "this", "->", "xml", "=", "$", "imp", "->", "createDocument", "(", "null", ",", "'html'", ",", "$", "dtd", ")", ";", "$", "html", "=", "\"<!DOCTYPE root [\\n\"", ".", "file_get_contents", "(", "dirname", "(", "__FILE__", ")", ".", "'/xhtml-lat1.ent'", ")", ".", "file_get_contents", "(", "dirname", "(", "__FILE__", ")", ".", "'/xhtml-special.ent'", ")", ".", "\"\\n]>\\n\"", ".", "$", "html", ";", "$", "this", "->", "xml", "->", "loadXML", "(", "$", "html", ")", ";", "$", "this", "->", "xml", "->", "encoding", "=", "'utf-8'", ";", "$", "this", "->", "xml", "->", "normalize", "(", ")", ";", "}" ]
Компиляция XML
[ "Компиляция", "XML" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1299-L1316
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.childrenAsArray
protected function childrenAsArray($nodeList) { $result = array(); if (! is_object($nodeList)) { return $result; } if (! ($nodeList instanceof DOMNodeList)) { return $result; } for ($i = 0; $i < $nodeList->length; $i++) { $result []= $nodeList->item($i); } return $result; }
php
protected function childrenAsArray($nodeList) { $result = array(); if (! is_object($nodeList)) { return $result; } if (! ($nodeList instanceof DOMNodeList)) { return $result; } for ($i = 0; $i < $nodeList->length; $i++) { $result []= $nodeList->item($i); } return $result; }
[ "protected", "function", "childrenAsArray", "(", "$", "nodeList", ")", "{", "$", "result", "=", "array", "(", ")", ";", "if", "(", "!", "is_object", "(", "$", "nodeList", ")", ")", "{", "return", "$", "result", ";", "}", "if", "(", "!", "(", "$", "nodeList", "instanceof", "DOMNodeList", ")", ")", "{", "return", "$", "result", ";", "}", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "nodeList", "->", "length", ";", "$", "i", "++", ")", "{", "$", "result", "[", "]", "=", "$", "nodeList", "->", "item", "(", "$", "i", ")", ";", "}", "return", "$", "result", ";", "}" ]
Получить дочерние узлы в виде списка @param DOMNode $node @return array
[ "Получить", "дочерние", "узлы", "в", "виде", "списка" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1323-L1342
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.copyElement
protected function copyElement(DOMElement $source, DOMElement $target) { if ($source->hasAttributes()) { $attributes = $source->attributes; if (!is_null($attributes)) { foreach ($attributes as $attr) { $target->setAttribute($attr->name, $attr->value); } } } foreach ($source->childNodes as $child) { $target->appendChild($child->cloneNode(true)); } }
php
protected function copyElement(DOMElement $source, DOMElement $target) { if ($source->hasAttributes()) { $attributes = $source->attributes; if (!is_null($attributes)) { foreach ($attributes as $attr) { $target->setAttribute($attr->name, $attr->value); } } } foreach ($source->childNodes as $child) { $target->appendChild($child->cloneNode(true)); } }
[ "protected", "function", "copyElement", "(", "DOMElement", "$", "source", ",", "DOMElement", "$", "target", ")", "{", "if", "(", "$", "source", "->", "hasAttributes", "(", ")", ")", "{", "$", "attributes", "=", "$", "source", "->", "attributes", ";", "if", "(", "!", "is_null", "(", "$", "attributes", ")", ")", "{", "foreach", "(", "$", "attributes", "as", "$", "attr", ")", "{", "$", "target", "->", "setAttribute", "(", "$", "attr", "->", "name", ",", "$", "attr", "->", "value", ")", ";", "}", "}", "}", "foreach", "(", "$", "source", "->", "childNodes", "as", "$", "child", ")", "{", "$", "target", "->", "appendChild", "(", "$", "child", "->", "cloneNode", "(", "true", ")", ")", ";", "}", "}" ]
Копирует атрибуты элемента и его дочерние узлы @param DOMElement $source @param DOMElement $target @return void
[ "Копирует", "атрибуты", "элемента", "и", "его", "дочерние", "узлы" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1352-L1370
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.valueOf
protected function valueOf(DOMNode $node) { switch ($node->nodeName) { case 'input': switch ($node->getAttribute('type')) { case 'checkbox': return $node->getAttribute('checked') ? $node->getAttribute('value') : false; break; default: return $node->getAttribute('value'); } break; } return null; }
php
protected function valueOf(DOMNode $node) { switch ($node->nodeName) { case 'input': switch ($node->getAttribute('type')) { case 'checkbox': return $node->getAttribute('checked') ? $node->getAttribute('value') : false; break; default: return $node->getAttribute('value'); } break; } return null; }
[ "protected", "function", "valueOf", "(", "DOMNode", "$", "node", ")", "{", "switch", "(", "$", "node", "->", "nodeName", ")", "{", "case", "'input'", ":", "switch", "(", "$", "node", "->", "getAttribute", "(", "'type'", ")", ")", "{", "case", "'checkbox'", ":", "return", "$", "node", "->", "getAttribute", "(", "'checked'", ")", "?", "$", "node", "->", "getAttribute", "(", "'value'", ")", ":", "false", ";", "break", ";", "default", ":", "return", "$", "node", "->", "getAttribute", "(", "'value'", ")", ";", "}", "break", ";", "}", "return", "null", ";", "}" ]
Получение значения поля ввода @param DOMNode $node @return mixed
[ "Получение", "значения", "поля", "ввода" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1379-L1398
Eresus/EresusCMS
src/core/EresusForm.php
EresusForm.detectAutoValidate
protected function detectAutoValidate() { $this->autoValidate = true; if ($this->xml->firstChild->nextSibling->hasAttributeNS(self::NS, 'validate')) { $value = $this->xml->firstChild->nextSibling->getAttributeNS(self::NS, 'validate'); switch ($value) { case '': case '0': case 'false': $this->autoValidate = false; $this->js []= 'autoValidate = false;'; break; } } }
php
protected function detectAutoValidate() { $this->autoValidate = true; if ($this->xml->firstChild->nextSibling->hasAttributeNS(self::NS, 'validate')) { $value = $this->xml->firstChild->nextSibling->getAttributeNS(self::NS, 'validate'); switch ($value) { case '': case '0': case 'false': $this->autoValidate = false; $this->js []= 'autoValidate = false;'; break; } } }
[ "protected", "function", "detectAutoValidate", "(", ")", "{", "$", "this", "->", "autoValidate", "=", "true", ";", "if", "(", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "hasAttributeNS", "(", "self", "::", "NS", ",", "'validate'", ")", ")", "{", "$", "value", "=", "$", "this", "->", "xml", "->", "firstChild", "->", "nextSibling", "->", "getAttributeNS", "(", "self", "::", "NS", ",", "'validate'", ")", ";", "switch", "(", "$", "value", ")", "{", "case", "''", ":", "case", "'0'", ":", "case", "'false'", ":", "$", "this", "->", "autoValidate", "=", "false", ";", "$", "this", "->", "js", "[", "]", "=", "'autoValidate = false;'", ";", "break", ";", "}", "}", "}" ]
Определение режима проверки ошибок на JavaScript @return void
[ "Определение", "режима", "проверки", "ошибок", "на", "JavaScript" ]
train
https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/EresusForm.php#L1406-L1424
eghojansu/moe
src/Base.php
Base.build
function build($url,$params=array()) { $params+=$this->hive['PARAMS']; if (is_array($url)) foreach ($url as &$var) { $var=$this->build($var,$params); unset($var); } else { $i=0; $url=preg_replace_callback('/@(\w+)|\*/', function($match) use(&$i,$params) { $i++; if (isset($match[1]) && array_key_exists($match[1],$params)) return $params[$match[1]]; return array_key_exists($i,$params)? $params[$i]: $match[0]; },$url); } return $url; }
php
function build($url,$params=array()) { $params+=$this->hive['PARAMS']; if (is_array($url)) foreach ($url as &$var) { $var=$this->build($var,$params); unset($var); } else { $i=0; $url=preg_replace_callback('/@(\w+)|\*/', function($match) use(&$i,$params) { $i++; if (isset($match[1]) && array_key_exists($match[1],$params)) return $params[$match[1]]; return array_key_exists($i,$params)? $params[$i]: $match[0]; },$url); } return $url; }
[ "function", "build", "(", "$", "url", ",", "$", "params", "=", "array", "(", ")", ")", "{", "$", "params", "+=", "$", "this", "->", "hive", "[", "'PARAMS'", "]", ";", "if", "(", "is_array", "(", "$", "url", ")", ")", "foreach", "(", "$", "url", "as", "&", "$", "var", ")", "{", "$", "var", "=", "$", "this", "->", "build", "(", "$", "var", ",", "$", "params", ")", ";", "unset", "(", "$", "var", ")", ";", "}", "else", "{", "$", "i", "=", "0", ";", "$", "url", "=", "preg_replace_callback", "(", "'/@(\\w+)|\\*/'", ",", "function", "(", "$", "match", ")", "use", "(", "&", "$", "i", ",", "$", "params", ")", "{", "$", "i", "++", ";", "if", "(", "isset", "(", "$", "match", "[", "1", "]", ")", "&&", "array_key_exists", "(", "$", "match", "[", "1", "]", ",", "$", "params", ")", ")", "return", "$", "params", "[", "$", "match", "[", "1", "]", "]", ";", "return", "array_key_exists", "(", "$", "i", ",", "$", "params", ")", "?", "$", "params", "[", "$", "i", "]", ":", "$", "match", "[", "0", "]", ";", "}", ",", "$", "url", ")", ";", "}", "return", "$", "url", ";", "}" ]
Replace tokenized URL with available token values @return string @param $url array|string @param $params array
[ "Replace", "tokenized", "URL", "with", "available", "token", "values" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L124-L145
eghojansu/moe
src/Base.php
Base.parse
function parse($str) { preg_match_all('/(\w+)\h*=\h*(.+?)(?=,|$)/', $str,$pairs,PREG_SET_ORDER); $out=array(); foreach ($pairs as $pair) $out[$pair[1]]=trim($pair[2]); return $out; }
php
function parse($str) { preg_match_all('/(\w+)\h*=\h*(.+?)(?=,|$)/', $str,$pairs,PREG_SET_ORDER); $out=array(); foreach ($pairs as $pair) $out[$pair[1]]=trim($pair[2]); return $out; }
[ "function", "parse", "(", "$", "str", ")", "{", "preg_match_all", "(", "'/(\\w+)\\h*=\\h*(.+?)(?=,|$)/'", ",", "$", "str", ",", "$", "pairs", ",", "PREG_SET_ORDER", ")", ";", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "$", "pairs", "as", "$", "pair", ")", "$", "out", "[", "$", "pair", "[", "1", "]", "]", "=", "trim", "(", "$", "pair", "[", "2", "]", ")", ";", "return", "$", "out", ";", "}" ]
Parse string containing key-value pairs @return array @param $str string
[ "Parse", "string", "containing", "key", "-", "value", "pairs" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L167-L174
eghojansu/moe
src/Base.php
Base.siteUrl
function siteUrl($url, $params = array()) { return $this->hive['BASEURL'] . ltrim(empty($this->hive['ALIASES'][$url])?$url:$this->alias($url, $params), '/'); }
php
function siteUrl($url, $params = array()) { return $this->hive['BASEURL'] . ltrim(empty($this->hive['ALIASES'][$url])?$url:$this->alias($url, $params), '/'); }
[ "function", "siteUrl", "(", "$", "url", ",", "$", "params", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "hive", "[", "'BASEURL'", "]", ".", "ltrim", "(", "empty", "(", "$", "this", "->", "hive", "[", "'ALIASES'", "]", "[", "$", "url", "]", ")", "?", "$", "url", ":", "$", "this", "->", "alias", "(", "$", "url", ",", "$", "params", ")", ",", "'/'", ")", ";", "}" ]
Site Url
[ "Site", "Url" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L179-L181
eghojansu/moe
src/Base.php
Base.compile
function compile($str) { $fw=$this; return preg_replace_callback( '/(?<!\w)@(\w(?:[\w\.\[\]\(]|\->|::)*)/', function($var) use($fw) { return '$'.preg_replace_callback( '/\.(\w+)\(|\.(\w+)|\[((?:[^\[\]]*|(?R))*)\]/', function($expr) use($fw) { return $expr[1]? ((function_exists($expr[1])? ('.'.$expr[1]): ('['.var_export($expr[1],TRUE).']')).'('): ('['.var_export( isset($expr[3])? $fw->compile($expr[3]): (ctype_digit($expr[2])? (int)$expr[2]: $expr[2]),TRUE).']'); }, $var[1] ); }, $str ); }
php
function compile($str) { $fw=$this; return preg_replace_callback( '/(?<!\w)@(\w(?:[\w\.\[\]\(]|\->|::)*)/', function($var) use($fw) { return '$'.preg_replace_callback( '/\.(\w+)\(|\.(\w+)|\[((?:[^\[\]]*|(?R))*)\]/', function($expr) use($fw) { return $expr[1]? ((function_exists($expr[1])? ('.'.$expr[1]): ('['.var_export($expr[1],TRUE).']')).'('): ('['.var_export( isset($expr[3])? $fw->compile($expr[3]): (ctype_digit($expr[2])? (int)$expr[2]: $expr[2]),TRUE).']'); }, $var[1] ); }, $str ); }
[ "function", "compile", "(", "$", "str", ")", "{", "$", "fw", "=", "$", "this", ";", "return", "preg_replace_callback", "(", "'/(?<!\\w)@(\\w(?:[\\w\\.\\[\\]\\(]|\\->|::)*)/'", ",", "function", "(", "$", "var", ")", "use", "(", "$", "fw", ")", "{", "return", "'$'", ".", "preg_replace_callback", "(", "'/\\.(\\w+)\\(|\\.(\\w+)|\\[((?:[^\\[\\]]*|(?R))*)\\]/'", ",", "function", "(", "$", "expr", ")", "use", "(", "$", "fw", ")", "{", "return", "$", "expr", "[", "1", "]", "?", "(", "(", "function_exists", "(", "$", "expr", "[", "1", "]", ")", "?", "(", "'.'", ".", "$", "expr", "[", "1", "]", ")", ":", "(", "'['", ".", "var_export", "(", "$", "expr", "[", "1", "]", ",", "TRUE", ")", ".", "']'", ")", ")", ".", "'('", ")", ":", "(", "'['", ".", "var_export", "(", "isset", "(", "$", "expr", "[", "3", "]", ")", "?", "$", "fw", "->", "compile", "(", "$", "expr", "[", "3", "]", ")", ":", "(", "ctype_digit", "(", "$", "expr", "[", "2", "]", ")", "?", "(", "int", ")", "$", "expr", "[", "2", "]", ":", "$", "expr", "[", "2", "]", ")", ",", "TRUE", ")", ".", "']'", ")", ";", "}", ",", "$", "var", "[", "1", "]", ")", ";", "}", ",", "$", "str", ")", ";", "}" ]
Convert JS-style token to PHP expression @return string @param $str string
[ "Convert", "JS", "-", "style", "token", "to", "PHP", "expression" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L188-L212
eghojansu/moe
src/Base.php
Base.&
function &ref($key,$add=TRUE) { $null=NULL; $parts=$this->cut($key); if ($parts[0]=='SESSION') { @session_start(); $this->sync('SESSION'); } elseif (!preg_match('/^\w+$/',$parts[0])) user_error(sprintf(self::E_Hive,$this->stringify($key)), E_USER_ERROR); if ($add) $var=&$this->hive; else $var=$this->hive; $obj=FALSE; foreach ($parts as $part) if ($part=='->') $obj=TRUE; elseif ($obj) { $obj=FALSE; if (!is_object($var)) $var=new stdclass; if ($add || property_exists($var,$part)) $var=&$var->$part; else { $var=&$null; break; } } else { if (!is_array($var)) $var=array(); if ($add || array_key_exists($part,$var)) $var=&$var[$part]; else { $var=&$null; break; } } if ($parts[0]=='ALIASES') $var=$this->build($var); return $var; }
php
function &ref($key,$add=TRUE) { $null=NULL; $parts=$this->cut($key); if ($parts[0]=='SESSION') { @session_start(); $this->sync('SESSION'); } elseif (!preg_match('/^\w+$/',$parts[0])) user_error(sprintf(self::E_Hive,$this->stringify($key)), E_USER_ERROR); if ($add) $var=&$this->hive; else $var=$this->hive; $obj=FALSE; foreach ($parts as $part) if ($part=='->') $obj=TRUE; elseif ($obj) { $obj=FALSE; if (!is_object($var)) $var=new stdclass; if ($add || property_exists($var,$part)) $var=&$var->$part; else { $var=&$null; break; } } else { if (!is_array($var)) $var=array(); if ($add || array_key_exists($part,$var)) $var=&$var[$part]; else { $var=&$null; break; } } if ($parts[0]=='ALIASES') $var=$this->build($var); return $var; }
[ "function", "&", "ref", "(", "$", "key", ",", "$", "add", "=", "TRUE", ")", "{", "$", "null", "=", "NULL", ";", "$", "parts", "=", "$", "this", "->", "cut", "(", "$", "key", ")", ";", "if", "(", "$", "parts", "[", "0", "]", "==", "'SESSION'", ")", "{", "@", "session_start", "(", ")", ";", "$", "this", "->", "sync", "(", "'SESSION'", ")", ";", "}", "elseif", "(", "!", "preg_match", "(", "'/^\\w+$/'", ",", "$", "parts", "[", "0", "]", ")", ")", "user_error", "(", "sprintf", "(", "self", "::", "E_Hive", ",", "$", "this", "->", "stringify", "(", "$", "key", ")", ")", ",", "E_USER_ERROR", ")", ";", "if", "(", "$", "add", ")", "$", "var", "=", "&", "$", "this", "->", "hive", ";", "else", "$", "var", "=", "$", "this", "->", "hive", ";", "$", "obj", "=", "FALSE", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "if", "(", "$", "part", "==", "'->'", ")", "$", "obj", "=", "TRUE", ";", "elseif", "(", "$", "obj", ")", "{", "$", "obj", "=", "FALSE", ";", "if", "(", "!", "is_object", "(", "$", "var", ")", ")", "$", "var", "=", "new", "stdclass", ";", "if", "(", "$", "add", "||", "property_exists", "(", "$", "var", ",", "$", "part", ")", ")", "$", "var", "=", "&", "$", "var", "->", "$", "part", ";", "else", "{", "$", "var", "=", "&", "$", "null", ";", "break", ";", "}", "}", "else", "{", "if", "(", "!", "is_array", "(", "$", "var", ")", ")", "$", "var", "=", "array", "(", ")", ";", "if", "(", "$", "add", "||", "array_key_exists", "(", "$", "part", ",", "$", "var", ")", ")", "$", "var", "=", "&", "$", "var", "[", "$", "part", "]", ";", "else", "{", "$", "var", "=", "&", "$", "null", ";", "break", ";", "}", "}", "if", "(", "$", "parts", "[", "0", "]", "==", "'ALIASES'", ")", "$", "var", "=", "$", "this", "->", "build", "(", "$", "var", ")", ";", "return", "$", "var", ";", "}" ]
Get hive key reference/contents; Add non-existent hive keys, array elements, and object properties by default @return mixed @param $key string @param $add bool
[ "Get", "hive", "key", "reference", "/", "contents", ";", "Add", "non", "-", "existent", "hive", "keys", "array", "elements", "and", "object", "properties", "by", "default" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L221-L263
eghojansu/moe
src/Base.php
Base.devoid
function devoid($key) { $val=$this->ref($key,FALSE); return empty($val) && (!Cache::instance()->exists($this->hash($key).'.var',$val) || !$val); }
php
function devoid($key) { $val=$this->ref($key,FALSE); return empty($val) && (!Cache::instance()->exists($this->hash($key).'.var',$val) || !$val); }
[ "function", "devoid", "(", "$", "key", ")", "{", "$", "val", "=", "$", "this", "->", "ref", "(", "$", "key", ",", "FALSE", ")", ";", "return", "empty", "(", "$", "val", ")", "&&", "(", "!", "Cache", "::", "instance", "(", ")", "->", "exists", "(", "$", "this", "->", "hash", "(", "$", "key", ")", ".", "'.var'", ",", "$", "val", ")", "||", "!", "$", "val", ")", ";", "}" ]
Return TRUE if hive key is empty and not cached @return bool @param $key string
[ "Return", "TRUE", "if", "hive", "key", "is", "empty", "and", "not", "cached" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L284-L289
eghojansu/moe
src/Base.php
Base.set
function set($key,$val,$ttl=0) { $time=time(); if (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) { $this->set('REQUEST'.$expr[2],$val); if ($expr[1]=='COOKIE') { $parts=$this->cut($key); $jar=$this->unserialize($this->serialize($this->hive['JAR'])); if ($ttl) $jar['expire']=$time+$ttl; call_user_func_array('setcookie',array($parts[1],$val)+$jar); return $val; } } else switch ($key) { case 'CACHE': $val=Cache::instance()->load($val,TRUE); break; case 'ENCODING': ini_set('default_charset',$val); if (extension_loaded('mbstring')) mb_internal_encoding($val); break; case 'FALLBACK': $this->fallback=$val; $lang=$this->language($this->hive['LANGUAGE']); case 'LANGUAGE': if (!isset($lang)) $val=$this->language($val); $lex=$this->lexicon($this->hive['LOCALES']); case 'LOCALES': if (isset($lex) || $lex=$this->lexicon($val)) $this->mset($lex,$this->hive['PREFIX'],$ttl); break; case 'TZ': date_default_timezone_set($val); break; case 'DEBUG': !$val || ini_set('display_errors',1); break; } $ref=&$this->ref($key); $ref=$val; if (preg_match('/^JAR\b/',$key)) { $jar=$this->unserialize($this->serialize($this->hive['JAR'])); $jar['expire']-=$time; call_user_func_array('session_set_cookie_params',$jar); } $cache=Cache::instance(); if ($cache->exists($hash=$this->hash($key).'.var') || $ttl) // Persist the key-value pair $cache->set($hash,$val,$ttl); return $ref; }
php
function set($key,$val,$ttl=0) { $time=time(); if (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) { $this->set('REQUEST'.$expr[2],$val); if ($expr[1]=='COOKIE') { $parts=$this->cut($key); $jar=$this->unserialize($this->serialize($this->hive['JAR'])); if ($ttl) $jar['expire']=$time+$ttl; call_user_func_array('setcookie',array($parts[1],$val)+$jar); return $val; } } else switch ($key) { case 'CACHE': $val=Cache::instance()->load($val,TRUE); break; case 'ENCODING': ini_set('default_charset',$val); if (extension_loaded('mbstring')) mb_internal_encoding($val); break; case 'FALLBACK': $this->fallback=$val; $lang=$this->language($this->hive['LANGUAGE']); case 'LANGUAGE': if (!isset($lang)) $val=$this->language($val); $lex=$this->lexicon($this->hive['LOCALES']); case 'LOCALES': if (isset($lex) || $lex=$this->lexicon($val)) $this->mset($lex,$this->hive['PREFIX'],$ttl); break; case 'TZ': date_default_timezone_set($val); break; case 'DEBUG': !$val || ini_set('display_errors',1); break; } $ref=&$this->ref($key); $ref=$val; if (preg_match('/^JAR\b/',$key)) { $jar=$this->unserialize($this->serialize($this->hive['JAR'])); $jar['expire']-=$time; call_user_func_array('session_set_cookie_params',$jar); } $cache=Cache::instance(); if ($cache->exists($hash=$this->hash($key).'.var') || $ttl) // Persist the key-value pair $cache->set($hash,$val,$ttl); return $ref; }
[ "function", "set", "(", "$", "key", ",", "$", "val", ",", "$", "ttl", "=", "0", ")", "{", "$", "time", "=", "time", "(", ")", ";", "if", "(", "preg_match", "(", "'/^(GET|POST|COOKIE)\\b(.+)/'", ",", "$", "key", ",", "$", "expr", ")", ")", "{", "$", "this", "->", "set", "(", "'REQUEST'", ".", "$", "expr", "[", "2", "]", ",", "$", "val", ")", ";", "if", "(", "$", "expr", "[", "1", "]", "==", "'COOKIE'", ")", "{", "$", "parts", "=", "$", "this", "->", "cut", "(", "$", "key", ")", ";", "$", "jar", "=", "$", "this", "->", "unserialize", "(", "$", "this", "->", "serialize", "(", "$", "this", "->", "hive", "[", "'JAR'", "]", ")", ")", ";", "if", "(", "$", "ttl", ")", "$", "jar", "[", "'expire'", "]", "=", "$", "time", "+", "$", "ttl", ";", "call_user_func_array", "(", "'setcookie'", ",", "array", "(", "$", "parts", "[", "1", "]", ",", "$", "val", ")", "+", "$", "jar", ")", ";", "return", "$", "val", ";", "}", "}", "else", "switch", "(", "$", "key", ")", "{", "case", "'CACHE'", ":", "$", "val", "=", "Cache", "::", "instance", "(", ")", "->", "load", "(", "$", "val", ",", "TRUE", ")", ";", "break", ";", "case", "'ENCODING'", ":", "ini_set", "(", "'default_charset'", ",", "$", "val", ")", ";", "if", "(", "extension_loaded", "(", "'mbstring'", ")", ")", "mb_internal_encoding", "(", "$", "val", ")", ";", "break", ";", "case", "'FALLBACK'", ":", "$", "this", "->", "fallback", "=", "$", "val", ";", "$", "lang", "=", "$", "this", "->", "language", "(", "$", "this", "->", "hive", "[", "'LANGUAGE'", "]", ")", ";", "case", "'LANGUAGE'", ":", "if", "(", "!", "isset", "(", "$", "lang", ")", ")", "$", "val", "=", "$", "this", "->", "language", "(", "$", "val", ")", ";", "$", "lex", "=", "$", "this", "->", "lexicon", "(", "$", "this", "->", "hive", "[", "'LOCALES'", "]", ")", ";", "case", "'LOCALES'", ":", "if", "(", "isset", "(", "$", "lex", ")", "||", "$", "lex", "=", "$", "this", "->", "lexicon", "(", "$", "val", ")", ")", "$", "this", "->", "mset", "(", "$", "lex", ",", "$", "this", "->", "hive", "[", "'PREFIX'", "]", ",", "$", "ttl", ")", ";", "break", ";", "case", "'TZ'", ":", "date_default_timezone_set", "(", "$", "val", ")", ";", "break", ";", "case", "'DEBUG'", ":", "!", "$", "val", "||", "ini_set", "(", "'display_errors'", ",", "1", ")", ";", "break", ";", "}", "$", "ref", "=", "&", "$", "this", "->", "ref", "(", "$", "key", ")", ";", "$", "ref", "=", "$", "val", ";", "if", "(", "preg_match", "(", "'/^JAR\\b/'", ",", "$", "key", ")", ")", "{", "$", "jar", "=", "$", "this", "->", "unserialize", "(", "$", "this", "->", "serialize", "(", "$", "this", "->", "hive", "[", "'JAR'", "]", ")", ")", ";", "$", "jar", "[", "'expire'", "]", "-=", "$", "time", ";", "call_user_func_array", "(", "'session_set_cookie_params'", ",", "$", "jar", ")", ";", "}", "$", "cache", "=", "Cache", "::", "instance", "(", ")", ";", "if", "(", "$", "cache", "->", "exists", "(", "$", "hash", "=", "$", "this", "->", "hash", "(", "$", "key", ")", ".", "'.var'", ")", "||", "$", "ttl", ")", "// Persist the key-value pair", "$", "cache", "->", "set", "(", "$", "hash", ",", "$", "val", ",", "$", "ttl", ")", ";", "return", "$", "ref", ";", "}" ]
Bind value to hive key @return mixed @param $key string @param $val mixed @param $ttl int
[ "Bind", "value", "to", "hive", "key" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L298-L350
eghojansu/moe
src/Base.php
Base.get
function get($key,$args=NULL) { if (is_string($val=$this->ref($key,FALSE)) && !is_null($args)) return call_user_func_array( array($this,'format'), array_merge(array($val),is_array($args)?$args:array($args)) ); if (is_null($val)) { // Attempt to retrieve from cache if (Cache::instance()->exists($this->hash($key).'.var',$data)) return $data; } return $val; }
php
function get($key,$args=NULL) { if (is_string($val=$this->ref($key,FALSE)) && !is_null($args)) return call_user_func_array( array($this,'format'), array_merge(array($val),is_array($args)?$args:array($args)) ); if (is_null($val)) { // Attempt to retrieve from cache if (Cache::instance()->exists($this->hash($key).'.var',$data)) return $data; } return $val; }
[ "function", "get", "(", "$", "key", ",", "$", "args", "=", "NULL", ")", "{", "if", "(", "is_string", "(", "$", "val", "=", "$", "this", "->", "ref", "(", "$", "key", ",", "FALSE", ")", ")", "&&", "!", "is_null", "(", "$", "args", ")", ")", "return", "call_user_func_array", "(", "array", "(", "$", "this", ",", "'format'", ")", ",", "array_merge", "(", "array", "(", "$", "val", ")", ",", "is_array", "(", "$", "args", ")", "?", "$", "args", ":", "array", "(", "$", "args", ")", ")", ")", ";", "if", "(", "is_null", "(", "$", "val", ")", ")", "{", "// Attempt to retrieve from cache", "if", "(", "Cache", "::", "instance", "(", ")", "->", "exists", "(", "$", "this", "->", "hash", "(", "$", "key", ")", ".", "'.var'", ",", "$", "data", ")", ")", "return", "$", "data", ";", "}", "return", "$", "val", ";", "}" ]
Retrieve contents of hive key @return mixed @param $key string @param $args string|array
[ "Retrieve", "contents", "of", "hive", "key" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L358-L370
eghojansu/moe
src/Base.php
Base.merge
function merge($key,$src) { $ref=&$this->ref($key); return ($ref = array_merge($ref,is_string($src)?$this->hive[$src]:$src)); }
php
function merge($key,$src) { $ref=&$this->ref($key); return ($ref = array_merge($ref,is_string($src)?$this->hive[$src]:$src)); }
[ "function", "merge", "(", "$", "key", ",", "$", "src", ")", "{", "$", "ref", "=", "&", "$", "this", "->", "ref", "(", "$", "key", ")", ";", "return", "(", "$", "ref", "=", "array_merge", "(", "$", "ref", ",", "is_string", "(", "$", "src", ")", "?", "$", "this", "->", "hive", "[", "$", "src", "]", ":", "$", "src", ")", ")", ";", "}" ]
Merge array with hive array variable @return array @param $key string @param $src string|array
[ "Merge", "array", "with", "hive", "array", "variable" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L551-L554
eghojansu/moe
src/Base.php
Base.readByte
function readByte($byte, $precision = 7) { $unit = array('Byte','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'); if (is_numeric($byte)) { $w = floor((strlen($byte) - 1) / 3); return sprintf("%.{$precision}f %s", $byte/pow(1024, $w), $unit[$w]); } $str = array_values(array_filter(explode(' ', $byte))); return array_shift($str)*pow(1024, (int) array_search(array_shift($str), $unit)).' '.$unit[0]; }
php
function readByte($byte, $precision = 7) { $unit = array('Byte','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'); if (is_numeric($byte)) { $w = floor((strlen($byte) - 1) / 3); return sprintf("%.{$precision}f %s", $byte/pow(1024, $w), $unit[$w]); } $str = array_values(array_filter(explode(' ', $byte))); return array_shift($str)*pow(1024, (int) array_search(array_shift($str), $unit)).' '.$unit[0]; }
[ "function", "readByte", "(", "$", "byte", ",", "$", "precision", "=", "7", ")", "{", "$", "unit", "=", "array", "(", "'Byte'", ",", "'KiB'", ",", "'MiB'", ",", "'GiB'", ",", "'TiB'", ",", "'PiB'", ",", "'EiB'", ",", "'ZiB'", ",", "'YiB'", ")", ";", "if", "(", "is_numeric", "(", "$", "byte", ")", ")", "{", "$", "w", "=", "floor", "(", "(", "strlen", "(", "$", "byte", ")", "-", "1", ")", "/", "3", ")", ";", "return", "sprintf", "(", "\"%.{$precision}f %s\"", ",", "$", "byte", "/", "pow", "(", "1024", ",", "$", "w", ")", ",", "$", "unit", "[", "$", "w", "]", ")", ";", "}", "$", "str", "=", "array_values", "(", "array_filter", "(", "explode", "(", "' '", ",", "$", "byte", ")", ")", ")", ";", "return", "array_shift", "(", "$", "str", ")", "*", "pow", "(", "1024", ",", "(", "int", ")", "array_search", "(", "array_shift", "(", "$", "str", ")", ",", "$", "unit", ")", ")", ".", "' '", ".", "$", "unit", "[", "0", "]", ";", "}" ]
Convert byte @return string byte
[ "Convert", "byte" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L618-L630
eghojansu/moe
src/Base.php
Base.random
function random($len) { $len = abs($len); $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $poolLen = strlen($pool); $str = ''; while ($len-- > 0) $str .= substr($pool, rand(0, $poolLen), 1); return $str; }
php
function random($len) { $len = abs($len); $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $poolLen = strlen($pool); $str = ''; while ($len-- > 0) $str .= substr($pool, rand(0, $poolLen), 1); return $str; }
[ "function", "random", "(", "$", "len", ")", "{", "$", "len", "=", "abs", "(", "$", "len", ")", ";", "$", "pool", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'", ";", "$", "poolLen", "=", "strlen", "(", "$", "pool", ")", ";", "$", "str", "=", "''", ";", "while", "(", "$", "len", "--", ">", "0", ")", "$", "str", ".=", "substr", "(", "$", "pool", ",", "rand", "(", "0", ",", "$", "poolLen", ")", ",", "1", ")", ";", "return", "$", "str", ";", "}" ]
Generate random string @param int $len random string length @return string random string
[ "Generate", "random", "string" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L637-L647
eghojansu/moe
src/Base.php
Base.pre
function pre($data, $exit = false) { echo '<pre>'; print_r($data); echo '</pre>'; !$exit || exit(str_repeat('<br>', 2).' '.$exit); echo '<hr>'; }
php
function pre($data, $exit = false) { echo '<pre>'; print_r($data); echo '</pre>'; !$exit || exit(str_repeat('<br>', 2).' '.$exit); echo '<hr>'; }
[ "function", "pre", "(", "$", "data", ",", "$", "exit", "=", "false", ")", "{", "echo", "'<pre>'", ";", "print_r", "(", "$", "data", ")", ";", "echo", "'</pre>'", ";", "!", "$", "exit", "||", "exit", "(", "str_repeat", "(", "'<br>'", ",", "2", ")", ".", "' '", ".", "$", "exit", ")", ";", "echo", "'<hr>'", ";", "}" ]
Output the data @param mixed $data @param bool $exit wether to exit after dumping or not
[ "Output", "the", "data" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L654-L661
eghojansu/moe
src/Base.php
Base.ulMenu
function ulMenu($menu, $active) { $menu || $menu = array(); $active = str_replace('@', '', $active); $opt = [ 'href'=>'', 'label'=>'', 'class'=>'', 'activeClass'=>'active', 'type'=>'ul', 'child'=>[ 'class'=>'', 'li'=>[ 'class'=>'', 'attributes'=>[], ], 'a'=>[ 'class'=>'', 'attributes'=>[], ], ], 'level'=>-1, 'hide'=>false, 'items'=>[], ]; $menu += $opt; $menu['level']++; $eol = PHP_EOL; $str = sprintf('<%s class="%s">', $menu['type'], ($menu['level']>0?$menu['child']['class']:$menu['class'])).$eol; $activeClass = $menu['activeClass']; foreach ($menu['items'] as $key => $value) { $value += $opt; if ($value['hide']) continue; $value['label'] || $value['label'] = $key; $hasChild = count($value['items'])>0; $liAttr = [ 'class'=>[$menu['child']['li']['class']], 'attributes'=>$menu['child']['a']['attributes'], ]; $aAttr = [ 'href'=>$value['href']?:($Instance::get('ALIASES.'.$key)?Instance::siteUrl($key):'#'), 'class'=>[$menu['child']['a']['class']], 'attributes'=>$menu['child']['a']['attributes'], ]; $child = ''; if ($hasChild) { $value['level'] = $menu['level'] + 1; $child = $eol.$this->ulMenu($value, $active).$eol; } if ($active === $key || preg_match('/".*'.$activeClass.'.*"/i', $child)) { array_push($liAttr['class'], $child); array_push($aAttr['class'], $child); } $attr = array_pop($liAttr); $liAttr = array_merge($liAttr, $attr); $attr = array_pop($aAttr); $aAttr = array_merge($aAttr, $attr); $str .= '<li'; foreach ($liAttr as $key2 => $value2) !$value2 || $str .= ' '.$key2.'="'. (is_array($value2)?implode(' ', $value2):$value2).'"'; $str .= '><a'; foreach ($aAttr as $key2 => $value2) !$value2 || $str .= ' '.$key2.'="'. (is_array($value2)?implode(' ', $value2):$value2).'"'; $str .= '>'.$value['label'].'</a>'; $str .= $child; $str .= '</li>'.$eol; } $str .= '</'.$menu['type'].'>'; return $str; }
php
function ulMenu($menu, $active) { $menu || $menu = array(); $active = str_replace('@', '', $active); $opt = [ 'href'=>'', 'label'=>'', 'class'=>'', 'activeClass'=>'active', 'type'=>'ul', 'child'=>[ 'class'=>'', 'li'=>[ 'class'=>'', 'attributes'=>[], ], 'a'=>[ 'class'=>'', 'attributes'=>[], ], ], 'level'=>-1, 'hide'=>false, 'items'=>[], ]; $menu += $opt; $menu['level']++; $eol = PHP_EOL; $str = sprintf('<%s class="%s">', $menu['type'], ($menu['level']>0?$menu['child']['class']:$menu['class'])).$eol; $activeClass = $menu['activeClass']; foreach ($menu['items'] as $key => $value) { $value += $opt; if ($value['hide']) continue; $value['label'] || $value['label'] = $key; $hasChild = count($value['items'])>0; $liAttr = [ 'class'=>[$menu['child']['li']['class']], 'attributes'=>$menu['child']['a']['attributes'], ]; $aAttr = [ 'href'=>$value['href']?:($Instance::get('ALIASES.'.$key)?Instance::siteUrl($key):'#'), 'class'=>[$menu['child']['a']['class']], 'attributes'=>$menu['child']['a']['attributes'], ]; $child = ''; if ($hasChild) { $value['level'] = $menu['level'] + 1; $child = $eol.$this->ulMenu($value, $active).$eol; } if ($active === $key || preg_match('/".*'.$activeClass.'.*"/i', $child)) { array_push($liAttr['class'], $child); array_push($aAttr['class'], $child); } $attr = array_pop($liAttr); $liAttr = array_merge($liAttr, $attr); $attr = array_pop($aAttr); $aAttr = array_merge($aAttr, $attr); $str .= '<li'; foreach ($liAttr as $key2 => $value2) !$value2 || $str .= ' '.$key2.'="'. (is_array($value2)?implode(' ', $value2):$value2).'"'; $str .= '><a'; foreach ($aAttr as $key2 => $value2) !$value2 || $str .= ' '.$key2.'="'. (is_array($value2)?implode(' ', $value2):$value2).'"'; $str .= '>'.$value['label'].'</a>'; $str .= $child; $str .= '</li>'.$eol; } $str .= '</'.$menu['type'].'>'; return $str; }
[ "function", "ulMenu", "(", "$", "menu", ",", "$", "active", ")", "{", "$", "menu", "||", "$", "menu", "=", "array", "(", ")", ";", "$", "active", "=", "str_replace", "(", "'@'", ",", "''", ",", "$", "active", ")", ";", "$", "opt", "=", "[", "'href'", "=>", "''", ",", "'label'", "=>", "''", ",", "'class'", "=>", "''", ",", "'activeClass'", "=>", "'active'", ",", "'type'", "=>", "'ul'", ",", "'child'", "=>", "[", "'class'", "=>", "''", ",", "'li'", "=>", "[", "'class'", "=>", "''", ",", "'attributes'", "=>", "[", "]", ",", "]", ",", "'a'", "=>", "[", "'class'", "=>", "''", ",", "'attributes'", "=>", "[", "]", ",", "]", ",", "]", ",", "'level'", "=>", "-", "1", ",", "'hide'", "=>", "false", ",", "'items'", "=>", "[", "]", ",", "]", ";", "$", "menu", "+=", "$", "opt", ";", "$", "menu", "[", "'level'", "]", "++", ";", "$", "eol", "=", "PHP_EOL", ";", "$", "str", "=", "sprintf", "(", "'<%s class=\"%s\">'", ",", "$", "menu", "[", "'type'", "]", ",", "(", "$", "menu", "[", "'level'", "]", ">", "0", "?", "$", "menu", "[", "'child'", "]", "[", "'class'", "]", ":", "$", "menu", "[", "'class'", "]", ")", ")", ".", "$", "eol", ";", "$", "activeClass", "=", "$", "menu", "[", "'activeClass'", "]", ";", "foreach", "(", "$", "menu", "[", "'items'", "]", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "value", "+=", "$", "opt", ";", "if", "(", "$", "value", "[", "'hide'", "]", ")", "continue", ";", "$", "value", "[", "'label'", "]", "||", "$", "value", "[", "'label'", "]", "=", "$", "key", ";", "$", "hasChild", "=", "count", "(", "$", "value", "[", "'items'", "]", ")", ">", "0", ";", "$", "liAttr", "=", "[", "'class'", "=>", "[", "$", "menu", "[", "'child'", "]", "[", "'li'", "]", "[", "'class'", "]", "]", ",", "'attributes'", "=>", "$", "menu", "[", "'child'", "]", "[", "'a'", "]", "[", "'attributes'", "]", ",", "]", ";", "$", "aAttr", "=", "[", "'href'", "=>", "$", "value", "[", "'href'", "]", "?", ":", "(", "$", "Instance", "::", "get", "(", "'ALIASES.'", ".", "$", "key", ")", "?", "Instance", "::", "siteUrl", "(", "$", "key", ")", ":", "'#'", ")", ",", "'class'", "=>", "[", "$", "menu", "[", "'child'", "]", "[", "'a'", "]", "[", "'class'", "]", "]", ",", "'attributes'", "=>", "$", "menu", "[", "'child'", "]", "[", "'a'", "]", "[", "'attributes'", "]", ",", "]", ";", "$", "child", "=", "''", ";", "if", "(", "$", "hasChild", ")", "{", "$", "value", "[", "'level'", "]", "=", "$", "menu", "[", "'level'", "]", "+", "1", ";", "$", "child", "=", "$", "eol", ".", "$", "this", "->", "ulMenu", "(", "$", "value", ",", "$", "active", ")", ".", "$", "eol", ";", "}", "if", "(", "$", "active", "===", "$", "key", "||", "preg_match", "(", "'/\".*'", ".", "$", "activeClass", ".", "'.*\"/i'", ",", "$", "child", ")", ")", "{", "array_push", "(", "$", "liAttr", "[", "'class'", "]", ",", "$", "child", ")", ";", "array_push", "(", "$", "aAttr", "[", "'class'", "]", ",", "$", "child", ")", ";", "}", "$", "attr", "=", "array_pop", "(", "$", "liAttr", ")", ";", "$", "liAttr", "=", "array_merge", "(", "$", "liAttr", ",", "$", "attr", ")", ";", "$", "attr", "=", "array_pop", "(", "$", "aAttr", ")", ";", "$", "aAttr", "=", "array_merge", "(", "$", "aAttr", ",", "$", "attr", ")", ";", "$", "str", ".=", "'<li'", ";", "foreach", "(", "$", "liAttr", "as", "$", "key2", "=>", "$", "value2", ")", "!", "$", "value2", "||", "$", "str", ".=", "' '", ".", "$", "key2", ".", "'=\"'", ".", "(", "is_array", "(", "$", "value2", ")", "?", "implode", "(", "' '", ",", "$", "value2", ")", ":", "$", "value2", ")", ".", "'\"'", ";", "$", "str", ".=", "'><a'", ";", "foreach", "(", "$", "aAttr", "as", "$", "key2", "=>", "$", "value2", ")", "!", "$", "value2", "||", "$", "str", ".=", "' '", ".", "$", "key2", ".", "'=\"'", ".", "(", "is_array", "(", "$", "value2", ")", "?", "implode", "(", "' '", ",", "$", "value2", ")", ":", "$", "value2", ")", ".", "'\"'", ";", "$", "str", ".=", "'>'", ".", "$", "value", "[", "'label'", "]", ".", "'</a>'", ";", "$", "str", ".=", "$", "child", ";", "$", "str", ".=", "'</li>'", ".", "$", "eol", ";", "}", "$", "str", ".=", "'</'", ".", "$", "menu", "[", "'type'", "]", ".", "'>'", ";", "return", "$", "str", ";", "}" ]
Generate html list menu @param array $menu @param string $active active url (token alias) @return string ul html
[ "Generate", "html", "list", "menu" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L669-L750
eghojansu/moe
src/Base.php
Base.constants
function constants($class,$prefix='') { $ref=new ReflectionClass($class); $out=array(); foreach (preg_grep('/^'.$prefix.'/',array_keys($ref->getconstants())) as $val) { $out[$key=substr($val,strlen($prefix))]= constant((is_object($class)?get_class($class):$class).'::'.$prefix.$key); } unset($ref); return $out; }
php
function constants($class,$prefix='') { $ref=new ReflectionClass($class); $out=array(); foreach (preg_grep('/^'.$prefix.'/',array_keys($ref->getconstants())) as $val) { $out[$key=substr($val,strlen($prefix))]= constant((is_object($class)?get_class($class):$class).'::'.$prefix.$key); } unset($ref); return $out; }
[ "function", "constants", "(", "$", "class", ",", "$", "prefix", "=", "''", ")", "{", "$", "ref", "=", "new", "ReflectionClass", "(", "$", "class", ")", ";", "$", "out", "=", "array", "(", ")", ";", "foreach", "(", "preg_grep", "(", "'/^'", ".", "$", "prefix", ".", "'/'", ",", "array_keys", "(", "$", "ref", "->", "getconstants", "(", ")", ")", ")", "as", "$", "val", ")", "{", "$", "out", "[", "$", "key", "=", "substr", "(", "$", "val", ",", "strlen", "(", "$", "prefix", ")", ")", "]", "=", "constant", "(", "(", "is_object", "(", "$", "class", ")", "?", "get_class", "(", "$", "class", ")", ":", "$", "class", ")", ".", "'::'", ".", "$", "prefix", ".", "$", "key", ")", ";", "}", "unset", "(", "$", "ref", ")", ";", "return", "$", "out", ";", "}" ]
Convert class constants to array @return array @param $class object|string @param $prefix string
[ "Convert", "class", "constants", "to", "array" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L827-L837
eghojansu/moe
src/Base.php
Base.recursive
function recursive($arg,$func,$stack=NULL) { if ($stack) { foreach ($stack as $node) if ($arg===$node) return $arg; } else $stack=array(); switch (gettype($arg)) { case 'object': if (method_exists('ReflectionClass','iscloneable')) { $ref=new ReflectionClass($arg); if ($ref->iscloneable()) { $arg=clone($arg); $cast=is_a($arg,'IteratorAggregate')? iterator_to_array($arg):get_object_vars($arg); foreach ($cast as $key=>$val) $arg->$key=$this->recursive( $val,$func,array_merge($stack,array($arg))); } } return $arg; case 'array': $copy=array(); foreach ($arg as $key=>$val) $copy[$key]=$this->recursive($val,$func, array_merge($stack,array($arg))); return $copy; } return $func($arg); }
php
function recursive($arg,$func,$stack=NULL) { if ($stack) { foreach ($stack as $node) if ($arg===$node) return $arg; } else $stack=array(); switch (gettype($arg)) { case 'object': if (method_exists('ReflectionClass','iscloneable')) { $ref=new ReflectionClass($arg); if ($ref->iscloneable()) { $arg=clone($arg); $cast=is_a($arg,'IteratorAggregate')? iterator_to_array($arg):get_object_vars($arg); foreach ($cast as $key=>$val) $arg->$key=$this->recursive( $val,$func,array_merge($stack,array($arg))); } } return $arg; case 'array': $copy=array(); foreach ($arg as $key=>$val) $copy[$key]=$this->recursive($val,$func, array_merge($stack,array($arg))); return $copy; } return $func($arg); }
[ "function", "recursive", "(", "$", "arg", ",", "$", "func", ",", "$", "stack", "=", "NULL", ")", "{", "if", "(", "$", "stack", ")", "{", "foreach", "(", "$", "stack", "as", "$", "node", ")", "if", "(", "$", "arg", "===", "$", "node", ")", "return", "$", "arg", ";", "}", "else", "$", "stack", "=", "array", "(", ")", ";", "switch", "(", "gettype", "(", "$", "arg", ")", ")", "{", "case", "'object'", ":", "if", "(", "method_exists", "(", "'ReflectionClass'", ",", "'iscloneable'", ")", ")", "{", "$", "ref", "=", "new", "ReflectionClass", "(", "$", "arg", ")", ";", "if", "(", "$", "ref", "->", "iscloneable", "(", ")", ")", "{", "$", "arg", "=", "clone", "(", "$", "arg", ")", ";", "$", "cast", "=", "is_a", "(", "$", "arg", ",", "'IteratorAggregate'", ")", "?", "iterator_to_array", "(", "$", "arg", ")", ":", "get_object_vars", "(", "$", "arg", ")", ";", "foreach", "(", "$", "cast", "as", "$", "key", "=>", "$", "val", ")", "$", "arg", "->", "$", "key", "=", "$", "this", "->", "recursive", "(", "$", "val", ",", "$", "func", ",", "array_merge", "(", "$", "stack", ",", "array", "(", "$", "arg", ")", ")", ")", ";", "}", "}", "return", "$", "arg", ";", "case", "'array'", ":", "$", "copy", "=", "array", "(", ")", ";", "foreach", "(", "$", "arg", "as", "$", "key", "=>", "$", "val", ")", "$", "copy", "[", "$", "key", "]", "=", "$", "this", "->", "recursive", "(", "$", "val", ",", "$", "func", ",", "array_merge", "(", "$", "stack", ",", "array", "(", "$", "arg", ")", ")", ")", ";", "return", "$", "copy", ";", "}", "return", "$", "func", "(", "$", "arg", ")", ";", "}" ]
Invoke callback recursively for all data types @return mixed @param $arg mixed @param $func callback @param $stack array
[ "Invoke", "callback", "recursively", "for", "all", "data", "types" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L885-L915
eghojansu/moe
src/Base.php
Base.clean
function clean($arg,$tags=NULL) { $fw=$this; return $this->recursive($arg, function($val) use($fw,$tags) { if ($tags!='*') $val=trim(strip_tags($val, '<'.implode('><',$fw->split($tags)).'>')); return trim(preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/','',$val)); } ); }
php
function clean($arg,$tags=NULL) { $fw=$this; return $this->recursive($arg, function($val) use($fw,$tags) { if ($tags!='*') $val=trim(strip_tags($val, '<'.implode('><',$fw->split($tags)).'>')); return trim(preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/','',$val)); } ); }
[ "function", "clean", "(", "$", "arg", ",", "$", "tags", "=", "NULL", ")", "{", "$", "fw", "=", "$", "this", ";", "return", "$", "this", "->", "recursive", "(", "$", "arg", ",", "function", "(", "$", "val", ")", "use", "(", "$", "fw", ",", "$", "tags", ")", "{", "if", "(", "$", "tags", "!=", "'*'", ")", "$", "val", "=", "trim", "(", "strip_tags", "(", "$", "val", ",", "'<'", ".", "implode", "(", "'><'", ",", "$", "fw", "->", "split", "(", "$", "tags", ")", ")", ".", "'>'", ")", ")", ";", "return", "trim", "(", "preg_replace", "(", "'/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/'", ",", "''", ",", "$", "val", ")", ")", ";", "}", ")", ";", "}" ]
Remove HTML tags (except those enumerated) and non-printable characters to mitigate XSS/code injection attacks @return mixed @param $arg mixed @param $tags string
[ "Remove", "HTML", "tags", "(", "except", "those", "enumerated", ")", "and", "non", "-", "printable", "characters", "to", "mitigate", "XSS", "/", "code", "injection", "attacks" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L924-L935
eghojansu/moe
src/Base.php
Base.format
function format() { $args=func_get_args(); $val=array_shift($args); // Get formatting rules $conv=localeconv(); return preg_replace_callback( '/\{(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'. '(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?)?)*)'. '(?:,\s*(?P<prop>.+?))?)?)?\}/', function($expr) use($args,$conv) { extract($expr); extract($conv); if (!array_key_exists($pos,$args)) return $expr[0]; if (isset($type)) switch ($type) { case 'plural': preg_match_all('/(?<tag>\w+)'. '(?:\s*\{\s*(?<data>.+?)\s*\})/', $mod,$matches,PREG_SET_ORDER); $ord=array('zero','one','two'); foreach ($matches as $match) { extract($match); if (isset($ord[$args[$pos]]) && $tag==$ord[$args[$pos]] || $tag=='other') return str_replace('#',$args[$pos],$data); } case 'number': if (isset($mod)) switch ($mod) { case 'integer': return number_format( $args[$pos],0,'',$thousands_sep); case 'currency': if (function_exists('money_format')) return money_format( '%n',$args[$pos]); $fmt=array( 0=>'(nc)',1=>'(n c)', 2=>'(nc)',10=>'+nc', 11=>'+n c',12=>'+ nc', 20=>'nc+',21=>'n c+', 22=>'nc +',30=>'n+c', 31=>'n +c',32=>'n+ c', 40=>'nc+',41=>'n c+', 42=>'nc +',100=>'(cn)', 101=>'(c n)',102=>'(cn)', 110=>'+cn',111=>'+c n', 112=>'+ cn',120=>'cn+', 121=>'c n+',122=>'cn +', 130=>'+cn',131=>'+c n', 132=>'+ cn',140=>'c+n', 141=>'c+ n',142=>'c +n' ); if ($args[$pos]<0) { $sgn=$negative_sign; $pre='n'; } else { $sgn=$positive_sign; $pre='p'; } return str_replace( array('+','n','c'), array($sgn,number_format( abs($args[$pos]), $frac_digits, $decimal_point, $thousands_sep), $currency_symbol), $fmt[(int)( (${$pre.'_cs_precedes'}%2). (${$pre.'_sign_posn'}%5). (${$pre.'_sep_by_space'}%3) )] ); case 'percent': return number_format( $args[$pos]*100,0,$decimal_point, $thousands_sep).'%'; case 'decimal': return number_format( $args[$pos],$prop,$decimal_point, $thousands_sep); } break; case 'date': if (empty($mod) || $mod=='short') $prop='%x'; elseif ($mod=='long') $prop='%A, %d %B %Y'; return strftime($prop,$args[$pos]); case 'time': if (empty($mod) || $mod=='short') $prop='%X'; return strftime($prop,$args[$pos]); default: return $expr[0]; } return $args[$pos]; }, $val ); }
php
function format() { $args=func_get_args(); $val=array_shift($args); // Get formatting rules $conv=localeconv(); return preg_replace_callback( '/\{(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'. '(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?)?)*)'. '(?:,\s*(?P<prop>.+?))?)?)?\}/', function($expr) use($args,$conv) { extract($expr); extract($conv); if (!array_key_exists($pos,$args)) return $expr[0]; if (isset($type)) switch ($type) { case 'plural': preg_match_all('/(?<tag>\w+)'. '(?:\s*\{\s*(?<data>.+?)\s*\})/', $mod,$matches,PREG_SET_ORDER); $ord=array('zero','one','two'); foreach ($matches as $match) { extract($match); if (isset($ord[$args[$pos]]) && $tag==$ord[$args[$pos]] || $tag=='other') return str_replace('#',$args[$pos],$data); } case 'number': if (isset($mod)) switch ($mod) { case 'integer': return number_format( $args[$pos],0,'',$thousands_sep); case 'currency': if (function_exists('money_format')) return money_format( '%n',$args[$pos]); $fmt=array( 0=>'(nc)',1=>'(n c)', 2=>'(nc)',10=>'+nc', 11=>'+n c',12=>'+ nc', 20=>'nc+',21=>'n c+', 22=>'nc +',30=>'n+c', 31=>'n +c',32=>'n+ c', 40=>'nc+',41=>'n c+', 42=>'nc +',100=>'(cn)', 101=>'(c n)',102=>'(cn)', 110=>'+cn',111=>'+c n', 112=>'+ cn',120=>'cn+', 121=>'c n+',122=>'cn +', 130=>'+cn',131=>'+c n', 132=>'+ cn',140=>'c+n', 141=>'c+ n',142=>'c +n' ); if ($args[$pos]<0) { $sgn=$negative_sign; $pre='n'; } else { $sgn=$positive_sign; $pre='p'; } return str_replace( array('+','n','c'), array($sgn,number_format( abs($args[$pos]), $frac_digits, $decimal_point, $thousands_sep), $currency_symbol), $fmt[(int)( (${$pre.'_cs_precedes'}%2). (${$pre.'_sign_posn'}%5). (${$pre.'_sep_by_space'}%3) )] ); case 'percent': return number_format( $args[$pos]*100,0,$decimal_point, $thousands_sep).'%'; case 'decimal': return number_format( $args[$pos],$prop,$decimal_point, $thousands_sep); } break; case 'date': if (empty($mod) || $mod=='short') $prop='%x'; elseif ($mod=='long') $prop='%A, %d %B %Y'; return strftime($prop,$args[$pos]); case 'time': if (empty($mod) || $mod=='short') $prop='%X'; return strftime($prop,$args[$pos]); default: return $expr[0]; } return $args[$pos]; }, $val ); }
[ "function", "format", "(", ")", "{", "$", "args", "=", "func_get_args", "(", ")", ";", "$", "val", "=", "array_shift", "(", "$", "args", ")", ";", "// Get formatting rules", "$", "conv", "=", "localeconv", "(", ")", ";", "return", "preg_replace_callback", "(", "'/\\{(?P<pos>\\d+)\\s*(?:,\\s*(?P<type>\\w+)\\s*'", ".", "'(?:,\\s*(?P<mod>(?:\\w+(?:\\s*\\{.+?\\}\\s*,?)?)*)'", ".", "'(?:,\\s*(?P<prop>.+?))?)?)?\\}/'", ",", "function", "(", "$", "expr", ")", "use", "(", "$", "args", ",", "$", "conv", ")", "{", "extract", "(", "$", "expr", ")", ";", "extract", "(", "$", "conv", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "pos", ",", "$", "args", ")", ")", "return", "$", "expr", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "type", ")", ")", "switch", "(", "$", "type", ")", "{", "case", "'plural'", ":", "preg_match_all", "(", "'/(?<tag>\\w+)'", ".", "'(?:\\s*\\{\\s*(?<data>.+?)\\s*\\})/'", ",", "$", "mod", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ";", "$", "ord", "=", "array", "(", "'zero'", ",", "'one'", ",", "'two'", ")", ";", "foreach", "(", "$", "matches", "as", "$", "match", ")", "{", "extract", "(", "$", "match", ")", ";", "if", "(", "isset", "(", "$", "ord", "[", "$", "args", "[", "$", "pos", "]", "]", ")", "&&", "$", "tag", "==", "$", "ord", "[", "$", "args", "[", "$", "pos", "]", "]", "||", "$", "tag", "==", "'other'", ")", "return", "str_replace", "(", "'#'", ",", "$", "args", "[", "$", "pos", "]", ",", "$", "data", ")", ";", "}", "case", "'number'", ":", "if", "(", "isset", "(", "$", "mod", ")", ")", "switch", "(", "$", "mod", ")", "{", "case", "'integer'", ":", "return", "number_format", "(", "$", "args", "[", "$", "pos", "]", ",", "0", ",", "''", ",", "$", "thousands_sep", ")", ";", "case", "'currency'", ":", "if", "(", "function_exists", "(", "'money_format'", ")", ")", "return", "money_format", "(", "'%n'", ",", "$", "args", "[", "$", "pos", "]", ")", ";", "$", "fmt", "=", "array", "(", "0", "=>", "'(nc)'", ",", "1", "=>", "'(n c)'", ",", "2", "=>", "'(nc)'", ",", "10", "=>", "'+nc'", ",", "11", "=>", "'+n c'", ",", "12", "=>", "'+ nc'", ",", "20", "=>", "'nc+'", ",", "21", "=>", "'n c+'", ",", "22", "=>", "'nc +'", ",", "30", "=>", "'n+c'", ",", "31", "=>", "'n +c'", ",", "32", "=>", "'n+ c'", ",", "40", "=>", "'nc+'", ",", "41", "=>", "'n c+'", ",", "42", "=>", "'nc +'", ",", "100", "=>", "'(cn)'", ",", "101", "=>", "'(c n)'", ",", "102", "=>", "'(cn)'", ",", "110", "=>", "'+cn'", ",", "111", "=>", "'+c n'", ",", "112", "=>", "'+ cn'", ",", "120", "=>", "'cn+'", ",", "121", "=>", "'c n+'", ",", "122", "=>", "'cn +'", ",", "130", "=>", "'+cn'", ",", "131", "=>", "'+c n'", ",", "132", "=>", "'+ cn'", ",", "140", "=>", "'c+n'", ",", "141", "=>", "'c+ n'", ",", "142", "=>", "'c +n'", ")", ";", "if", "(", "$", "args", "[", "$", "pos", "]", "<", "0", ")", "{", "$", "sgn", "=", "$", "negative_sign", ";", "$", "pre", "=", "'n'", ";", "}", "else", "{", "$", "sgn", "=", "$", "positive_sign", ";", "$", "pre", "=", "'p'", ";", "}", "return", "str_replace", "(", "array", "(", "'+'", ",", "'n'", ",", "'c'", ")", ",", "array", "(", "$", "sgn", ",", "number_format", "(", "abs", "(", "$", "args", "[", "$", "pos", "]", ")", ",", "$", "frac_digits", ",", "$", "decimal_point", ",", "$", "thousands_sep", ")", ",", "$", "currency_symbol", ")", ",", "$", "fmt", "[", "(", "int", ")", "(", "(", "$", "{", "$", "pre", ".", "'_cs_precedes'", "}", "%", "2", ")", ".", "(", "$", "{", "$", "pre", ".", "'_sign_posn'", "}", "%", "5", ")", ".", "(", "$", "{", "$", "pre", ".", "'_sep_by_space'", "}", "%", "3", ")", ")", "]", ")", ";", "case", "'percent'", ":", "return", "number_format", "(", "$", "args", "[", "$", "pos", "]", "*", "100", ",", "0", ",", "$", "decimal_point", ",", "$", "thousands_sep", ")", ".", "'%'", ";", "case", "'decimal'", ":", "return", "number_format", "(", "$", "args", "[", "$", "pos", "]", ",", "$", "prop", ",", "$", "decimal_point", ",", "$", "thousands_sep", ")", ";", "}", "break", ";", "case", "'date'", ":", "if", "(", "empty", "(", "$", "mod", ")", "||", "$", "mod", "==", "'short'", ")", "$", "prop", "=", "'%x'", ";", "elseif", "(", "$", "mod", "==", "'long'", ")", "$", "prop", "=", "'%A, %d %B %Y'", ";", "return", "strftime", "(", "$", "prop", ",", "$", "args", "[", "$", "pos", "]", ")", ";", "case", "'time'", ":", "if", "(", "empty", "(", "$", "mod", ")", "||", "$", "mod", "==", "'short'", ")", "$", "prop", "=", "'%X'", ";", "return", "strftime", "(", "$", "prop", ",", "$", "args", "[", "$", "pos", "]", ")", ";", "default", ":", "return", "$", "expr", "[", "0", "]", ";", "}", "return", "$", "args", "[", "$", "pos", "]", ";", "}", ",", "$", "val", ")", ";", "}" ]
Return locale-aware formatted string @return string
[ "Return", "locale", "-", "aware", "formatted", "string" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L951-L1054
eghojansu/moe
src/Base.php
Base.lexicon
function lexicon($path) { $lex=array(); foreach ($this->languages?:explode(',',$this->fallback) as $lang) foreach ($this->split($path) as $dir) if ((is_file($file=($base=$dir.$lang).'.php') || is_file($file=$base.'.php')) && is_array($dict=require($file))) $lex+=$dict; elseif (is_file($file=$base.'.ini')) { preg_match_all( '/(?<=^|\n)(?:'. '\[(?<prefix>.+?)\]|'. '(?<lval>[^\h\r\n;].*?)\h*=\h*'. '(?<rval>(?:\\\\\h*\r?\n|.+?)*)'. ')(?=\r?\n|$)/', $this->read($file),$matches,PREG_SET_ORDER); if ($matches) { $prefix=''; foreach ($matches as $match) if ($match['prefix']) $prefix=$match['prefix'].'.'; elseif (!array_key_exists( $key=$prefix.$match['lval'],$lex)) $lex[$key]=trim(preg_replace( '/\\\\\h*\r?\n/','',$match['rval'])); } } return $lex; }
php
function lexicon($path) { $lex=array(); foreach ($this->languages?:explode(',',$this->fallback) as $lang) foreach ($this->split($path) as $dir) if ((is_file($file=($base=$dir.$lang).'.php') || is_file($file=$base.'.php')) && is_array($dict=require($file))) $lex+=$dict; elseif (is_file($file=$base.'.ini')) { preg_match_all( '/(?<=^|\n)(?:'. '\[(?<prefix>.+?)\]|'. '(?<lval>[^\h\r\n;].*?)\h*=\h*'. '(?<rval>(?:\\\\\h*\r?\n|.+?)*)'. ')(?=\r?\n|$)/', $this->read($file),$matches,PREG_SET_ORDER); if ($matches) { $prefix=''; foreach ($matches as $match) if ($match['prefix']) $prefix=$match['prefix'].'.'; elseif (!array_key_exists( $key=$prefix.$match['lval'],$lex)) $lex[$key]=trim(preg_replace( '/\\\\\h*\r?\n/','',$match['rval'])); } } return $lex; }
[ "function", "lexicon", "(", "$", "path", ")", "{", "$", "lex", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "languages", "?", ":", "explode", "(", "','", ",", "$", "this", "->", "fallback", ")", "as", "$", "lang", ")", "foreach", "(", "$", "this", "->", "split", "(", "$", "path", ")", "as", "$", "dir", ")", "if", "(", "(", "is_file", "(", "$", "file", "=", "(", "$", "base", "=", "$", "dir", ".", "$", "lang", ")", ".", "'.php'", ")", "||", "is_file", "(", "$", "file", "=", "$", "base", ".", "'.php'", ")", ")", "&&", "is_array", "(", "$", "dict", "=", "require", "(", "$", "file", ")", ")", ")", "$", "lex", "+=", "$", "dict", ";", "elseif", "(", "is_file", "(", "$", "file", "=", "$", "base", ".", "'.ini'", ")", ")", "{", "preg_match_all", "(", "'/(?<=^|\\n)(?:'", ".", "'\\[(?<prefix>.+?)\\]|'", ".", "'(?<lval>[^\\h\\r\\n;].*?)\\h*=\\h*'", ".", "'(?<rval>(?:\\\\\\\\\\h*\\r?\\n|.+?)*)'", ".", "')(?=\\r?\\n|$)/'", ",", "$", "this", "->", "read", "(", "$", "file", ")", ",", "$", "matches", ",", "PREG_SET_ORDER", ")", ";", "if", "(", "$", "matches", ")", "{", "$", "prefix", "=", "''", ";", "foreach", "(", "$", "matches", "as", "$", "match", ")", "if", "(", "$", "match", "[", "'prefix'", "]", ")", "$", "prefix", "=", "$", "match", "[", "'prefix'", "]", ".", "'.'", ";", "elseif", "(", "!", "array_key_exists", "(", "$", "key", "=", "$", "prefix", ".", "$", "match", "[", "'lval'", "]", ",", "$", "lex", ")", ")", "$", "lex", "[", "$", "key", "]", "=", "trim", "(", "preg_replace", "(", "'/\\\\\\\\\\h*\\r?\\n/'", ",", "''", ",", "$", "match", "[", "'rval'", "]", ")", ")", ";", "}", "}", "return", "$", "lex", ";", "}" ]
Return lexicon entries @return array @param $path string
[ "Return", "lexicon", "entries" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1099-L1127
eghojansu/moe
src/Base.php
Base.status
function status($code) { $reason=@constant('self::HTTP_'.$code); if (PHP_SAPI!='cli') header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$reason); return $reason; }
php
function status($code) { $reason=@constant('self::HTTP_'.$code); if (PHP_SAPI!='cli') header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$reason); return $reason; }
[ "function", "status", "(", "$", "code", ")", "{", "$", "reason", "=", "@", "constant", "(", "'self::HTTP_'", ".", "$", "code", ")", ";", "if", "(", "PHP_SAPI", "!=", "'cli'", ")", "header", "(", "$", "_SERVER", "[", "'SERVER_PROTOCOL'", "]", ".", "' '", ".", "$", "code", ".", "' '", ".", "$", "reason", ")", ";", "return", "$", "reason", ";", "}" ]
Send HTTP status header; Return text equivalent of status code @return string @param $code int
[ "Send", "HTTP", "status", "header", ";", "Return", "text", "equivalent", "of", "status", "code" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1162-L1167
eghojansu/moe
src/Base.php
Base.expire
function expire($secs=0) { if (PHP_SAPI!='cli') { header('X-Content-Type-Options: nosniff'); header('X-Frame-Options: '.$this->hive['XFRAME']); header('X-Powered-By: '.$this->hive['PACKAGE']); header('X-XSS-Protection: 1; mode=block'); if ($secs) { $time=microtime(TRUE); header_remove('Pragma'); header('Expires: '.gmdate('r',$time+$secs)); header('Cache-Control: max-age='.$secs); header('Last-Modified: '.gmdate('r')); } else header('Cache-Control: no-cache, no-store, must-revalidate'); } }
php
function expire($secs=0) { if (PHP_SAPI!='cli') { header('X-Content-Type-Options: nosniff'); header('X-Frame-Options: '.$this->hive['XFRAME']); header('X-Powered-By: '.$this->hive['PACKAGE']); header('X-XSS-Protection: 1; mode=block'); if ($secs) { $time=microtime(TRUE); header_remove('Pragma'); header('Expires: '.gmdate('r',$time+$secs)); header('Cache-Control: max-age='.$secs); header('Last-Modified: '.gmdate('r')); } else header('Cache-Control: no-cache, no-store, must-revalidate'); } }
[ "function", "expire", "(", "$", "secs", "=", "0", ")", "{", "if", "(", "PHP_SAPI", "!=", "'cli'", ")", "{", "header", "(", "'X-Content-Type-Options: nosniff'", ")", ";", "header", "(", "'X-Frame-Options: '", ".", "$", "this", "->", "hive", "[", "'XFRAME'", "]", ")", ";", "header", "(", "'X-Powered-By: '", ".", "$", "this", "->", "hive", "[", "'PACKAGE'", "]", ")", ";", "header", "(", "'X-XSS-Protection: 1; mode=block'", ")", ";", "if", "(", "$", "secs", ")", "{", "$", "time", "=", "microtime", "(", "TRUE", ")", ";", "header_remove", "(", "'Pragma'", ")", ";", "header", "(", "'Expires: '", ".", "gmdate", "(", "'r'", ",", "$", "time", "+", "$", "secs", ")", ")", ";", "header", "(", "'Cache-Control: max-age='", ".", "$", "secs", ")", ";", "header", "(", "'Last-Modified: '", ".", "gmdate", "(", "'r'", ")", ")", ";", "}", "else", "header", "(", "'Cache-Control: no-cache, no-store, must-revalidate'", ")", ";", "}", "}" ]
Send cache metadata to HTTP client @return NULL @param $secs int
[ "Send", "cache", "metadata", "to", "HTTP", "client" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1174-L1190
eghojansu/moe
src/Base.php
Base.error
function error($code,$text='',array $trace=NULL) { $prior=$this->hive['ERROR']; $header=$this->status($code); $req=$this->hive['VERB'].' '.$this->hive['PATH']; if (!$text) $text='HTTP '.$code.' ('.$req.')'; $logger = new Log($this->hive['ERROR_LOG']); $logger->write($text); $trace=$this->trace($trace); foreach (explode("\n",$trace) as $nexus) if ($nexus) $logger->write($nexus); unset($logger); if ($highlight=PHP_SAPI!='cli' && !$this->hive['AJAX'] && $this->hive['HIGHLIGHT'] && is_file($css=$this->hive['ERROR_TEMPLATE']['CSS'])) $trace=$this->highlight($trace); $this->hive['ERROR']=array( 'status'=>$header, 'code'=>$code, 'text'=>$text, 'trace'=>$trace ); $handler=$this->hive['ONERROR']; $this->hive['ONERROR']=NULL; if ((!$handler || $this->call($handler,array($this,$this->hive['PARAMS']), 'beforeroute,afterroute')===FALSE) && !$prior && PHP_SAPI!='cli' && !$this->hive['QUIET']) if ($this->hive['AJAX']) { echo json_encode($this->hive['ERROR']); } else { $views = $this->hive['ERROR_TEMPLATE']; isset($views['FALLBACK']) || user_error(self::E_fallback); $view = isset($views['E'.$code])?$views['E'.$code]:$views['FALLBACK']; $this->set('ASSETS.error.code', ($highlight?($this->read($css)):'')); !(is_file($css=$this->hive['ERROR_TEMPLATE']['CSS_LAYOUT'])) || $this->set('ASSETS.error.layout', $this->read($css)); $this->concat('UI', ';'.$this->fixslashes(__DIR__).'/'); echo Silet::instance()->render($view); } if ($this->hive['HALT']) die; }
php
function error($code,$text='',array $trace=NULL) { $prior=$this->hive['ERROR']; $header=$this->status($code); $req=$this->hive['VERB'].' '.$this->hive['PATH']; if (!$text) $text='HTTP '.$code.' ('.$req.')'; $logger = new Log($this->hive['ERROR_LOG']); $logger->write($text); $trace=$this->trace($trace); foreach (explode("\n",$trace) as $nexus) if ($nexus) $logger->write($nexus); unset($logger); if ($highlight=PHP_SAPI!='cli' && !$this->hive['AJAX'] && $this->hive['HIGHLIGHT'] && is_file($css=$this->hive['ERROR_TEMPLATE']['CSS'])) $trace=$this->highlight($trace); $this->hive['ERROR']=array( 'status'=>$header, 'code'=>$code, 'text'=>$text, 'trace'=>$trace ); $handler=$this->hive['ONERROR']; $this->hive['ONERROR']=NULL; if ((!$handler || $this->call($handler,array($this,$this->hive['PARAMS']), 'beforeroute,afterroute')===FALSE) && !$prior && PHP_SAPI!='cli' && !$this->hive['QUIET']) if ($this->hive['AJAX']) { echo json_encode($this->hive['ERROR']); } else { $views = $this->hive['ERROR_TEMPLATE']; isset($views['FALLBACK']) || user_error(self::E_fallback); $view = isset($views['E'.$code])?$views['E'.$code]:$views['FALLBACK']; $this->set('ASSETS.error.code', ($highlight?($this->read($css)):'')); !(is_file($css=$this->hive['ERROR_TEMPLATE']['CSS_LAYOUT'])) || $this->set('ASSETS.error.layout', $this->read($css)); $this->concat('UI', ';'.$this->fixslashes(__DIR__).'/'); echo Silet::instance()->render($view); } if ($this->hive['HALT']) die; }
[ "function", "error", "(", "$", "code", ",", "$", "text", "=", "''", ",", "array", "$", "trace", "=", "NULL", ")", "{", "$", "prior", "=", "$", "this", "->", "hive", "[", "'ERROR'", "]", ";", "$", "header", "=", "$", "this", "->", "status", "(", "$", "code", ")", ";", "$", "req", "=", "$", "this", "->", "hive", "[", "'VERB'", "]", ".", "' '", ".", "$", "this", "->", "hive", "[", "'PATH'", "]", ";", "if", "(", "!", "$", "text", ")", "$", "text", "=", "'HTTP '", ".", "$", "code", ".", "' ('", ".", "$", "req", ".", "')'", ";", "$", "logger", "=", "new", "Log", "(", "$", "this", "->", "hive", "[", "'ERROR_LOG'", "]", ")", ";", "$", "logger", "->", "write", "(", "$", "text", ")", ";", "$", "trace", "=", "$", "this", "->", "trace", "(", "$", "trace", ")", ";", "foreach", "(", "explode", "(", "\"\\n\"", ",", "$", "trace", ")", "as", "$", "nexus", ")", "if", "(", "$", "nexus", ")", "$", "logger", "->", "write", "(", "$", "nexus", ")", ";", "unset", "(", "$", "logger", ")", ";", "if", "(", "$", "highlight", "=", "PHP_SAPI", "!=", "'cli'", "&&", "!", "$", "this", "->", "hive", "[", "'AJAX'", "]", "&&", "$", "this", "->", "hive", "[", "'HIGHLIGHT'", "]", "&&", "is_file", "(", "$", "css", "=", "$", "this", "->", "hive", "[", "'ERROR_TEMPLATE'", "]", "[", "'CSS'", "]", ")", ")", "$", "trace", "=", "$", "this", "->", "highlight", "(", "$", "trace", ")", ";", "$", "this", "->", "hive", "[", "'ERROR'", "]", "=", "array", "(", "'status'", "=>", "$", "header", ",", "'code'", "=>", "$", "code", ",", "'text'", "=>", "$", "text", ",", "'trace'", "=>", "$", "trace", ")", ";", "$", "handler", "=", "$", "this", "->", "hive", "[", "'ONERROR'", "]", ";", "$", "this", "->", "hive", "[", "'ONERROR'", "]", "=", "NULL", ";", "if", "(", "(", "!", "$", "handler", "||", "$", "this", "->", "call", "(", "$", "handler", ",", "array", "(", "$", "this", ",", "$", "this", "->", "hive", "[", "'PARAMS'", "]", ")", ",", "'beforeroute,afterroute'", ")", "===", "FALSE", ")", "&&", "!", "$", "prior", "&&", "PHP_SAPI", "!=", "'cli'", "&&", "!", "$", "this", "->", "hive", "[", "'QUIET'", "]", ")", "if", "(", "$", "this", "->", "hive", "[", "'AJAX'", "]", ")", "{", "echo", "json_encode", "(", "$", "this", "->", "hive", "[", "'ERROR'", "]", ")", ";", "}", "else", "{", "$", "views", "=", "$", "this", "->", "hive", "[", "'ERROR_TEMPLATE'", "]", ";", "isset", "(", "$", "views", "[", "'FALLBACK'", "]", ")", "||", "user_error", "(", "self", "::", "E_fallback", ")", ";", "$", "view", "=", "isset", "(", "$", "views", "[", "'E'", ".", "$", "code", "]", ")", "?", "$", "views", "[", "'E'", ".", "$", "code", "]", ":", "$", "views", "[", "'FALLBACK'", "]", ";", "$", "this", "->", "set", "(", "'ASSETS.error.code'", ",", "(", "$", "highlight", "?", "(", "$", "this", "->", "read", "(", "$", "css", ")", ")", ":", "''", ")", ")", ";", "!", "(", "is_file", "(", "$", "css", "=", "$", "this", "->", "hive", "[", "'ERROR_TEMPLATE'", "]", "[", "'CSS_LAYOUT'", "]", ")", ")", "||", "$", "this", "->", "set", "(", "'ASSETS.error.layout'", ",", "$", "this", "->", "read", "(", "$", "css", ")", ")", ";", "$", "this", "->", "concat", "(", "'UI'", ",", "';'", ".", "$", "this", "->", "fixslashes", "(", "__DIR__", ")", ".", "'/'", ")", ";", "echo", "Silet", "::", "instance", "(", ")", "->", "render", "(", "$", "view", ")", ";", "}", "if", "(", "$", "this", "->", "hive", "[", "'HALT'", "]", ")", "die", ";", "}" ]
Log error; Execute ONERROR handler if defined, else display default error page (HTML for synchronous requests, JSON string for AJAX requests) @return NULL @param $code int @param $text string @param $trace array
[ "Log", "error", ";", "Execute", "ONERROR", "handler", "if", "defined", "else", "display", "default", "error", "page", "(", "HTML", "for", "synchronous", "requests", "JSON", "string", "for", "AJAX", "requests", ")" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1288-L1330
eghojansu/moe
src/Base.php
Base.reroute
function reroute($url=NULL,$permanent=FALSE) { if (!$url) $url=$this->hive['REALM']; if (preg_match('/^(?:@(\w+)(?:(\(.+?)\))*)/',$url,$parts)) { if (empty($this->hive['ALIASES'][$parts[1]])) user_error(sprintf(self::E_Named,$parts[1]),E_USER_ERROR); $url=$this->hive['ALIASES'][$parts[1]]; } $url=$this->build($url, isset($parts[2])?$this->parse($parts[2]):array()); if (($handler=$this->hive['ONREROUTE']) && $this->call($handler,array($url,$permanent))!==FALSE) return; if ($url[0]=='/') $url=$this->hive['BASE'].$url; if (PHP_SAPI!='cli') { header('Location: '.$url); $this->status($permanent?301:302); die; } $this->mock('GET '.$url); }
php
function reroute($url=NULL,$permanent=FALSE) { if (!$url) $url=$this->hive['REALM']; if (preg_match('/^(?:@(\w+)(?:(\(.+?)\))*)/',$url,$parts)) { if (empty($this->hive['ALIASES'][$parts[1]])) user_error(sprintf(self::E_Named,$parts[1]),E_USER_ERROR); $url=$this->hive['ALIASES'][$parts[1]]; } $url=$this->build($url, isset($parts[2])?$this->parse($parts[2]):array()); if (($handler=$this->hive['ONREROUTE']) && $this->call($handler,array($url,$permanent))!==FALSE) return; if ($url[0]=='/') $url=$this->hive['BASE'].$url; if (PHP_SAPI!='cli') { header('Location: '.$url); $this->status($permanent?301:302); die; } $this->mock('GET '.$url); }
[ "function", "reroute", "(", "$", "url", "=", "NULL", ",", "$", "permanent", "=", "FALSE", ")", "{", "if", "(", "!", "$", "url", ")", "$", "url", "=", "$", "this", "->", "hive", "[", "'REALM'", "]", ";", "if", "(", "preg_match", "(", "'/^(?:@(\\w+)(?:(\\(.+?)\\))*)/'", ",", "$", "url", ",", "$", "parts", ")", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "hive", "[", "'ALIASES'", "]", "[", "$", "parts", "[", "1", "]", "]", ")", ")", "user_error", "(", "sprintf", "(", "self", "::", "E_Named", ",", "$", "parts", "[", "1", "]", ")", ",", "E_USER_ERROR", ")", ";", "$", "url", "=", "$", "this", "->", "hive", "[", "'ALIASES'", "]", "[", "$", "parts", "[", "1", "]", "]", ";", "}", "$", "url", "=", "$", "this", "->", "build", "(", "$", "url", ",", "isset", "(", "$", "parts", "[", "2", "]", ")", "?", "$", "this", "->", "parse", "(", "$", "parts", "[", "2", "]", ")", ":", "array", "(", ")", ")", ";", "if", "(", "(", "$", "handler", "=", "$", "this", "->", "hive", "[", "'ONREROUTE'", "]", ")", "&&", "$", "this", "->", "call", "(", "$", "handler", ",", "array", "(", "$", "url", ",", "$", "permanent", ")", ")", "!==", "FALSE", ")", "return", ";", "if", "(", "$", "url", "[", "0", "]", "==", "'/'", ")", "$", "url", "=", "$", "this", "->", "hive", "[", "'BASE'", "]", ".", "$", "url", ";", "if", "(", "PHP_SAPI", "!=", "'cli'", ")", "{", "header", "(", "'Location: '", ".", "$", "url", ")", ";", "$", "this", "->", "status", "(", "$", "permanent", "?", "301", ":", "302", ")", ";", "die", ";", "}", "$", "this", "->", "mock", "(", "'GET '", ".", "$", "url", ")", ";", "}" ]
Reroute to specified URI @return NULL @param $url string @param $permanent bool
[ "Reroute", "to", "specified", "URI" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1421-L1442
eghojansu/moe
src/Base.php
Base.map
function map($url,$class,$ttl=0,$kbps=0) { if (is_array($url)) { foreach ($url as $item) $this->map($item,$class,$ttl,$kbps); return; } foreach (explode('|',self::VERBS) as $method) $this->route($method.' '.$url,is_string($class)? $class.'->'.$this->hive['PREMAP'].strtolower($method): array($class,$this->hive['PREMAP'].strtolower($method)), $ttl,$kbps); }
php
function map($url,$class,$ttl=0,$kbps=0) { if (is_array($url)) { foreach ($url as $item) $this->map($item,$class,$ttl,$kbps); return; } foreach (explode('|',self::VERBS) as $method) $this->route($method.' '.$url,is_string($class)? $class.'->'.$this->hive['PREMAP'].strtolower($method): array($class,$this->hive['PREMAP'].strtolower($method)), $ttl,$kbps); }
[ "function", "map", "(", "$", "url", ",", "$", "class", ",", "$", "ttl", "=", "0", ",", "$", "kbps", "=", "0", ")", "{", "if", "(", "is_array", "(", "$", "url", ")", ")", "{", "foreach", "(", "$", "url", "as", "$", "item", ")", "$", "this", "->", "map", "(", "$", "item", ",", "$", "class", ",", "$", "ttl", ",", "$", "kbps", ")", ";", "return", ";", "}", "foreach", "(", "explode", "(", "'|'", ",", "self", "::", "VERBS", ")", "as", "$", "method", ")", "$", "this", "->", "route", "(", "$", "method", ".", "' '", ".", "$", "url", ",", "is_string", "(", "$", "class", ")", "?", "$", "class", ".", "'->'", ".", "$", "this", "->", "hive", "[", "'PREMAP'", "]", ".", "strtolower", "(", "$", "method", ")", ":", "array", "(", "$", "class", ",", "$", "this", "->", "hive", "[", "'PREMAP'", "]", ".", "strtolower", "(", "$", "method", ")", ")", ",", "$", "ttl", ",", "$", "kbps", ")", ";", "}" ]
Provide ReST interface by mapping HTTP verb to class method @return NULL @param $url string @param $class string|object @param $ttl int @param $kbps int
[ "Provide", "ReST", "interface", "by", "mapping", "HTTP", "verb", "to", "class", "method" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1452-L1463
eghojansu/moe
src/Base.php
Base.mask
function mask($pattern,$url=NULL) { if (!$url) $url=$this->rel($this->hive['URI']); $case=$this->hive['CASELESS']?'i':''; preg_match('/^'. preg_replace('/@(\w+\b)/','(?P<\1>[^\/\?]+)', str_replace('\*','([^\?]+)',preg_quote($pattern,'/'))). '\/?(?:\?.*)?$/'.$case.'um',$url,$args); return $args; }
php
function mask($pattern,$url=NULL) { if (!$url) $url=$this->rel($this->hive['URI']); $case=$this->hive['CASELESS']?'i':''; preg_match('/^'. preg_replace('/@(\w+\b)/','(?P<\1>[^\/\?]+)', str_replace('\*','([^\?]+)',preg_quote($pattern,'/'))). '\/?(?:\?.*)?$/'.$case.'um',$url,$args); return $args; }
[ "function", "mask", "(", "$", "pattern", ",", "$", "url", "=", "NULL", ")", "{", "if", "(", "!", "$", "url", ")", "$", "url", "=", "$", "this", "->", "rel", "(", "$", "this", "->", "hive", "[", "'URI'", "]", ")", ";", "$", "case", "=", "$", "this", "->", "hive", "[", "'CASELESS'", "]", "?", "'i'", ":", "''", ";", "preg_match", "(", "'/^'", ".", "preg_replace", "(", "'/@(\\w+\\b)/'", ",", "'(?P<\\1>[^\\/\\?]+)'", ",", "str_replace", "(", "'\\*'", ",", "'([^\\?]+)'", ",", "preg_quote", "(", "$", "pattern", ",", "'/'", ")", ")", ")", ".", "'\\/?(?:\\?.*)?$/'", ".", "$", "case", ".", "'um'", ",", "$", "url", ",", "$", "args", ")", ";", "return", "$", "args", ";", "}" ]
Applies the specified URL mask and returns parameterized matches @return $args array @param $pattern string @param $url string|NULL
[ "Applies", "the", "specified", "URL", "mask", "and", "returns", "parameterized", "matches" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1512-L1521
eghojansu/moe
src/Base.php
Base.run
function run() { if ($this->blacklisted($this->hive['IP'])) // Spammer detected $this->error(403); if (!$this->hive['ROUTES']) // No routes defined user_error(self::E_Routes,E_USER_ERROR); // Match specific routes first $paths=array(); foreach ($keys=array_keys($this->hive['ROUTES']) as $key) $paths[]=str_replace('@','*@',$key); $vals=array_values($this->hive['ROUTES']); array_multisort($paths,SORT_DESC,$keys,$vals); $this->hive['ROUTES']=array_combine($keys,$vals); // Convert to BASE-relative URL $req=$this->rel($this->hive['URI']); if ($cors=(isset($this->hive['HEADERS']['Origin']) && $this->hive['CORS']['origin'])) { $cors=$this->hive['CORS']; header('Access-Control-Allow-Origin: '.$cors['origin']); header('Access-Control-Allow-Credentials: '. ($cors['credentials']?'true':'false')); } $allowed=array(); foreach ($this->hive['ROUTES'] as $pattern=>$routes) { if (!$args=$this->mask($pattern,$req)) continue; ksort($args); $route=NULL; if (isset( $routes[$ptr=$this->hive['AJAX']+1][$this->hive['VERB']])) $route=$routes[$ptr]; elseif (isset($routes[self::REQ_SYNC|self::REQ_AJAX])) $route=$routes[self::REQ_SYNC|self::REQ_AJAX]; if (!$route) continue; if ($this->hive['VERB']!='OPTIONS' && isset($route[$this->hive['VERB']])) { $parts=parse_url($req); if ($this->hive['VERB']=='GET' && preg_match('/.+\/$/',$parts['path'])) $this->reroute(substr($parts['path'],0,-1). (isset($parts['query'])?('?'.$parts['query']):'')); list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']]; if (is_bool(strpos($pattern,'/*'))) foreach (array_keys($args) as $key) if (is_numeric($key) && $key) unset($args[$key]); // Capture values of route pattern tokens $this->hive['PARAMS']=$args=array_map('urldecode',$args); // Save matching route $this->hive['ALIAS']=$alias; $this->hive['PATTERN']=$pattern; if ($cors && $cors['expose']) header('Access-Control-Expose-Headers: '.(is_array($cors['expose'])? implode(',',$cors['expose']):$cors['expose'])); if (is_string($handler)) { // Replace route pattern tokens in handler if any $handler=preg_replace_callback('/@(\w+\b)/', function($id) use($args) { return isset($args[$id[1]])?$args[$id[1]]:$id[0]; }, $handler ); if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) && !class_exists($match[1])) $this->error(404); } // Process request $result=NULL; $body=''; $now=microtime(TRUE); if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) { // Only GET and HEAD requests are cacheable $headers=$this->hive['HEADERS']; $cache=Cache::instance(); $cached=$cache->exists( $hash=$this->hash($this->hive['VERB'].' '. $this->hive['URI']).'.url',$data); if ($cached && $cached[0]+$ttl>$now) { if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since'])+ $ttl>$now) { $this->status(304); die; } // Retrieve from cache backend list($headers,$body,$result)=$data; if (PHP_SAPI!='cli') array_walk($headers,'header'); $this->expire($cached[0]+$ttl-$now); } else // Expire HTTP client-cached page $this->expire($ttl); } else $this->expire(0); if (!strlen($body)) { if (!$this->hive['RAW'] && !$this->hive['BODY']) $this->hive['BODY']=file_get_contents('php://input'); ob_start(); // Call route handler $result=$this->call($handler,array($this, $args), 'beforeroute,afterroute'); $body=ob_get_clean(); // Template Parsing if ($this->hive['TEMPLATE']) { $this->hive['RESPONSE'] = $body; $body = $this->send($this->hive['TEMPLATE'], true); } if (isset($cache) && !error_get_last()) { // Save to cache backend $cache->set($hash,array( // Remove cookies preg_grep('/Set-Cookie\:/',headers_list(), PREG_GREP_INVERT),$body,$result),$ttl); } } $this->hive['RESPONSE']=$body; if (!$this->hive['QUIET']) { if ($kbps) { $ctr=0; foreach (str_split($body,1024) as $part) { // Throttle output $ctr++; if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) && !connection_aborted()) usleep(1e6*($ctr/$kbps-$elapsed)); echo $part; } } else echo $body; } return $result; } $allowed=array_merge($allowed,array_keys($route)); } if (!$allowed) // URL doesn't match any route $this->error(404); elseif (PHP_SAPI!='cli') { // Unhandled HTTP method header('Allow: '.implode(',',array_unique($allowed))); if ($cors) { header('Access-Control-Allow-Methods: OPTIONS,'.implode(',',$allowed)); if ($cors['headers']) header('Access-Control-Allow-Headers: '.(is_array($cors['headers'])? implode(',',$cors['headers']):$cors['headers'])); if ($cors['ttl']>0) header('Access-Control-Max-Age: '.$cors['ttl']); } if ($this->hive['VERB']!='OPTIONS') $this->error(405); } return FALSE; }
php
function run() { if ($this->blacklisted($this->hive['IP'])) // Spammer detected $this->error(403); if (!$this->hive['ROUTES']) // No routes defined user_error(self::E_Routes,E_USER_ERROR); // Match specific routes first $paths=array(); foreach ($keys=array_keys($this->hive['ROUTES']) as $key) $paths[]=str_replace('@','*@',$key); $vals=array_values($this->hive['ROUTES']); array_multisort($paths,SORT_DESC,$keys,$vals); $this->hive['ROUTES']=array_combine($keys,$vals); // Convert to BASE-relative URL $req=$this->rel($this->hive['URI']); if ($cors=(isset($this->hive['HEADERS']['Origin']) && $this->hive['CORS']['origin'])) { $cors=$this->hive['CORS']; header('Access-Control-Allow-Origin: '.$cors['origin']); header('Access-Control-Allow-Credentials: '. ($cors['credentials']?'true':'false')); } $allowed=array(); foreach ($this->hive['ROUTES'] as $pattern=>$routes) { if (!$args=$this->mask($pattern,$req)) continue; ksort($args); $route=NULL; if (isset( $routes[$ptr=$this->hive['AJAX']+1][$this->hive['VERB']])) $route=$routes[$ptr]; elseif (isset($routes[self::REQ_SYNC|self::REQ_AJAX])) $route=$routes[self::REQ_SYNC|self::REQ_AJAX]; if (!$route) continue; if ($this->hive['VERB']!='OPTIONS' && isset($route[$this->hive['VERB']])) { $parts=parse_url($req); if ($this->hive['VERB']=='GET' && preg_match('/.+\/$/',$parts['path'])) $this->reroute(substr($parts['path'],0,-1). (isset($parts['query'])?('?'.$parts['query']):'')); list($handler,$ttl,$kbps,$alias)=$route[$this->hive['VERB']]; if (is_bool(strpos($pattern,'/*'))) foreach (array_keys($args) as $key) if (is_numeric($key) && $key) unset($args[$key]); // Capture values of route pattern tokens $this->hive['PARAMS']=$args=array_map('urldecode',$args); // Save matching route $this->hive['ALIAS']=$alias; $this->hive['PATTERN']=$pattern; if ($cors && $cors['expose']) header('Access-Control-Expose-Headers: '.(is_array($cors['expose'])? implode(',',$cors['expose']):$cors['expose'])); if (is_string($handler)) { // Replace route pattern tokens in handler if any $handler=preg_replace_callback('/@(\w+\b)/', function($id) use($args) { return isset($args[$id[1]])?$args[$id[1]]:$id[0]; }, $handler ); if (preg_match('/(.+)\h*(?:->|::)/',$handler,$match) && !class_exists($match[1])) $this->error(404); } // Process request $result=NULL; $body=''; $now=microtime(TRUE); if (preg_match('/GET|HEAD/',$this->hive['VERB']) && $ttl) { // Only GET and HEAD requests are cacheable $headers=$this->hive['HEADERS']; $cache=Cache::instance(); $cached=$cache->exists( $hash=$this->hash($this->hive['VERB'].' '. $this->hive['URI']).'.url',$data); if ($cached && $cached[0]+$ttl>$now) { if (isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since'])+ $ttl>$now) { $this->status(304); die; } // Retrieve from cache backend list($headers,$body,$result)=$data; if (PHP_SAPI!='cli') array_walk($headers,'header'); $this->expire($cached[0]+$ttl-$now); } else // Expire HTTP client-cached page $this->expire($ttl); } else $this->expire(0); if (!strlen($body)) { if (!$this->hive['RAW'] && !$this->hive['BODY']) $this->hive['BODY']=file_get_contents('php://input'); ob_start(); // Call route handler $result=$this->call($handler,array($this, $args), 'beforeroute,afterroute'); $body=ob_get_clean(); // Template Parsing if ($this->hive['TEMPLATE']) { $this->hive['RESPONSE'] = $body; $body = $this->send($this->hive['TEMPLATE'], true); } if (isset($cache) && !error_get_last()) { // Save to cache backend $cache->set($hash,array( // Remove cookies preg_grep('/Set-Cookie\:/',headers_list(), PREG_GREP_INVERT),$body,$result),$ttl); } } $this->hive['RESPONSE']=$body; if (!$this->hive['QUIET']) { if ($kbps) { $ctr=0; foreach (str_split($body,1024) as $part) { // Throttle output $ctr++; if ($ctr/$kbps>($elapsed=microtime(TRUE)-$now) && !connection_aborted()) usleep(1e6*($ctr/$kbps-$elapsed)); echo $part; } } else echo $body; } return $result; } $allowed=array_merge($allowed,array_keys($route)); } if (!$allowed) // URL doesn't match any route $this->error(404); elseif (PHP_SAPI!='cli') { // Unhandled HTTP method header('Allow: '.implode(',',array_unique($allowed))); if ($cors) { header('Access-Control-Allow-Methods: OPTIONS,'.implode(',',$allowed)); if ($cors['headers']) header('Access-Control-Allow-Headers: '.(is_array($cors['headers'])? implode(',',$cors['headers']):$cors['headers'])); if ($cors['ttl']>0) header('Access-Control-Max-Age: '.$cors['ttl']); } if ($this->hive['VERB']!='OPTIONS') $this->error(405); } return FALSE; }
[ "function", "run", "(", ")", "{", "if", "(", "$", "this", "->", "blacklisted", "(", "$", "this", "->", "hive", "[", "'IP'", "]", ")", ")", "// Spammer detected", "$", "this", "->", "error", "(", "403", ")", ";", "if", "(", "!", "$", "this", "->", "hive", "[", "'ROUTES'", "]", ")", "// No routes defined", "user_error", "(", "self", "::", "E_Routes", ",", "E_USER_ERROR", ")", ";", "// Match specific routes first", "$", "paths", "=", "array", "(", ")", ";", "foreach", "(", "$", "keys", "=", "array_keys", "(", "$", "this", "->", "hive", "[", "'ROUTES'", "]", ")", "as", "$", "key", ")", "$", "paths", "[", "]", "=", "str_replace", "(", "'@'", ",", "'*@'", ",", "$", "key", ")", ";", "$", "vals", "=", "array_values", "(", "$", "this", "->", "hive", "[", "'ROUTES'", "]", ")", ";", "array_multisort", "(", "$", "paths", ",", "SORT_DESC", ",", "$", "keys", ",", "$", "vals", ")", ";", "$", "this", "->", "hive", "[", "'ROUTES'", "]", "=", "array_combine", "(", "$", "keys", ",", "$", "vals", ")", ";", "// Convert to BASE-relative URL", "$", "req", "=", "$", "this", "->", "rel", "(", "$", "this", "->", "hive", "[", "'URI'", "]", ")", ";", "if", "(", "$", "cors", "=", "(", "isset", "(", "$", "this", "->", "hive", "[", "'HEADERS'", "]", "[", "'Origin'", "]", ")", "&&", "$", "this", "->", "hive", "[", "'CORS'", "]", "[", "'origin'", "]", ")", ")", "{", "$", "cors", "=", "$", "this", "->", "hive", "[", "'CORS'", "]", ";", "header", "(", "'Access-Control-Allow-Origin: '", ".", "$", "cors", "[", "'origin'", "]", ")", ";", "header", "(", "'Access-Control-Allow-Credentials: '", ".", "(", "$", "cors", "[", "'credentials'", "]", "?", "'true'", ":", "'false'", ")", ")", ";", "}", "$", "allowed", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "hive", "[", "'ROUTES'", "]", "as", "$", "pattern", "=>", "$", "routes", ")", "{", "if", "(", "!", "$", "args", "=", "$", "this", "->", "mask", "(", "$", "pattern", ",", "$", "req", ")", ")", "continue", ";", "ksort", "(", "$", "args", ")", ";", "$", "route", "=", "NULL", ";", "if", "(", "isset", "(", "$", "routes", "[", "$", "ptr", "=", "$", "this", "->", "hive", "[", "'AJAX'", "]", "+", "1", "]", "[", "$", "this", "->", "hive", "[", "'VERB'", "]", "]", ")", ")", "$", "route", "=", "$", "routes", "[", "$", "ptr", "]", ";", "elseif", "(", "isset", "(", "$", "routes", "[", "self", "::", "REQ_SYNC", "|", "self", "::", "REQ_AJAX", "]", ")", ")", "$", "route", "=", "$", "routes", "[", "self", "::", "REQ_SYNC", "|", "self", "::", "REQ_AJAX", "]", ";", "if", "(", "!", "$", "route", ")", "continue", ";", "if", "(", "$", "this", "->", "hive", "[", "'VERB'", "]", "!=", "'OPTIONS'", "&&", "isset", "(", "$", "route", "[", "$", "this", "->", "hive", "[", "'VERB'", "]", "]", ")", ")", "{", "$", "parts", "=", "parse_url", "(", "$", "req", ")", ";", "if", "(", "$", "this", "->", "hive", "[", "'VERB'", "]", "==", "'GET'", "&&", "preg_match", "(", "'/.+\\/$/'", ",", "$", "parts", "[", "'path'", "]", ")", ")", "$", "this", "->", "reroute", "(", "substr", "(", "$", "parts", "[", "'path'", "]", ",", "0", ",", "-", "1", ")", ".", "(", "isset", "(", "$", "parts", "[", "'query'", "]", ")", "?", "(", "'?'", ".", "$", "parts", "[", "'query'", "]", ")", ":", "''", ")", ")", ";", "list", "(", "$", "handler", ",", "$", "ttl", ",", "$", "kbps", ",", "$", "alias", ")", "=", "$", "route", "[", "$", "this", "->", "hive", "[", "'VERB'", "]", "]", ";", "if", "(", "is_bool", "(", "strpos", "(", "$", "pattern", ",", "'/*'", ")", ")", ")", "foreach", "(", "array_keys", "(", "$", "args", ")", "as", "$", "key", ")", "if", "(", "is_numeric", "(", "$", "key", ")", "&&", "$", "key", ")", "unset", "(", "$", "args", "[", "$", "key", "]", ")", ";", "// Capture values of route pattern tokens", "$", "this", "->", "hive", "[", "'PARAMS'", "]", "=", "$", "args", "=", "array_map", "(", "'urldecode'", ",", "$", "args", ")", ";", "// Save matching route", "$", "this", "->", "hive", "[", "'ALIAS'", "]", "=", "$", "alias", ";", "$", "this", "->", "hive", "[", "'PATTERN'", "]", "=", "$", "pattern", ";", "if", "(", "$", "cors", "&&", "$", "cors", "[", "'expose'", "]", ")", "header", "(", "'Access-Control-Expose-Headers: '", ".", "(", "is_array", "(", "$", "cors", "[", "'expose'", "]", ")", "?", "implode", "(", "','", ",", "$", "cors", "[", "'expose'", "]", ")", ":", "$", "cors", "[", "'expose'", "]", ")", ")", ";", "if", "(", "is_string", "(", "$", "handler", ")", ")", "{", "// Replace route pattern tokens in handler if any", "$", "handler", "=", "preg_replace_callback", "(", "'/@(\\w+\\b)/'", ",", "function", "(", "$", "id", ")", "use", "(", "$", "args", ")", "{", "return", "isset", "(", "$", "args", "[", "$", "id", "[", "1", "]", "]", ")", "?", "$", "args", "[", "$", "id", "[", "1", "]", "]", ":", "$", "id", "[", "0", "]", ";", "}", ",", "$", "handler", ")", ";", "if", "(", "preg_match", "(", "'/(.+)\\h*(?:->|::)/'", ",", "$", "handler", ",", "$", "match", ")", "&&", "!", "class_exists", "(", "$", "match", "[", "1", "]", ")", ")", "$", "this", "->", "error", "(", "404", ")", ";", "}", "// Process request", "$", "result", "=", "NULL", ";", "$", "body", "=", "''", ";", "$", "now", "=", "microtime", "(", "TRUE", ")", ";", "if", "(", "preg_match", "(", "'/GET|HEAD/'", ",", "$", "this", "->", "hive", "[", "'VERB'", "]", ")", "&&", "$", "ttl", ")", "{", "// Only GET and HEAD requests are cacheable", "$", "headers", "=", "$", "this", "->", "hive", "[", "'HEADERS'", "]", ";", "$", "cache", "=", "Cache", "::", "instance", "(", ")", ";", "$", "cached", "=", "$", "cache", "->", "exists", "(", "$", "hash", "=", "$", "this", "->", "hash", "(", "$", "this", "->", "hive", "[", "'VERB'", "]", ".", "' '", ".", "$", "this", "->", "hive", "[", "'URI'", "]", ")", ".", "'.url'", ",", "$", "data", ")", ";", "if", "(", "$", "cached", "&&", "$", "cached", "[", "0", "]", "+", "$", "ttl", ">", "$", "now", ")", "{", "if", "(", "isset", "(", "$", "headers", "[", "'If-Modified-Since'", "]", ")", "&&", "strtotime", "(", "$", "headers", "[", "'If-Modified-Since'", "]", ")", "+", "$", "ttl", ">", "$", "now", ")", "{", "$", "this", "->", "status", "(", "304", ")", ";", "die", ";", "}", "// Retrieve from cache backend", "list", "(", "$", "headers", ",", "$", "body", ",", "$", "result", ")", "=", "$", "data", ";", "if", "(", "PHP_SAPI", "!=", "'cli'", ")", "array_walk", "(", "$", "headers", ",", "'header'", ")", ";", "$", "this", "->", "expire", "(", "$", "cached", "[", "0", "]", "+", "$", "ttl", "-", "$", "now", ")", ";", "}", "else", "// Expire HTTP client-cached page", "$", "this", "->", "expire", "(", "$", "ttl", ")", ";", "}", "else", "$", "this", "->", "expire", "(", "0", ")", ";", "if", "(", "!", "strlen", "(", "$", "body", ")", ")", "{", "if", "(", "!", "$", "this", "->", "hive", "[", "'RAW'", "]", "&&", "!", "$", "this", "->", "hive", "[", "'BODY'", "]", ")", "$", "this", "->", "hive", "[", "'BODY'", "]", "=", "file_get_contents", "(", "'php://input'", ")", ";", "ob_start", "(", ")", ";", "// Call route handler", "$", "result", "=", "$", "this", "->", "call", "(", "$", "handler", ",", "array", "(", "$", "this", ",", "$", "args", ")", ",", "'beforeroute,afterroute'", ")", ";", "$", "body", "=", "ob_get_clean", "(", ")", ";", "// Template Parsing", "if", "(", "$", "this", "->", "hive", "[", "'TEMPLATE'", "]", ")", "{", "$", "this", "->", "hive", "[", "'RESPONSE'", "]", "=", "$", "body", ";", "$", "body", "=", "$", "this", "->", "send", "(", "$", "this", "->", "hive", "[", "'TEMPLATE'", "]", ",", "true", ")", ";", "}", "if", "(", "isset", "(", "$", "cache", ")", "&&", "!", "error_get_last", "(", ")", ")", "{", "// Save to cache backend", "$", "cache", "->", "set", "(", "$", "hash", ",", "array", "(", "// Remove cookies", "preg_grep", "(", "'/Set-Cookie\\:/'", ",", "headers_list", "(", ")", ",", "PREG_GREP_INVERT", ")", ",", "$", "body", ",", "$", "result", ")", ",", "$", "ttl", ")", ";", "}", "}", "$", "this", "->", "hive", "[", "'RESPONSE'", "]", "=", "$", "body", ";", "if", "(", "!", "$", "this", "->", "hive", "[", "'QUIET'", "]", ")", "{", "if", "(", "$", "kbps", ")", "{", "$", "ctr", "=", "0", ";", "foreach", "(", "str_split", "(", "$", "body", ",", "1024", ")", "as", "$", "part", ")", "{", "// Throttle output", "$", "ctr", "++", ";", "if", "(", "$", "ctr", "/", "$", "kbps", ">", "(", "$", "elapsed", "=", "microtime", "(", "TRUE", ")", "-", "$", "now", ")", "&&", "!", "connection_aborted", "(", ")", ")", "usleep", "(", "1e6", "*", "(", "$", "ctr", "/", "$", "kbps", "-", "$", "elapsed", ")", ")", ";", "echo", "$", "part", ";", "}", "}", "else", "echo", "$", "body", ";", "}", "return", "$", "result", ";", "}", "$", "allowed", "=", "array_merge", "(", "$", "allowed", ",", "array_keys", "(", "$", "route", ")", ")", ";", "}", "if", "(", "!", "$", "allowed", ")", "// URL doesn't match any route", "$", "this", "->", "error", "(", "404", ")", ";", "elseif", "(", "PHP_SAPI", "!=", "'cli'", ")", "{", "// Unhandled HTTP method", "header", "(", "'Allow: '", ".", "implode", "(", "','", ",", "array_unique", "(", "$", "allowed", ")", ")", ")", ";", "if", "(", "$", "cors", ")", "{", "header", "(", "'Access-Control-Allow-Methods: OPTIONS,'", ".", "implode", "(", "','", ",", "$", "allowed", ")", ")", ";", "if", "(", "$", "cors", "[", "'headers'", "]", ")", "header", "(", "'Access-Control-Allow-Headers: '", ".", "(", "is_array", "(", "$", "cors", "[", "'headers'", "]", ")", "?", "implode", "(", "','", ",", "$", "cors", "[", "'headers'", "]", ")", ":", "$", "cors", "[", "'headers'", "]", ")", ")", ";", "if", "(", "$", "cors", "[", "'ttl'", "]", ">", "0", ")", "header", "(", "'Access-Control-Max-Age: '", ".", "$", "cors", "[", "'ttl'", "]", ")", ";", "}", "if", "(", "$", "this", "->", "hive", "[", "'VERB'", "]", "!=", "'OPTIONS'", ")", "$", "this", "->", "error", "(", "405", ")", ";", "}", "return", "FALSE", ";", "}" ]
Match routes against incoming URI @return mixed
[ "Match", "routes", "against", "incoming", "URI" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1527-L1684
eghojansu/moe
src/Base.php
Base.send
function send($object, $return = false) { if (is_array($object)) $this->sendJson($object); $content = Silet::instance()->render($object.( (strpos($object, '.')===false?'.silet':''))); if ($return) return $content; echo $content; }
php
function send($object, $return = false) { if (is_array($object)) $this->sendJson($object); $content = Silet::instance()->render($object.( (strpos($object, '.')===false?'.silet':''))); if ($return) return $content; echo $content; }
[ "function", "send", "(", "$", "object", ",", "$", "return", "=", "false", ")", "{", "if", "(", "is_array", "(", "$", "object", ")", ")", "$", "this", "->", "sendJson", "(", "$", "object", ")", ";", "$", "content", "=", "Silet", "::", "instance", "(", ")", "->", "render", "(", "$", "object", ".", "(", "(", "strpos", "(", "$", "object", ",", "'.'", ")", "===", "false", "?", "'.silet'", ":", "''", ")", ")", ")", ";", "if", "(", "$", "return", ")", "return", "$", "content", ";", "echo", "$", "content", ";", "}" ]
Send object view or array (as json) @param mixed $object String view or array @param boolean $return wether to return content or not @return string or nothing
[ "Send", "object", "view", "or", "array", "(", "as", "json", ")" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1692-L1703
eghojansu/moe
src/Base.php
Base.parseBody
function parseBody() { $result = array( 'data'=>array(), 'files'=>array(), ); // read incoming data $input = Instance::get('BODY'); // grab multipart boundary from content type header preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches); // content type is probably regular form-encoded if (!count($matches)) { // we expect regular puts to containt a query string containing data parse_str($input, $result['data']); } else { $boundary = $matches[1]; // split content by boundary and get rid of last -- element $a_blocks = preg_split("/-+$boundary/", $input); array_pop($a_blocks); // loop data blocks foreach ($a_blocks as $id => $block) { if (empty($block)) continue; // you'll have to var_dump $block to understand this and maybe replace \n or \r with a visibile char // parse uploaded files if (strpos($block, 'application/octet-stream') !== FALSE) { // match "name", then everything after "stream" (optional) except for prepending newlines // preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches); // $a_data['files'][$matches[1]] = isset($matches[2])?$matches[2]:null; } // parse all other fields else { // match "name" and optional value in between newline sequences if (strpos($block, 'filename="')===false) { preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); $result['data'][$matches[1]] = isset($matches[2])?$matches[2]:null; } else { preg_match('/; name=\"([^\"]*)\"; filename=\"([^\"]*)\"\s*Content\-Type: ([\w\/]+)[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); $result['files'][$matches[1]] = array( 'name' => $matches[2], 'type' => $matches[3], 'tmp_name' => tempnam( ini_get( 'upload_tmp_dir' ), 'php' ), 'error' => UPLOAD_ERR_OK, 'size' => 0); $result['files'][$matches[1]]['size'] = file_put_contents($result['files'][$matches[1]]['tmp_name'], $matches[4]); $result['files'][$matches[1]]['size']!==false || $result['files'][$matches[1]]['error'] = UPLOAD_ERR_CANT_WRITE; } } } } return $result; }
php
function parseBody() { $result = array( 'data'=>array(), 'files'=>array(), ); // read incoming data $input = Instance::get('BODY'); // grab multipart boundary from content type header preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches); // content type is probably regular form-encoded if (!count($matches)) { // we expect regular puts to containt a query string containing data parse_str($input, $result['data']); } else { $boundary = $matches[1]; // split content by boundary and get rid of last -- element $a_blocks = preg_split("/-+$boundary/", $input); array_pop($a_blocks); // loop data blocks foreach ($a_blocks as $id => $block) { if (empty($block)) continue; // you'll have to var_dump $block to understand this and maybe replace \n or \r with a visibile char // parse uploaded files if (strpos($block, 'application/octet-stream') !== FALSE) { // match "name", then everything after "stream" (optional) except for prepending newlines // preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches); // $a_data['files'][$matches[1]] = isset($matches[2])?$matches[2]:null; } // parse all other fields else { // match "name" and optional value in between newline sequences if (strpos($block, 'filename="')===false) { preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); $result['data'][$matches[1]] = isset($matches[2])?$matches[2]:null; } else { preg_match('/; name=\"([^\"]*)\"; filename=\"([^\"]*)\"\s*Content\-Type: ([\w\/]+)[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches); $result['files'][$matches[1]] = array( 'name' => $matches[2], 'type' => $matches[3], 'tmp_name' => tempnam( ini_get( 'upload_tmp_dir' ), 'php' ), 'error' => UPLOAD_ERR_OK, 'size' => 0); $result['files'][$matches[1]]['size'] = file_put_contents($result['files'][$matches[1]]['tmp_name'], $matches[4]); $result['files'][$matches[1]]['size']!==false || $result['files'][$matches[1]]['error'] = UPLOAD_ERR_CANT_WRITE; } } } } return $result; }
[ "function", "parseBody", "(", ")", "{", "$", "result", "=", "array", "(", "'data'", "=>", "array", "(", ")", ",", "'files'", "=>", "array", "(", ")", ",", ")", ";", "// read incoming data", "$", "input", "=", "Instance", "::", "get", "(", "'BODY'", ")", ";", "// grab multipart boundary from content type header", "preg_match", "(", "'/boundary=(.*)$/'", ",", "$", "_SERVER", "[", "'CONTENT_TYPE'", "]", ",", "$", "matches", ")", ";", "// content type is probably regular form-encoded", "if", "(", "!", "count", "(", "$", "matches", ")", ")", "{", "// we expect regular puts to containt a query string containing data", "parse_str", "(", "$", "input", ",", "$", "result", "[", "'data'", "]", ")", ";", "}", "else", "{", "$", "boundary", "=", "$", "matches", "[", "1", "]", ";", "// split content by boundary and get rid of last -- element", "$", "a_blocks", "=", "preg_split", "(", "\"/-+$boundary/\"", ",", "$", "input", ")", ";", "array_pop", "(", "$", "a_blocks", ")", ";", "// loop data blocks", "foreach", "(", "$", "a_blocks", "as", "$", "id", "=>", "$", "block", ")", "{", "if", "(", "empty", "(", "$", "block", ")", ")", "continue", ";", "// you'll have to var_dump $block to understand this and maybe replace \\n or \\r with a visibile char", "// parse uploaded files", "if", "(", "strpos", "(", "$", "block", ",", "'application/octet-stream'", ")", "!==", "FALSE", ")", "{", "// match \"name\", then everything after \"stream\" (optional) except for prepending newlines", "// preg_match(\"/name=\\\"([^\\\"]*)\\\".*stream[\\n|\\r]+([^\\n\\r].*)?$/s\", $block, $matches);", "// $a_data['files'][$matches[1]] = isset($matches[2])?$matches[2]:null;", "}", "// parse all other fields", "else", "{", "// match \"name\" and optional value in between newline sequences", "if", "(", "strpos", "(", "$", "block", ",", "'filename=\"'", ")", "===", "false", ")", "{", "preg_match", "(", "'/name=\\\"([^\\\"]*)\\\"[\\n|\\r]+([^\\n\\r].*)?\\r$/s'", ",", "$", "block", ",", "$", "matches", ")", ";", "$", "result", "[", "'data'", "]", "[", "$", "matches", "[", "1", "]", "]", "=", "isset", "(", "$", "matches", "[", "2", "]", ")", "?", "$", "matches", "[", "2", "]", ":", "null", ";", "}", "else", "{", "preg_match", "(", "'/; name=\\\"([^\\\"]*)\\\"; filename=\\\"([^\\\"]*)\\\"\\s*Content\\-Type: ([\\w\\/]+)[\\n|\\r]+([^\\n\\r].*)?\\r$/s'", ",", "$", "block", ",", "$", "matches", ")", ";", "$", "result", "[", "'files'", "]", "[", "$", "matches", "[", "1", "]", "]", "=", "array", "(", "'name'", "=>", "$", "matches", "[", "2", "]", ",", "'type'", "=>", "$", "matches", "[", "3", "]", ",", "'tmp_name'", "=>", "tempnam", "(", "ini_get", "(", "'upload_tmp_dir'", ")", ",", "'php'", ")", ",", "'error'", "=>", "UPLOAD_ERR_OK", ",", "'size'", "=>", "0", ")", ";", "$", "result", "[", "'files'", "]", "[", "$", "matches", "[", "1", "]", "]", "[", "'size'", "]", "=", "file_put_contents", "(", "$", "result", "[", "'files'", "]", "[", "$", "matches", "[", "1", "]", "]", "[", "'tmp_name'", "]", ",", "$", "matches", "[", "4", "]", ")", ";", "$", "result", "[", "'files'", "]", "[", "$", "matches", "[", "1", "]", "]", "[", "'size'", "]", "!==", "false", "||", "$", "result", "[", "'files'", "]", "[", "$", "matches", "[", "1", "]", "]", "[", "'error'", "]", "=", "UPLOAD_ERR_CANT_WRITE", ";", "}", "}", "}", "}", "return", "$", "result", ";", "}" ]
Parse body from PUT method @source https://gist.github.com/chlab/4283560 @return array data and files
[ "Parse", "body", "from", "PUT", "method", "@source", "https", ":", "//", "gist", ".", "github", ".", "com", "/", "chlab", "/", "4283560" ]
train
https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/Base.php#L1722-L1778