repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.convertToConnectorEncoding
public static function convertToConnectorEncoding($fileName) { $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $encoding = $_config->getFilesystemEncoding(); if (is_null($encoding) || strcasecmp($encoding, "UTF-8") == 0 || strcasecmp($encoding, "UTF8") == 0) { return $fileName; } if (!function_exists("iconv")) { if (strcasecmp($encoding, "ISO-8859-1") == 0 || strcasecmp($encoding, "ISO8859-1") == 0 || strcasecmp($encoding, "Latin1") == 0) { return utf8_encode($fileName); } else { return $fileName; } } $converted = @iconv($encoding, "UTF-8", $fileName); if ($converted === false) { return $fileName; } return $converted; }
php
public static function convertToConnectorEncoding($fileName) { $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $encoding = $_config->getFilesystemEncoding(); if (is_null($encoding) || strcasecmp($encoding, "UTF-8") == 0 || strcasecmp($encoding, "UTF8") == 0) { return $fileName; } if (!function_exists("iconv")) { if (strcasecmp($encoding, "ISO-8859-1") == 0 || strcasecmp($encoding, "ISO8859-1") == 0 || strcasecmp($encoding, "Latin1") == 0) { return utf8_encode($fileName); } else { return $fileName; } } $converted = @iconv($encoding, "UTF-8", $fileName); if ($converted === false) { return $fileName; } return $converted; }
[ "public", "static", "function", "convertToConnectorEncoding", "(", "$", "fileName", ")", "{", "$", "_config", "=", "&", "CKFinder_Connector_Core_Factory", "::", "getInstance", "(", "\"Core_Config\"", ")", ";", "$", "encoding", "=", "$", "_config", "->", "getFilesy...
Convert file name from system encoding into UTF-8 @static @access public @param string $fileName @return string
[ "Convert", "file", "name", "from", "system", "encoding", "into", "UTF", "-", "8" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L404-L427
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.getDocumentRootPath
public function getDocumentRootPath() { /** * The absolute pathname of the currently executing script. * Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, * $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. */ if (isset($_SERVER['SCRIPT_FILENAME'])) { $sRealPath = dirname($_SERVER['SCRIPT_FILENAME']); } else { /** * realpath — Returns canonicalized absolute pathname */ $sRealPath = realpath('.') ; } $sRealPath = $this->trimPathTrailingSlashes($sRealPath); /** * The filename of the currently executing script, relative to the document root. * For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar * would be /test.php/foo.bar. */ $sSelfPath = dirname($_SERVER['PHP_SELF']); $sSelfPath = $this->trimPathTrailingSlashes($sSelfPath); return $this->trimPathTrailingSlashes(substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath))); }
php
public function getDocumentRootPath() { /** * The absolute pathname of the currently executing script. * Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, * $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user. */ if (isset($_SERVER['SCRIPT_FILENAME'])) { $sRealPath = dirname($_SERVER['SCRIPT_FILENAME']); } else { /** * realpath — Returns canonicalized absolute pathname */ $sRealPath = realpath('.') ; } $sRealPath = $this->trimPathTrailingSlashes($sRealPath); /** * The filename of the currently executing script, relative to the document root. * For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar * would be /test.php/foo.bar. */ $sSelfPath = dirname($_SERVER['PHP_SELF']); $sSelfPath = $this->trimPathTrailingSlashes($sSelfPath); return $this->trimPathTrailingSlashes(substr($sRealPath, 0, strlen($sRealPath) - strlen($sSelfPath))); }
[ "public", "function", "getDocumentRootPath", "(", ")", "{", "/**\n * The absolute pathname of the currently executing script.\n * Notatka: If a script is executed with the CLI, as a relative path, such as file.php or ../file.php,\n * $_SERVER['SCRIPT_FILENAME'] will contain the r...
Find document root @return string @access public
[ "Find", "document", "root" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L435-L463
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.createDirectoryRecursively
public static function createDirectoryRecursively($dir) { if (DIRECTORY_SEPARATOR === "\\") { $dir = str_replace("/", "\\", $dir); } else if (DIRECTORY_SEPARATOR === "/") { $dir = str_replace("\\", "/", $dir); } $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); if ($perms = $_config->getChmodFolders()) { $oldUmask = umask(0); $bCreated = @mkdir($dir, $perms, true); umask($oldUmask); } else { $bCreated = @mkdir($dir, 0777, true); } return $bCreated; }
php
public static function createDirectoryRecursively($dir) { if (DIRECTORY_SEPARATOR === "\\") { $dir = str_replace("/", "\\", $dir); } else if (DIRECTORY_SEPARATOR === "/") { $dir = str_replace("\\", "/", $dir); } $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); if ($perms = $_config->getChmodFolders()) { $oldUmask = umask(0); $bCreated = @mkdir($dir, $perms, true); umask($oldUmask); } else { $bCreated = @mkdir($dir, 0777, true); } return $bCreated; }
[ "public", "static", "function", "createDirectoryRecursively", "(", "$", "dir", ")", "{", "if", "(", "DIRECTORY_SEPARATOR", "===", "\"\\\\\"", ")", "{", "$", "dir", "=", "str_replace", "(", "\"/\"", ",", "\"\\\\\"", ",", "$", "dir", ")", ";", "}", "else", ...
Create directory recursively @access public @static @param string $dir @return boolean
[ "Create", "directory", "recursively" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L473-L493
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.isImageValid
public static function isImageValid($filePath, $extension) { if (!@is_readable($filePath)) { return -1; } $imageCheckExtensions = array('gif', 'jpeg', 'jpg', 'png', 'psd', 'bmp', 'tiff'); // version_compare is available since PHP4 >= 4.0.7 if ( function_exists( 'version_compare' ) ) { $sCurrentVersion = phpversion(); if ( version_compare( $sCurrentVersion, "4.2.0" ) >= 0 ) { $imageCheckExtensions[] = "tiff"; $imageCheckExtensions[] = "tif"; } if ( version_compare( $sCurrentVersion, "4.3.0" ) >= 0 ) { $imageCheckExtensions[] = "swc"; } if ( version_compare( $sCurrentVersion, "4.3.2" ) >= 0 ) { $imageCheckExtensions[] = "jpc"; $imageCheckExtensions[] = "jp2"; $imageCheckExtensions[] = "jpx"; $imageCheckExtensions[] = "jb2"; $imageCheckExtensions[] = "xbm"; $imageCheckExtensions[] = "wbmp"; } } if ( !in_array( $extension, $imageCheckExtensions ) ) { return true; } if ( @getimagesize( $filePath ) === false ) { return false ; } return true; }
php
public static function isImageValid($filePath, $extension) { if (!@is_readable($filePath)) { return -1; } $imageCheckExtensions = array('gif', 'jpeg', 'jpg', 'png', 'psd', 'bmp', 'tiff'); // version_compare is available since PHP4 >= 4.0.7 if ( function_exists( 'version_compare' ) ) { $sCurrentVersion = phpversion(); if ( version_compare( $sCurrentVersion, "4.2.0" ) >= 0 ) { $imageCheckExtensions[] = "tiff"; $imageCheckExtensions[] = "tif"; } if ( version_compare( $sCurrentVersion, "4.3.0" ) >= 0 ) { $imageCheckExtensions[] = "swc"; } if ( version_compare( $sCurrentVersion, "4.3.2" ) >= 0 ) { $imageCheckExtensions[] = "jpc"; $imageCheckExtensions[] = "jp2"; $imageCheckExtensions[] = "jpx"; $imageCheckExtensions[] = "jb2"; $imageCheckExtensions[] = "xbm"; $imageCheckExtensions[] = "wbmp"; } } if ( !in_array( $extension, $imageCheckExtensions ) ) { return true; } if ( @getimagesize( $filePath ) === false ) { return false ; } return true; }
[ "public", "static", "function", "isImageValid", "(", "$", "filePath", ",", "$", "extension", ")", "{", "if", "(", "!", "@", "is_readable", "(", "$", "filePath", ")", ")", "{", "return", "-", "1", ";", "}", "$", "imageCheckExtensions", "=", "array", "("...
Check file content. Currently this function validates only image files. Returns false if file is invalid. @static @access public @param string $filePath absolute path to file @param string $extension file extension @param integer $detectionLevel 0 = none, 1 = use getimagesize for images, 2 = use DetectHtml for images @return boolean
[ "Check", "file", "content", ".", "Currently", "this", "function", "validates", "only", "image", "files", ".", "Returns", "false", "if", "file", "is", "invalid", "." ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L567-L604
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.hasChildren
public static function hasChildren($clientPath, $_resourceType) { $serverPath = CKFinder_Connector_Utils_FileSystem::combinePaths($_resourceType->getDirectory(), $clientPath); if (!is_dir($serverPath) || (false === $fh = @opendir($serverPath))) { return false; } $hasChildren = false; while (false !== ($filename = readdir($fh))) { if ($filename == '.' || $filename == '..') { continue; } else if (is_dir($serverPath . $filename)) { //we have found valid directory $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_acl = $_config->getAccessControlConfig(); $_aclMask = $_acl->getComputedMask($_resourceType->getName(), $clientPath . $filename); if ( ($_aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) != CKFINDER_CONNECTOR_ACL_FOLDER_VIEW ) { continue; } if ($_resourceType->checkIsHiddenFolder($filename)) { continue; } $hasChildren = true; break; } } closedir($fh); return $hasChildren; }
php
public static function hasChildren($clientPath, $_resourceType) { $serverPath = CKFinder_Connector_Utils_FileSystem::combinePaths($_resourceType->getDirectory(), $clientPath); if (!is_dir($serverPath) || (false === $fh = @opendir($serverPath))) { return false; } $hasChildren = false; while (false !== ($filename = readdir($fh))) { if ($filename == '.' || $filename == '..') { continue; } else if (is_dir($serverPath . $filename)) { //we have found valid directory $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_acl = $_config->getAccessControlConfig(); $_aclMask = $_acl->getComputedMask($_resourceType->getName(), $clientPath . $filename); if ( ($_aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) != CKFINDER_CONNECTOR_ACL_FOLDER_VIEW ) { continue; } if ($_resourceType->checkIsHiddenFolder($filename)) { continue; } $hasChildren = true; break; } } closedir($fh); return $hasChildren; }
[ "public", "static", "function", "hasChildren", "(", "$", "clientPath", ",", "$", "_resourceType", ")", "{", "$", "serverPath", "=", "CKFinder_Connector_Utils_FileSystem", "::", "combinePaths", "(", "$", "_resourceType", "->", "getDirectory", "(", ")", ",", "$", ...
Returns true if directory is not empty @access public @static @param string $clientPath client path (with trailing slash) @param object $_resourceType resource type configuration @return boolean
[ "Returns", "true", "if", "directory", "is", "not", "empty" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L615-L647
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.getTmpDir
public static function getTmpDir() { $_config = & CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $tmpDir = $_config->getTempDirectory(); if ( $tmpDir ) { return $tmpDir; } if ( !function_exists('sys_get_temp_dir')) { function sys_get_temp_dir() { if( $temp=getenv('TMP') ){ return $temp; } if( $temp=getenv('TEMP') ) { return $temp; } if( $temp=getenv('TMPDIR') ) { return $temp; } $temp = tempnam(__FILE__,''); if ( file_exists($temp) ){ unlink($temp); return dirname($temp); } return null; } } return sys_get_temp_dir(); }
php
public static function getTmpDir() { $_config = & CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $tmpDir = $_config->getTempDirectory(); if ( $tmpDir ) { return $tmpDir; } if ( !function_exists('sys_get_temp_dir')) { function sys_get_temp_dir() { if( $temp=getenv('TMP') ){ return $temp; } if( $temp=getenv('TEMP') ) { return $temp; } if( $temp=getenv('TMPDIR') ) { return $temp; } $temp = tempnam(__FILE__,''); if ( file_exists($temp) ){ unlink($temp); return dirname($temp); } return null; } } return sys_get_temp_dir(); }
[ "public", "static", "function", "getTmpDir", "(", ")", "{", "$", "_config", "=", "&", "CKFinder_Connector_Core_Factory", "::", "getInstance", "(", "\"Core_Config\"", ")", ";", "$", "tmpDir", "=", "$", "_config", "->", "getTempDirectory", "(", ")", ";", "if", ...
Retruns temp directory @access public @static @return string
[ "Retruns", "temp", "directory" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L656-L684
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.isEmptyDir
public static function isEmptyDir($dirname) { $files = scandir($dirname); if ( $files && count($files) > 2) { return false; } return true; }
php
public static function isEmptyDir($dirname) { $files = scandir($dirname); if ( $files && count($files) > 2) { return false; } return true; }
[ "public", "static", "function", "isEmptyDir", "(", "$", "dirname", ")", "{", "$", "files", "=", "scandir", "(", "$", "dirname", ")", ";", "if", "(", "$", "files", "&&", "count", "(", "$", "files", ")", ">", "2", ")", "{", "return", "false", ";", ...
Check if given directory is empty @param string $dirname @access public @static @return bool
[ "Check", "if", "given", "directory", "is", "empty" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L694-L702
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.autoRename
public static function autoRename( $filePath, $fileName ) { $sFileNameOrginal = $fileName; $iCounter = 0; while (true) { $sFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($filePath, $fileName); if ( file_exists($sFilePath) ){ $iCounter++; $fileName = CKFinder_Connector_Utils_FileSystem::getFileNameWithoutExtension($sFileNameOrginal, false) . "(" . $iCounter . ")" . "." .CKFinder_Connector_Utils_FileSystem::getExtension($sFileNameOrginal, false); } else { break; } } return $fileName; }
php
public static function autoRename( $filePath, $fileName ) { $sFileNameOrginal = $fileName; $iCounter = 0; while (true) { $sFilePath = CKFinder_Connector_Utils_FileSystem::combinePaths($filePath, $fileName); if ( file_exists($sFilePath) ){ $iCounter++; $fileName = CKFinder_Connector_Utils_FileSystem::getFileNameWithoutExtension($sFileNameOrginal, false) . "(" . $iCounter . ")" . "." .CKFinder_Connector_Utils_FileSystem::getExtension($sFileNameOrginal, false); } else { break; } } return $fileName; }
[ "public", "static", "function", "autoRename", "(", "$", "filePath", ",", "$", "fileName", ")", "{", "$", "sFileNameOrginal", "=", "$", "fileName", ";", "$", "iCounter", "=", "0", ";", "while", "(", "true", ")", "{", "$", "sFilePath", "=", "CKFinder_Conne...
Autorename file if previous name is already taken @param string $filePath @param string $fileName @param string $sFileNameOrginal
[ "Autorename", "file", "if", "previous", "name", "is", "already", "taken" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L711-L728
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.sendFile
public static function sendFile( $filePath ){ $config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); if ( $config->getXSendfile() ){ CKFinder_Connector_Utils_FileSystem::sendWithXSendfile($filePath); } else { CKFinder_Connector_Utils_FileSystem::readfileChunked($filePath); } }
php
public static function sendFile( $filePath ){ $config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); if ( $config->getXSendfile() ){ CKFinder_Connector_Utils_FileSystem::sendWithXSendfile($filePath); } else { CKFinder_Connector_Utils_FileSystem::readfileChunked($filePath); } }
[ "public", "static", "function", "sendFile", "(", "$", "filePath", ")", "{", "$", "config", "=", "&", "CKFinder_Connector_Core_Factory", "::", "getInstance", "(", "\"Core_Config\"", ")", ";", "if", "(", "$", "config", "->", "getXSendfile", "(", ")", ")", "{",...
Send file to browser Selects the method depending on the XSendfile setting @param string $filePath
[ "Send", "file", "to", "browser", "Selects", "the", "method", "depending", "on", "the", "XSendfile", "setting" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L735-L742
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php
CKFinder_Connector_Utils_FileSystem.sendWithXSendfile
public static function sendWithXSendfile ( $filePath ){ if ( stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== FALSE ){ $fallback = true; $config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $XSendfileNginx = $config->getXSendfileNginx(); foreach ( $XSendfileNginx as $location => $root){ if ( false !== stripos($filePath , $root) ){ $fallback = false; $filePath = str_ireplace($root,$location,$filePath); header("X-Accel-Redirect: ".$filePath); // Nginx break; } } // fallback to standar method if ( $fallback ){ CKFinder_Connector_Utils_FileSystem::readfileChunked($filePath); } } elseif ( stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd/1.4') !== FALSE ){ header("X-LIGHTTPD-send-file: ".$filePath); // Lighttpd v1.4 } else { header("X-Sendfile: ".$filePath); // Apache, Lighttpd v1.5, Cherokee } }
php
public static function sendWithXSendfile ( $filePath ){ if ( stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== FALSE ){ $fallback = true; $config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $XSendfileNginx = $config->getXSendfileNginx(); foreach ( $XSendfileNginx as $location => $root){ if ( false !== stripos($filePath , $root) ){ $fallback = false; $filePath = str_ireplace($root,$location,$filePath); header("X-Accel-Redirect: ".$filePath); // Nginx break; } } // fallback to standar method if ( $fallback ){ CKFinder_Connector_Utils_FileSystem::readfileChunked($filePath); } } elseif ( stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd/1.4') !== FALSE ){ header("X-LIGHTTPD-send-file: ".$filePath); // Lighttpd v1.4 } else { header("X-Sendfile: ".$filePath); // Apache, Lighttpd v1.5, Cherokee } }
[ "public", "static", "function", "sendWithXSendfile", "(", "$", "filePath", ")", "{", "if", "(", "stripos", "(", "$", "_SERVER", "[", "'SERVER_SOFTWARE'", "]", ",", "'nginx'", ")", "!==", "FALSE", ")", "{", "$", "fallback", "=", "true", ";", "$", "config"...
Send files using X-Sendfile server module @param string $filePath
[ "Send", "files", "using", "X", "-", "Sendfile", "server", "module" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Utils/FileSystem.php#L749-L771
train
aimeos/ai-controller-jobs
controller/common/src/Controller/Common/Subscription/Export/Csv/Processor/Address/Standard.php
Standard.process
public function process( \Aimeos\MShop\Subscription\Item\Iface $subscription, \Aimeos\MShop\Order\Item\Base\Iface $order ) { $result = []; $addresses = $order->getAddresses(); krsort( $addresses ); foreach( $addresses as $items ) { foreach( $items as $item ) { $data = []; $list = $item->toArray(); foreach( $this->getMapping() as $pos => $key ) { if( array_key_exists( $key, $list ) ) { $data[$pos] = $list[$key]; } else { $data[$pos] = ''; } } ksort( $data ); $result[] = $data; } } return $result; }
php
public function process( \Aimeos\MShop\Subscription\Item\Iface $subscription, \Aimeos\MShop\Order\Item\Base\Iface $order ) { $result = []; $addresses = $order->getAddresses(); krsort( $addresses ); foreach( $addresses as $items ) { foreach( $items as $item ) { $data = []; $list = $item->toArray(); foreach( $this->getMapping() as $pos => $key ) { if( array_key_exists( $key, $list ) ) { $data[$pos] = $list[$key]; } else { $data[$pos] = ''; } } ksort( $data ); $result[] = $data; } } return $result; }
[ "public", "function", "process", "(", "\\", "Aimeos", "\\", "MShop", "\\", "Subscription", "\\", "Item", "\\", "Iface", "$", "subscription", ",", "\\", "Aimeos", "\\", "MShop", "\\", "Order", "\\", "Item", "\\", "Base", "\\", "Iface", "$", "order", ")", ...
Returns the subscription related data @param \Aimeos\MShop\Subscription\Item\Iface $subscription Subscription item @param \Aimeos\MShop\Order\Item\Base\Iface $order Full subscription with associated items @return array Two dimensional associative list of subscription data representing the lines in CSV
[ "Returns", "the", "subscription", "related", "data" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/common/src/Controller/Common/Subscription/Export/Csv/Processor/Address/Standard.php#L43-L72
train
pr-of-it/t4
framework/Orm/Extensions/Tree.php
Tree.insertModelAsLastRoot
protected function insertModelAsLastRoot(Model $model) { /** @var \T4\Orm\Model $class */ $class = get_class($model); $tableName = $class::getTableName(); /** @var \T4\Dbal\Connection $connection */ $connection = $class::getDbConnection(); $query = (new Query()) ->select('MAX(__rgt)') ->from($tableName); $maxRgt = (int)$connection->query($query)->fetchScalar(); if ($model->isNew()) { $model->__lft = $maxRgt + 1; $model->__rgt = $model->__lft + 1; $model->__lvl = 0; $model->__prt = null; } else { $query = (new Query()) ->update() ->table($tableName) ->values([ '__lft' => '__lft + :max - :lft + 1', '__rgt' => '__rgt + :max - :lft + 1', '__lvl' => '__lvl - :lvl', ]) ->where('__lft>=:lft AND __rgt<=:rgt') ->params([':max' => $maxRgt, ':lft' => $model->__lft, ':rgt' => $model->__rgt, ':lvl' => $model->__lvl]); $connection->execute($query); $this->removeFromTreeByElement($model); // TODO: calculate new __lft, __rgt! $model->refreshTreeColumns(); $model->__lvl = 0; $model->__prt = null; } }
php
protected function insertModelAsLastRoot(Model $model) { /** @var \T4\Orm\Model $class */ $class = get_class($model); $tableName = $class::getTableName(); /** @var \T4\Dbal\Connection $connection */ $connection = $class::getDbConnection(); $query = (new Query()) ->select('MAX(__rgt)') ->from($tableName); $maxRgt = (int)$connection->query($query)->fetchScalar(); if ($model->isNew()) { $model->__lft = $maxRgt + 1; $model->__rgt = $model->__lft + 1; $model->__lvl = 0; $model->__prt = null; } else { $query = (new Query()) ->update() ->table($tableName) ->values([ '__lft' => '__lft + :max - :lft + 1', '__rgt' => '__rgt + :max - :lft + 1', '__lvl' => '__lvl - :lvl', ]) ->where('__lft>=:lft AND __rgt<=:rgt') ->params([':max' => $maxRgt, ':lft' => $model->__lft, ':rgt' => $model->__rgt, ':lvl' => $model->__lvl]); $connection->execute($query); $this->removeFromTreeByElement($model); // TODO: calculate new __lft, __rgt! $model->refreshTreeColumns(); $model->__lvl = 0; $model->__prt = null; } }
[ "protected", "function", "insertModelAsLastRoot", "(", "Model", "$", "model", ")", "{", "/** @var \\T4\\Orm\\Model $class */", "$", "class", "=", "get_class", "(", "$", "model", ")", ";", "$", "tableName", "=", "$", "class", "::", "getTableName", "(", ")", ";"...
Prepares model for insert into tree as last root @param \T4\Orm\Model $model
[ "Prepares", "model", "for", "insert", "into", "tree", "as", "last", "root" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Orm/Extensions/Tree.php#L310-L351
train
wikimedia/html-formatter
src/HtmlFormatter.php
HtmlFormatter.filterContent
public function filterContent() { $removals = $this->parseItemsToRemove(); // Bail out early if nothing to do if ( \array_reduce( $removals, function ( $carry, $item ) { return $carry && !$item; }, true ) ) { return []; } $doc = $this->getDoc(); // Remove tags // You can't remove DOMNodes from a DOMNodeList as you're iterating // over them in a foreach loop. It will seemingly leave the internal // iterator on the foreach out of wack and results will be quite // strange. Though, making a queue of items to remove seems to work. $domElemsToRemove = []; foreach ( $removals['TAG'] as $tagToRemove ) { $tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove ); foreach ( $tagToRemoveNodes as $tagToRemoveNode ) { if ( $tagToRemoveNode ) { $domElemsToRemove[] = $tagToRemoveNode; } } } $removed = $this->removeElements( $domElemsToRemove ); // Elements with named IDs $domElemsToRemove = []; foreach ( $removals['ID'] as $itemToRemove ) { $itemToRemoveNode = $doc->getElementById( $itemToRemove ); if ( $itemToRemoveNode ) { $domElemsToRemove[] = $itemToRemoveNode; } } $removed = array_merge( $removed, $this->removeElements( $domElemsToRemove ) ); // CSS Classes $domElemsToRemove = []; $xpath = new \DOMXPath( $doc ); foreach ( $removals['CLASS'] as $classToRemove ) { $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' ); /** @var $element \DOMElement */ foreach ( $elements as $element ) { $classes = $element->getAttribute( 'class' ); if ( \preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) { $domElemsToRemove[] = $element; } } } $removed = \array_merge( $removed, $this->removeElements( $domElemsToRemove ) ); // Tags with CSS Classes foreach ( $removals['TAG_CLASS'] as $classToRemove ) { $parts = explode( '.', $classToRemove ); $elements = $xpath->query( '//' . $parts[0] . '[@class="' . $parts[1] . '"]' ); $removed = array_merge( $removed, $this->removeElements( $elements ) ); } return $removed; }
php
public function filterContent() { $removals = $this->parseItemsToRemove(); // Bail out early if nothing to do if ( \array_reduce( $removals, function ( $carry, $item ) { return $carry && !$item; }, true ) ) { return []; } $doc = $this->getDoc(); // Remove tags // You can't remove DOMNodes from a DOMNodeList as you're iterating // over them in a foreach loop. It will seemingly leave the internal // iterator on the foreach out of wack and results will be quite // strange. Though, making a queue of items to remove seems to work. $domElemsToRemove = []; foreach ( $removals['TAG'] as $tagToRemove ) { $tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove ); foreach ( $tagToRemoveNodes as $tagToRemoveNode ) { if ( $tagToRemoveNode ) { $domElemsToRemove[] = $tagToRemoveNode; } } } $removed = $this->removeElements( $domElemsToRemove ); // Elements with named IDs $domElemsToRemove = []; foreach ( $removals['ID'] as $itemToRemove ) { $itemToRemoveNode = $doc->getElementById( $itemToRemove ); if ( $itemToRemoveNode ) { $domElemsToRemove[] = $itemToRemoveNode; } } $removed = array_merge( $removed, $this->removeElements( $domElemsToRemove ) ); // CSS Classes $domElemsToRemove = []; $xpath = new \DOMXPath( $doc ); foreach ( $removals['CLASS'] as $classToRemove ) { $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' ); /** @var $element \DOMElement */ foreach ( $elements as $element ) { $classes = $element->getAttribute( 'class' ); if ( \preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) { $domElemsToRemove[] = $element; } } } $removed = \array_merge( $removed, $this->removeElements( $domElemsToRemove ) ); // Tags with CSS Classes foreach ( $removals['TAG_CLASS'] as $classToRemove ) { $parts = explode( '.', $classToRemove ); $elements = $xpath->query( '//' . $parts[0] . '[@class="' . $parts[1] . '"]' ); $removed = array_merge( $removed, $this->removeElements( $elements ) ); } return $removed; }
[ "public", "function", "filterContent", "(", ")", "{", "$", "removals", "=", "$", "this", "->", "parseItemsToRemove", "(", ")", ";", "// Bail out early if nothing to do", "if", "(", "\\", "array_reduce", "(", "$", "removals", ",", "function", "(", "$", "carry",...
Removes content we've chosen to remove. The text of the removed elements can be extracted with the getText method. @return array Array of removed DOMElements
[ "Removes", "content", "we", "ve", "chosen", "to", "remove", ".", "The", "text", "of", "the", "removed", "elements", "can", "be", "extracted", "with", "the", "getText", "method", "." ]
5e33e3bbb327b3e0d685cc595837ccb024b72f57
https://github.com/wikimedia/html-formatter/blob/5e33e3bbb327b3e0d685cc595837ccb024b72f57/src/HtmlFormatter.php#L137-L206
train
wikimedia/html-formatter
src/HtmlFormatter.php
HtmlFormatter.removeElements
private function removeElements( $elements ) { $list = $elements; if ( $elements instanceof \DOMNodeList ) { $list = []; foreach ( $elements as $element ) { $list[] = $element; } } /** @var $element \DOMElement */ foreach ( $list as $element ) { if ( $element->parentNode ) { $element->parentNode->removeChild( $element ); } } return $list; }
php
private function removeElements( $elements ) { $list = $elements; if ( $elements instanceof \DOMNodeList ) { $list = []; foreach ( $elements as $element ) { $list[] = $element; } } /** @var $element \DOMElement */ foreach ( $list as $element ) { if ( $element->parentNode ) { $element->parentNode->removeChild( $element ); } } return $list; }
[ "private", "function", "removeElements", "(", "$", "elements", ")", "{", "$", "list", "=", "$", "elements", ";", "if", "(", "$", "elements", "instanceof", "\\", "DOMNodeList", ")", "{", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "elements", ...
Removes a list of elelments from DOMDocument @param array|\DOMNodeList $elements @return array Array of removed elements
[ "Removes", "a", "list", "of", "elelments", "from", "DOMDocument" ]
5e33e3bbb327b3e0d685cc595837ccb024b72f57
https://github.com/wikimedia/html-formatter/blob/5e33e3bbb327b3e0d685cc595837ccb024b72f57/src/HtmlFormatter.php#L213-L228
train
wikimedia/html-formatter
src/HtmlFormatter.php
HtmlFormatter.fixLibXML
private function fixLibXML( $html ) { // We don't include rules like '&#34;' => '&amp;quot;' because entities had already been // normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE! $replacements = [ '&quot;' => '&amp;quot;', '&amp;' => '&amp;amp;', '&lt;' => '&amp;lt;', '&gt;' => '&amp;gt;', ]; $html = strtr( $html, $replacements ); // Just in case the conversion in getDoc() above used named // entities that aren't known to html_entity_decode(). $html = \mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' ); return $html; }
php
private function fixLibXML( $html ) { // We don't include rules like '&#34;' => '&amp;quot;' because entities had already been // normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE! $replacements = [ '&quot;' => '&amp;quot;', '&amp;' => '&amp;amp;', '&lt;' => '&amp;lt;', '&gt;' => '&amp;gt;', ]; $html = strtr( $html, $replacements ); // Just in case the conversion in getDoc() above used named // entities that aren't known to html_entity_decode(). $html = \mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' ); return $html; }
[ "private", "function", "fixLibXML", "(", "$", "html", ")", "{", "// We don't include rules like '&#34;' => '&amp;quot;' because entities had already been", "// normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE!", "$", "replacements", "=", "[", "'&quot...
libxml in its usual pointlessness converts many chars to entities - this function perfoms a reverse conversion @param string $html @return string
[ "libxml", "in", "its", "usual", "pointlessness", "converts", "many", "chars", "to", "entities", "-", "this", "function", "perfoms", "a", "reverse", "conversion" ]
5e33e3bbb327b3e0d685cc595837ccb024b72f57
https://github.com/wikimedia/html-formatter/blob/5e33e3bbb327b3e0d685cc595837ccb024b72f57/src/HtmlFormatter.php#L236-L251
train
aimeos/ai-controller-jobs
controller/common/src/Controller/Common/Product/Import/Csv/Processor/Stock/Standard.php
Standard.process
public function process( \Aimeos\MShop\Product\Item\Iface $product, array $data ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'stock' ); $manager->begin(); try { $map = $this->getMappedChunk( $data, $this->getMapping() ); $items = $this->getStockItems( $product->getCode() ); foreach( $map as $pos => $list ) { if( !array_key_exists( 'stock.stocklevel', $list ) ) { continue; } $list['stock.productcode'] = $product->getCode(); $list['stock.dateback'] = $this->getValue( $list, 'stock.dateback' ); $list['stock.stocklevel'] = $this->getValue( $list, 'stock.stocklevel' ); $list['stock.type'] = $this->getValue( $list, 'stock.type', 'default' ); if( !in_array( $list['stock.type'], $this->types ) ) { $msg = sprintf( 'Invalid type "%1$s" (%2$s)', $list['stock.type'], 'stock' ); throw new \Aimeos\Controller\Common\Exception( $msg ); } if( ( $item = array_pop( $items ) ) === null ) { $item = $manager->createItem(); } $manager->saveItem( $item->fromArray( $list ), false ); } $manager->deleteItems( array_keys( $items ) ); $data = $this->getObject()->process( $product, $data ); $manager->commit(); } catch( \Exception $e ) { $manager->rollback(); throw $e; } return $data; }
php
public function process( \Aimeos\MShop\Product\Item\Iface $product, array $data ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'stock' ); $manager->begin(); try { $map = $this->getMappedChunk( $data, $this->getMapping() ); $items = $this->getStockItems( $product->getCode() ); foreach( $map as $pos => $list ) { if( !array_key_exists( 'stock.stocklevel', $list ) ) { continue; } $list['stock.productcode'] = $product->getCode(); $list['stock.dateback'] = $this->getValue( $list, 'stock.dateback' ); $list['stock.stocklevel'] = $this->getValue( $list, 'stock.stocklevel' ); $list['stock.type'] = $this->getValue( $list, 'stock.type', 'default' ); if( !in_array( $list['stock.type'], $this->types ) ) { $msg = sprintf( 'Invalid type "%1$s" (%2$s)', $list['stock.type'], 'stock' ); throw new \Aimeos\Controller\Common\Exception( $msg ); } if( ( $item = array_pop( $items ) ) === null ) { $item = $manager->createItem(); } $manager->saveItem( $item->fromArray( $list ), false ); } $manager->deleteItems( array_keys( $items ) ); $data = $this->getObject()->process( $product, $data ); $manager->commit(); } catch( \Exception $e ) { $manager->rollback(); throw $e; } return $data; }
[ "public", "function", "process", "(", "\\", "Aimeos", "\\", "MShop", "\\", "Product", "\\", "Item", "\\", "Iface", "$", "product", ",", "array", "$", "data", ")", "{", "$", "manager", "=", "\\", "Aimeos", "\\", "MShop", "::", "create", "(", "$", "thi...
Saves the product stock related data to the storage @param \Aimeos\MShop\Product\Item\Iface $product Product item with associated items @param array $data List of CSV fields with position as key and data as value @return array List of data which hasn't been imported
[ "Saves", "the", "product", "stock", "related", "data", "to", "the", "storage" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/common/src/Controller/Common/Product/Import/Csv/Processor/Stock/Standard.php#L66-L113
train
aimeos/ai-controller-jobs
controller/common/src/Controller/Common/Product/Import/Csv/Processor/Stock/Standard.php
Standard.getStockItems
protected function getStockItems( $code ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'stock' ); $search = $manager->createSearch(); $search->setConditions( $search->compare( '==', 'stock.productcode', $code ) ); return $manager->searchItems( $search ); }
php
protected function getStockItems( $code ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'stock' ); $search = $manager->createSearch(); $search->setConditions( $search->compare( '==', 'stock.productcode', $code ) ); return $manager->searchItems( $search ); }
[ "protected", "function", "getStockItems", "(", "$", "code", ")", "{", "$", "manager", "=", "\\", "Aimeos", "\\", "MShop", "::", "create", "(", "$", "this", "->", "getContext", "(", ")", ",", "'stock'", ")", ";", "$", "search", "=", "$", "manager", "-...
Returns the stock items for the given product code @param string $code Unique product code @return \Aimeos\MShop\Stock\Item\Iface[] Associative list of stock items
[ "Returns", "the", "stock", "items", "for", "the", "given", "product", "code" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/common/src/Controller/Common/Product/Import/Csv/Processor/Stock/Standard.php#L122-L130
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php
CKFinder.CreateHtml
public function CreateHtml() { $className = $this->ClassName ; if ( !empty( $className ) ) $className = ' class="' . $className . '"' ; $id = $this->Id ; if ( !empty( $id ) ) $id = ' id="' . $id . '"' ; return '<iframe src="' . $this->_BuildUrl() . '" width="' . $this->Width . '" ' . 'height="' . $this->Height . '"' . $className . $id . ' frameborder="0" scrolling="no"></iframe>' ; }
php
public function CreateHtml() { $className = $this->ClassName ; if ( !empty( $className ) ) $className = ' class="' . $className . '"' ; $id = $this->Id ; if ( !empty( $id ) ) $id = ' id="' . $id . '"' ; return '<iframe src="' . $this->_BuildUrl() . '" width="' . $this->Width . '" ' . 'height="' . $this->Height . '"' . $className . $id . ' frameborder="0" scrolling="no"></iframe>' ; }
[ "public", "function", "CreateHtml", "(", ")", "{", "$", "className", "=", "$", "this", "->", "ClassName", ";", "if", "(", "!", "empty", "(", "$", "className", ")", ")", "$", "className", "=", "' class=\"'", ".", "$", "className", ".", "'\"'", ";", "$...
Gets the HTML needed to create a CKFinder instance.
[ "Gets", "the", "HTML", "needed", "to", "create", "a", "CKFinder", "instance", "." ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php#L50-L62
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php
CKFinder.CreateStatic
public static function CreateStatic( $basePath = CKFINDER_DEFAULT_BASEPATH, $width = '100%', $height = 400, $selectFunction = null ) { $finder = new CKFinder( $basePath, $width, $height, $selectFunction ) ; $finder->Create() ; }
php
public static function CreateStatic( $basePath = CKFINDER_DEFAULT_BASEPATH, $width = '100%', $height = 400, $selectFunction = null ) { $finder = new CKFinder( $basePath, $width, $height, $selectFunction ) ; $finder->Create() ; }
[ "public", "static", "function", "CreateStatic", "(", "$", "basePath", "=", "CKFINDER_DEFAULT_BASEPATH", ",", "$", "width", "=", "'100%'", ",", "$", "height", "=", "400", ",", "$", "selectFunction", "=", "null", ")", "{", "$", "finder", "=", "new", "CKFinde...
Static "Create".
[ "Static", "Create", "." ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php#L132-L136
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php
CKFinder.SetupFCKeditor
public static function SetupFCKeditor( &$editorObj, $basePath = CKFINDER_DEFAULT_BASEPATH, $imageType = null, $flashType = null ) { if ( empty( $basePath ) ) $basePath = CKFINDER_DEFAULT_BASEPATH ; $ckfinder = new CKFinder( $basePath ) ; $ckfinder->SetupFCKeditorObject( $editorObj, $imageType, $flashType ); }
php
public static function SetupFCKeditor( &$editorObj, $basePath = CKFINDER_DEFAULT_BASEPATH, $imageType = null, $flashType = null ) { if ( empty( $basePath ) ) $basePath = CKFINDER_DEFAULT_BASEPATH ; $ckfinder = new CKFinder( $basePath ) ; $ckfinder->SetupFCKeditorObject( $editorObj, $imageType, $flashType ); }
[ "public", "static", "function", "SetupFCKeditor", "(", "&", "$", "editorObj", ",", "$", "basePath", "=", "CKFINDER_DEFAULT_BASEPATH", ",", "$", "imageType", "=", "null", ",", "$", "flashType", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "basePath"...
Static "SetupFCKeditor".
[ "Static", "SetupFCKeditor", "." ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php#L139-L146
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php
CKFinder.SetupFCKeditorObject
public function SetupFCKeditorObject( &$editorObj, $imageType = null, $flashType = null ) { $url = $this->BasePath ; // If it is a path relative to the current page. if ( isset($url[0]) && $url[0] != '/' && strpos($url, "://") === false ) { $url = substr( $_SERVER[ 'REQUEST_URI' ], 0, strrpos( $_SERVER[ 'REQUEST_URI' ], '/' ) + 1 ) . $url ; } $url = $this->_BuildUrl( $url ) ; $qs = ( strpos($url, "?") !== false ) ? "&" : "?" ; if ( $this->Width !== '100%' && is_numeric( str_ireplace( "px", "", $this->Width ) ) ) { $width = intval( $this->Width ); $editorObj->Config['LinkBrowserWindowWidth'] = $width ; $editorObj->Config['ImageBrowserWindowWidth'] = $width ; $editorObj->Config['FlashBrowserWindowWidth'] = $width ; } if ( $this->Height !== 400 && is_numeric( str_ireplace( "px", "", $this->Height ) ) ) { $height = intval( $this->Height ); $editorObj->Config['LinkBrowserWindowHeight'] = $height ; $editorObj->Config['ImageBrowserWindowHeight'] = $height ; $editorObj->Config['FlashBrowserWindowHeight'] = $height ; } $editorObj->Config['LinkBrowserURL'] = $url ; $editorObj->Config['ImageBrowserURL'] = $url . $qs . 'type=' . ( empty( $imageType ) ? 'Images' : $imageType ) ; $editorObj->Config['FlashBrowserURL'] = $url . $qs . 'type=' . ( empty( $flashType ) ? 'Flash' : $flashType ) ; $dir = substr( $url, 0, strrpos( $url, "/" ) + 1 ) ; $editorObj->Config['LinkUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=Files' ) ; $editorObj->Config['ImageUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=') . ( empty( $imageType ) ? 'Images' : $imageType ) ; $editorObj->Config['FlashUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=') . ( empty( $flashType ) ? 'Flash' : $flashType ) ; }
php
public function SetupFCKeditorObject( &$editorObj, $imageType = null, $flashType = null ) { $url = $this->BasePath ; // If it is a path relative to the current page. if ( isset($url[0]) && $url[0] != '/' && strpos($url, "://") === false ) { $url = substr( $_SERVER[ 'REQUEST_URI' ], 0, strrpos( $_SERVER[ 'REQUEST_URI' ], '/' ) + 1 ) . $url ; } $url = $this->_BuildUrl( $url ) ; $qs = ( strpos($url, "?") !== false ) ? "&" : "?" ; if ( $this->Width !== '100%' && is_numeric( str_ireplace( "px", "", $this->Width ) ) ) { $width = intval( $this->Width ); $editorObj->Config['LinkBrowserWindowWidth'] = $width ; $editorObj->Config['ImageBrowserWindowWidth'] = $width ; $editorObj->Config['FlashBrowserWindowWidth'] = $width ; } if ( $this->Height !== 400 && is_numeric( str_ireplace( "px", "", $this->Height ) ) ) { $height = intval( $this->Height ); $editorObj->Config['LinkBrowserWindowHeight'] = $height ; $editorObj->Config['ImageBrowserWindowHeight'] = $height ; $editorObj->Config['FlashBrowserWindowHeight'] = $height ; } $editorObj->Config['LinkBrowserURL'] = $url ; $editorObj->Config['ImageBrowserURL'] = $url . $qs . 'type=' . ( empty( $imageType ) ? 'Images' : $imageType ) ; $editorObj->Config['FlashBrowserURL'] = $url . $qs . 'type=' . ( empty( $flashType ) ? 'Flash' : $flashType ) ; $dir = substr( $url, 0, strrpos( $url, "/" ) + 1 ) ; $editorObj->Config['LinkUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=Files' ) ; $editorObj->Config['ImageUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=') . ( empty( $imageType ) ? 'Images' : $imageType ) ; $editorObj->Config['FlashUploadURL'] = $dir . urlencode( 'core/connector/php/connector.php?command=QuickUpload&type=') . ( empty( $flashType ) ? 'Flash' : $flashType ) ; }
[ "public", "function", "SetupFCKeditorObject", "(", "&", "$", "editorObj", ",", "$", "imageType", "=", "null", ",", "$", "flashType", "=", "null", ")", "{", "$", "url", "=", "$", "this", "->", "BasePath", ";", "// If it is a path relative to the current page.", ...
Non-static method of attaching CKFinder to FCKeditor
[ "Non", "-", "static", "method", "of", "attaching", "CKFinder", "to", "FCKeditor" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php#L149-L185
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php
CKFinder.SetupCKEditor
public static function SetupCKEditor( &$editorObj, $basePath = CKFINDER_DEFAULT_BASEPATH, $imageType = null, $flashType = null ) { if ( empty( $basePath ) ) $basePath = CKFINDER_DEFAULT_BASEPATH ; $ckfinder = new CKFinder( $basePath ) ; $ckfinder->SetupCKEditorObject( $editorObj, $imageType, $flashType ); }
php
public static function SetupCKEditor( &$editorObj, $basePath = CKFINDER_DEFAULT_BASEPATH, $imageType = null, $flashType = null ) { if ( empty( $basePath ) ) $basePath = CKFINDER_DEFAULT_BASEPATH ; $ckfinder = new CKFinder( $basePath ) ; $ckfinder->SetupCKEditorObject( $editorObj, $imageType, $flashType ); }
[ "public", "static", "function", "SetupCKEditor", "(", "&", "$", "editorObj", ",", "$", "basePath", "=", "CKFINDER_DEFAULT_BASEPATH", ",", "$", "imageType", "=", "null", ",", "$", "flashType", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "basePath",...
Static "SetupCKEditor".
[ "Static", "SetupCKEditor", "." ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/ckfinder_php5.php#L188-L195
train
aimeos/ai-controller-jobs
controller/jobs/src/Controller/Jobs/Product/Import/Csv/Standard.php
Standard.getCodePosition
protected function getCodePosition( array $mapping ) { foreach( $mapping as $pos => $key ) { if( $key === 'product.code' ) { return $pos; } } throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "product.code" column in CSV mapping found' ) ); }
php
protected function getCodePosition( array $mapping ) { foreach( $mapping as $pos => $key ) { if( $key === 'product.code' ) { return $pos; } } throw new \Aimeos\Controller\Jobs\Exception( sprintf( 'No "product.code" column in CSV mapping found' ) ); }
[ "protected", "function", "getCodePosition", "(", "array", "$", "mapping", ")", "{", "foreach", "(", "$", "mapping", "as", "$", "pos", "=>", "$", "key", ")", "{", "if", "(", "$", "key", "===", "'product.code'", ")", "{", "return", "$", "pos", ";", "}"...
Returns the position of the "product.code" column from the product item mapping @param array $mapping Mapping of the "item" columns with position as key and code as value @return integer Position of the "product.code" column @throws \Aimeos\Controller\Jobs\Exception If no mapping for "product.code" is found
[ "Returns", "the", "position", "of", "the", "product", ".", "code", "column", "from", "the", "product", "item", "mapping" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/jobs/src/Controller/Jobs/Product/Import/Csv/Standard.php#L393-L403
train
aimeos/ai-controller-jobs
controller/jobs/src/Controller/Jobs/Product/Import/Csv/Standard.php
Standard.import
protected function import( array $products, array $data, array $mapping, array $types, \Aimeos\Controller\Common\Product\Import\Csv\Processor\Iface $processor, $strict ) { $items = []; $errors = 0; $context = $this->getContext(); $manager = \Aimeos\MShop::create( $context, 'product' ); $indexManager = \Aimeos\MShop::create( $context, 'index' ); foreach( $data as $code => $list ) { $manager->begin(); try { $code = trim( $code ); if( isset( $products[$code] ) ) { $product = $products[$code]; } else { $product = $manager->createItem(); } $map = $this->getMappedChunk( $list, $mapping ); if( isset( $map[0] ) ) { $map = $map[0]; // there can only be one chunk for the base product data $map['product.type'] = $this->getValue( $map, 'product.type', 'default' ); if( !in_array( $map['product.type'], $types ) ) { $msg = sprintf( 'Invalid product type "%1$s"', $map['product.type'] ); throw new \Aimeos\Controller\Jobs\Exception( $msg ); } $product = $manager->saveItem( $product->fromArray( $map, true ) ); $list = $processor->process( $product, $list ); $product = $manager->saveItem( $product ); $items[$product->getId()] = $product; } $manager->commit(); } catch( \Exception $e ) { $manager->rollback(); $msg = sprintf( 'Unable to import product with code "%1$s": %2$s', $code, $e->getMessage() ); $context->getLogger()->log( $msg ); $errors++; } if( $strict && !empty( $list ) ) { $context->getLogger()->log( 'Not imported: ' . print_r( $list, true ) ); } } $indexManager->rebuildIndex( $items ); return $errors; }
php
protected function import( array $products, array $data, array $mapping, array $types, \Aimeos\Controller\Common\Product\Import\Csv\Processor\Iface $processor, $strict ) { $items = []; $errors = 0; $context = $this->getContext(); $manager = \Aimeos\MShop::create( $context, 'product' ); $indexManager = \Aimeos\MShop::create( $context, 'index' ); foreach( $data as $code => $list ) { $manager->begin(); try { $code = trim( $code ); if( isset( $products[$code] ) ) { $product = $products[$code]; } else { $product = $manager->createItem(); } $map = $this->getMappedChunk( $list, $mapping ); if( isset( $map[0] ) ) { $map = $map[0]; // there can only be one chunk for the base product data $map['product.type'] = $this->getValue( $map, 'product.type', 'default' ); if( !in_array( $map['product.type'], $types ) ) { $msg = sprintf( 'Invalid product type "%1$s"', $map['product.type'] ); throw new \Aimeos\Controller\Jobs\Exception( $msg ); } $product = $manager->saveItem( $product->fromArray( $map, true ) ); $list = $processor->process( $product, $list ); $product = $manager->saveItem( $product ); $items[$product->getId()] = $product; } $manager->commit(); } catch( \Exception $e ) { $manager->rollback(); $msg = sprintf( 'Unable to import product with code "%1$s": %2$s', $code, $e->getMessage() ); $context->getLogger()->log( $msg ); $errors++; } if( $strict && !empty( $list ) ) { $context->getLogger()->log( 'Not imported: ' . print_r( $list, true ) ); } } $indexManager->rebuildIndex( $items ); return $errors; }
[ "protected", "function", "import", "(", "array", "$", "products", ",", "array", "$", "data", ",", "array", "$", "mapping", ",", "array", "$", "types", ",", "\\", "Aimeos", "\\", "Controller", "\\", "Common", "\\", "Product", "\\", "Import", "\\", "Csv", ...
Imports the CSV data and creates new products or updates existing ones @param array $products List of products items implementing \Aimeos\MShop\Product\Item\Iface @param array $data Associative list of import data as index/value pairs @param array $mapping Associative list of positions and domain item keys @param array $types List of allowed product type codes @param \Aimeos\Controller\Common\Product\Import\Csv\Processor\Iface $processor Processor object @param boolean $strict Log columns not mapped or silently ignore them @return integer Number of products that couldn't be imported @throws \Aimeos\Controller\Jobs\Exception
[ "Imports", "the", "CSV", "data", "and", "creates", "new", "products", "or", "updates", "existing", "ones" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/jobs/src/Controller/Jobs/Product/Import/Csv/Standard.php#L523-L587
train
Yoast/yoastcs
Yoast/Sniffs/Yoast/AlternativeFunctionsSniff.php
AlternativeFunctionsSniff.process_matched_token
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $replacement = ''; if ( isset( $this->groups[ $group_name ]['replacement'] ) ) { $replacement = $this->groups[ $group_name ]['replacement']; } $fixable = true; $message = $this->groups[ $group_name ]['message']; $is_error = ( $this->groups[ $group_name ]['type'] === 'error' ); $error_code = $this->string_to_errorcode( $group_name . '_' . $matched_content ); $data = array( $matched_content, $replacement, ); /* * Deal with specific situations. */ switch ( $matched_content ) { case 'json_encode': case 'wp_json_encode': /* * The function `WPSEO_Utils:format_json_encode()` is only a valid alternative * when only the first parameter is passed. */ if ( $this->get_function_call_parameter_count( $stackPtr ) !== 1 ) { $fixable = false; $error_code .= 'WithAdditionalParams'; } break; } if ( $fixable === false ) { $this->addMessage( $message, $stackPtr, $is_error, $error_code, $data ); return; } $fix = $this->addFixableMessage( $message, $stackPtr, $is_error, $error_code, $data ); if ( $fix === true ) { $namespaced = $this->determine_namespace( $stackPtr ); if ( empty( $namespaced ) || empty( $replacement ) ) { $this->phpcsFile->fixer->replaceToken( $stackPtr, $replacement ); } else { $this->phpcsFile->fixer->replaceToken( $stackPtr, '\\' . $replacement ); } } }
php
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $replacement = ''; if ( isset( $this->groups[ $group_name ]['replacement'] ) ) { $replacement = $this->groups[ $group_name ]['replacement']; } $fixable = true; $message = $this->groups[ $group_name ]['message']; $is_error = ( $this->groups[ $group_name ]['type'] === 'error' ); $error_code = $this->string_to_errorcode( $group_name . '_' . $matched_content ); $data = array( $matched_content, $replacement, ); /* * Deal with specific situations. */ switch ( $matched_content ) { case 'json_encode': case 'wp_json_encode': /* * The function `WPSEO_Utils:format_json_encode()` is only a valid alternative * when only the first parameter is passed. */ if ( $this->get_function_call_parameter_count( $stackPtr ) !== 1 ) { $fixable = false; $error_code .= 'WithAdditionalParams'; } break; } if ( $fixable === false ) { $this->addMessage( $message, $stackPtr, $is_error, $error_code, $data ); return; } $fix = $this->addFixableMessage( $message, $stackPtr, $is_error, $error_code, $data ); if ( $fix === true ) { $namespaced = $this->determine_namespace( $stackPtr ); if ( empty( $namespaced ) || empty( $replacement ) ) { $this->phpcsFile->fixer->replaceToken( $stackPtr, $replacement ); } else { $this->phpcsFile->fixer->replaceToken( $stackPtr, '\\' . $replacement ); } } }
[ "public", "function", "process_matched_token", "(", "$", "stackPtr", ",", "$", "group_name", ",", "$", "matched_content", ")", "{", "$", "replacement", "=", "''", ";", "if", "(", "isset", "(", "$", "this", "->", "groups", "[", "$", "group_name", "]", "["...
Process a matched token. @param int $stackPtr The position of the current token in the stack. @param string $group_name The name of the group which was matched. @param string $matched_content The token content (function name) which was matched. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
[ "Process", "a", "matched", "token", "." ]
44d4f28bbcf5f83d1111fafe67a17215b28c87d1
https://github.com/Yoast/yoastcs/blob/44d4f28bbcf5f83d1111fafe67a17215b28c87d1/Yoast/Sniffs/Yoast/AlternativeFunctionsSniff.php#L46-L96
train
Yoast/yoastcs
Yoast/Sniffs/Files/FileNameSniff.php
FileNameSniff.is_file_excluded
protected function is_file_excluded( File $phpcsFile, $path_to_file ) { $exclude = $this->clean_custom_array_property( $this->exclude, true, true ); if ( ! empty( $exclude ) ) { $exclude = array_map( array( $this, 'normalize_directory_separators' ), $exclude ); $path_to_file = $this->normalize_directory_separators( $path_to_file ); if ( ! isset( $phpcsFile->config->basepath ) ) { $phpcsFile->addWarning( 'For the exclude property to work with relative file path files, the --basepath needs to be set.', 0, 'MissingBasePath' ); } else { $base_path = $this->normalize_directory_separators( $phpcsFile->config->basepath ); $path_to_file = Common::stripBasepath( $path_to_file, $base_path ); } // Lowercase the filename to not interfere with the lowercase/dashes rule. $path_to_file = strtolower( ltrim( $path_to_file, '/' ) ); if ( isset( $exclude[ $path_to_file ] ) ) { // Filename is on the exclude list. return true; } } return false; }
php
protected function is_file_excluded( File $phpcsFile, $path_to_file ) { $exclude = $this->clean_custom_array_property( $this->exclude, true, true ); if ( ! empty( $exclude ) ) { $exclude = array_map( array( $this, 'normalize_directory_separators' ), $exclude ); $path_to_file = $this->normalize_directory_separators( $path_to_file ); if ( ! isset( $phpcsFile->config->basepath ) ) { $phpcsFile->addWarning( 'For the exclude property to work with relative file path files, the --basepath needs to be set.', 0, 'MissingBasePath' ); } else { $base_path = $this->normalize_directory_separators( $phpcsFile->config->basepath ); $path_to_file = Common::stripBasepath( $path_to_file, $base_path ); } // Lowercase the filename to not interfere with the lowercase/dashes rule. $path_to_file = strtolower( ltrim( $path_to_file, '/' ) ); if ( isset( $exclude[ $path_to_file ] ) ) { // Filename is on the exclude list. return true; } } return false; }
[ "protected", "function", "is_file_excluded", "(", "File", "$", "phpcsFile", ",", "$", "path_to_file", ")", "{", "$", "exclude", "=", "$", "this", "->", "clean_custom_array_property", "(", "$", "this", "->", "exclude", ",", "true", ",", "true", ")", ";", "i...
Check if the file is on the exclude list. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param string $path_to_file The full path to the file currently being examined. @return bool
[ "Check", "if", "the", "file", "is", "on", "the", "exclude", "list", "." ]
44d4f28bbcf5f83d1111fafe67a17215b28c87d1
https://github.com/Yoast/yoastcs/blob/44d4f28bbcf5f83d1111fafe67a17215b28c87d1/Yoast/Sniffs/Files/FileNameSniff.php#L206-L235
train
Yoast/yoastcs
Yoast/Sniffs/Files/FileNameSniff.php
FileNameSniff.clean_custom_array_property
protected function clean_custom_array_property( $property, $flip = false, $to_lower = false ) { if ( is_bool( $property ) ) { // Allow for resetting in the unit tests. return array(); } if ( is_string( $property ) ) { $property = explode( ',', $property ); } $property = array_filter( array_map( 'trim', $property ) ); if ( true === $to_lower ) { $property = array_map( 'strtolower', $property ); } if ( true === $flip ) { $property = array_fill_keys( $property, false ); } return $property; }
php
protected function clean_custom_array_property( $property, $flip = false, $to_lower = false ) { if ( is_bool( $property ) ) { // Allow for resetting in the unit tests. return array(); } if ( is_string( $property ) ) { $property = explode( ',', $property ); } $property = array_filter( array_map( 'trim', $property ) ); if ( true === $to_lower ) { $property = array_map( 'strtolower', $property ); } if ( true === $flip ) { $property = array_fill_keys( $property, false ); } return $property; }
[ "protected", "function", "clean_custom_array_property", "(", "$", "property", ",", "$", "flip", "=", "false", ",", "$", "to_lower", "=", "false", ")", "{", "if", "(", "is_bool", "(", "$", "property", ")", ")", "{", "// Allow for resetting in the unit tests.", ...
Clean a custom array property received from a ruleset. Deals with incorrectly passed custom array properties. - If the property was passed as a string, change it to an array. - Remove whitespace surrounding values. - Remove empty array entries. Optionally flips the array to allow for using `isset` instead of `in_array`. @param mixed $property The current property value. @param bool $flip Whether to flip the array values to keys. @param bool $to_lower Whether to lowercase the array values. @return array
[ "Clean", "a", "custom", "array", "property", "received", "from", "a", "ruleset", "." ]
44d4f28bbcf5f83d1111fafe67a17215b28c87d1
https://github.com/Yoast/yoastcs/blob/44d4f28bbcf5f83d1111fafe67a17215b28c87d1/Yoast/Sniffs/Files/FileNameSniff.php#L253-L274
train
Radvance/Radvance
src/Framework/BaseConsoleApplication.php
BaseConsoleApplication.configurePdo
protected function configurePdo() { if (!isset($this['parameters']['pdo'])) { return; } $connector = new Connector(); $this->pdo = $connector->getPdo( $connector->getConfig($this['parameters']['pdo']) ); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this['pdo'] = $this->pdo; }
php
protected function configurePdo() { if (!isset($this['parameters']['pdo'])) { return; } $connector = new Connector(); $this->pdo = $connector->getPdo( $connector->getConfig($this['parameters']['pdo']) ); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this['pdo'] = $this->pdo; }
[ "protected", "function", "configurePdo", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "[", "'parameters'", "]", "[", "'pdo'", "]", ")", ")", "{", "return", ";", "}", "$", "connector", "=", "new", "Connector", "(", ")", ";", "$", "this"...
Configure PDO.
[ "Configure", "PDO", "." ]
980034dd02da75882089210a25da6d5d74229b2b
https://github.com/Radvance/Radvance/blob/980034dd02da75882089210a25da6d5d74229b2b/src/Framework/BaseConsoleApplication.php#L223-L236
train
Radvance/Radvance
src/Framework/BaseConsoleApplication.php
BaseConsoleApplication.configureCache
protected function configureCache() { if (!isset($this['cache'])) { $this['cache'] = [ 'type' => 'array' ]; } if (!isset($this['cache']['type'])) { throw new RuntimeException("cache type not configured correctly"); } switch ($this['cache']['type']) { case 'array': $cache = new \Symfony\Component\Cache\Adapter\ArrayAdapter(); break; case 'filesystem': $directory = $this['cache']['directory']; if (!$directory) { throw new RuntimeException("cache directory not configured (please check doc/cache.md)"); } if (!file_exists($directory)) { mkdir($directory, 0777, true); } $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter('', 0, $directory); break; default: throw new RuntimeException("Unsupported cache.type:" . $this['cache']['type']); } $this['cache'] = $cache; }
php
protected function configureCache() { if (!isset($this['cache'])) { $this['cache'] = [ 'type' => 'array' ]; } if (!isset($this['cache']['type'])) { throw new RuntimeException("cache type not configured correctly"); } switch ($this['cache']['type']) { case 'array': $cache = new \Symfony\Component\Cache\Adapter\ArrayAdapter(); break; case 'filesystem': $directory = $this['cache']['directory']; if (!$directory) { throw new RuntimeException("cache directory not configured (please check doc/cache.md)"); } if (!file_exists($directory)) { mkdir($directory, 0777, true); } $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter('', 0, $directory); break; default: throw new RuntimeException("Unsupported cache.type:" . $this['cache']['type']); } $this['cache'] = $cache; }
[ "protected", "function", "configureCache", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "[", "'cache'", "]", ")", ")", "{", "$", "this", "[", "'cache'", "]", "=", "[", "'type'", "=>", "'array'", "]", ";", "}", "if", "(", "!", "isset"...
Configure cache.
[ "Configure", "cache", "." ]
980034dd02da75882089210a25da6d5d74229b2b
https://github.com/Radvance/Radvance/blob/980034dd02da75882089210a25da6d5d74229b2b/src/Framework/BaseConsoleApplication.php#L241-L270
train
Radvance/Radvance
src/Framework/BaseConsoleApplication.php
BaseConsoleApplication.configureService
protected function configureService() { // Translations $this['locale_fallbacks'] = array('en_US'); $this->register(new TranslationServiceProvider()); $translator = $this['translator']; $translator->addLoader('yaml', new RecursiveYamlFileMessageLoader()); $files = glob($this->getRootPath() .'/app/l10n/*.yml'); foreach ($files as $filename) { $locale = str_replace('.yml', '', basename($filename)); $translator->addResource('yaml', $filename, $locale); } }
php
protected function configureService() { // Translations $this['locale_fallbacks'] = array('en_US'); $this->register(new TranslationServiceProvider()); $translator = $this['translator']; $translator->addLoader('yaml', new RecursiveYamlFileMessageLoader()); $files = glob($this->getRootPath() .'/app/l10n/*.yml'); foreach ($files as $filename) { $locale = str_replace('.yml', '', basename($filename)); $translator->addResource('yaml', $filename, $locale); } }
[ "protected", "function", "configureService", "(", ")", "{", "// Translations", "$", "this", "[", "'locale_fallbacks'", "]", "=", "array", "(", "'en_US'", ")", ";", "$", "this", "->", "register", "(", "new", "TranslationServiceProvider", "(", ")", ")", ";", "...
Configure services.
[ "Configure", "services", "." ]
980034dd02da75882089210a25da6d5d74229b2b
https://github.com/Radvance/Radvance/blob/980034dd02da75882089210a25da6d5d74229b2b/src/Framework/BaseConsoleApplication.php#L275-L289
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.createQueue
public function createQueue(CreateQueueRequest $request) { $response = new CreateQueueResponse($request->getQueueName()); return $this->client->sendRequest($request, $response); }
php
public function createQueue(CreateQueueRequest $request) { $response = new CreateQueueResponse($request->getQueueName()); return $this->client->sendRequest($request, $response); }
[ "public", "function", "createQueue", "(", "CreateQueueRequest", "$", "request", ")", "{", "$", "response", "=", "new", "CreateQueueResponse", "(", "$", "request", "->", "getQueueName", "(", ")", ")", ";", "return", "$", "this", "->", "client", "->", "sendReq...
Create Queue and Returns the Queue reference @param CreateQueueRequest $request : the QueueName and QueueAttributes @return CreateQueueResponse $response: the CreateQueueResponse @throws QueueAlreadyExistException if queue already exists @throws InvalidArgumentException if any argument value is invalid @throws MnsException if any other exception happends
[ "Create", "Queue", "and", "Returns", "the", "Queue", "reference" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L72-L77
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.listQueue
public function listQueue(ListQueueRequest $request) { $response = new ListQueueResponse(); return $this->client->sendRequest($request, $response); }
php
public function listQueue(ListQueueRequest $request) { $response = new ListQueueResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "listQueue", "(", "ListQueueRequest", "$", "request", ")", "{", "$", "response", "=", "new", "ListQueueResponse", "(", ")", ";", "return", "$", "this", "->", "client", "->", "sendRequest", "(", "$", "request", ",", "$", "response", ")...
Query the queues created by current account @param ListQueueRequest $request : define filters for quering queues @return ListQueueResponse: the response containing queueNames
[ "Query", "the", "queues", "created", "by", "current", "account" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L106-L111
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.deleteQueue
public function deleteQueue($queueName) { $request = new DeleteQueueRequest($queueName); $response = new DeleteQueueResponse(); return $this->client->sendRequest($request, $response); }
php
public function deleteQueue($queueName) { $request = new DeleteQueueRequest($queueName); $response = new DeleteQueueResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "deleteQueue", "(", "$", "queueName", ")", "{", "$", "request", "=", "new", "DeleteQueueRequest", "(", "$", "queueName", ")", ";", "$", "response", "=", "new", "DeleteQueueResponse", "(", ")", ";", "return", "$", "this", "->", "client...
Delete the specified queue the request will succeed even when the queue does not exist @param $queueName : the queueName @return DeleteQueueResponse
[ "Delete", "the", "specified", "queue", "the", "request", "will", "succeed", "even", "when", "the", "queue", "does", "not", "exist" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L130-L136
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.createTopic
public function createTopic(CreateTopicRequest $request) { $response = new CreateTopicResponse($request->getTopicName()); return $this->client->sendRequest($request, $response); }
php
public function createTopic(CreateTopicRequest $request) { $response = new CreateTopicResponse($request->getTopicName()); return $this->client->sendRequest($request, $response); }
[ "public", "function", "createTopic", "(", "CreateTopicRequest", "$", "request", ")", "{", "$", "response", "=", "new", "CreateTopicResponse", "(", "$", "request", "->", "getTopicName", "(", ")", ")", ";", "return", "$", "this", "->", "client", "->", "sendReq...
Create Topic and Returns the Topic reference @param CreateTopicRequest $request : the TopicName and TopicAttributes @return CreateTopicResponse $response: the CreateTopicResponse @throws TopicAlreadyExistException if topic already exists @throws InvalidArgumentException if any argument value is invalid @throws MnsException if any other exception happends
[ "Create", "Topic", "and", "Returns", "the", "Topic", "reference" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L173-L178
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.deleteTopic
public function deleteTopic($topicName) { $request = new DeleteTopicRequest($topicName); $response = new DeleteTopicResponse(); return $this->client->sendRequest($request, $response); }
php
public function deleteTopic($topicName) { $request = new DeleteTopicRequest($topicName); $response = new DeleteTopicResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "deleteTopic", "(", "$", "topicName", ")", "{", "$", "request", "=", "new", "DeleteTopicRequest", "(", "$", "topicName", ")", ";", "$", "response", "=", "new", "DeleteTopicResponse", "(", ")", ";", "return", "$", "this", "->", "client...
Delete the specified topic the request will succeed even when the topic does not exist @param $topicName : the topicName @return DeleteTopicResponse
[ "Delete", "the", "specified", "topic", "the", "request", "will", "succeed", "even", "when", "the", "topic", "does", "not", "exist" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L189-L195
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Client.php
Client.listTopic
public function listTopic(ListTopicRequest $request) { $response = new ListTopicResponse(); return $this->client->sendRequest($request, $response); }
php
public function listTopic(ListTopicRequest $request) { $response = new ListTopicResponse(); return $this->client->sendRequest($request, $response); }
[ "public", "function", "listTopic", "(", "ListTopicRequest", "$", "request", ")", "{", "$", "response", "=", "new", "ListTopicResponse", "(", ")", ";", "return", "$", "this", "->", "client", "->", "sendRequest", "(", "$", "request", ",", "$", "response", ")...
Query the topics created by current account @param ListTopicRequest $request : define filters for quering topics @return ListTopicResponse: the response containing topicNames
[ "Query", "the", "topics", "created", "by", "current", "account" ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Client.php#L205-L210
train
AliyunOpenAPI/php-aliyun-open-api-mns
src/Common/XMLParser.php
XMLParser.parseNormalError
static function parseNormalError(\XMLReader $xmlReader) { $result = array( 'Code' => null, 'Message' => null, 'RequestId' => null, 'HostId' => null ); while ($xmlReader->Read()) { if ($xmlReader->nodeType == \XMLReader::ELEMENT) { switch ($xmlReader->name) { case 'Code': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['Code'] = $xmlReader->value; } break; case 'Message': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['Message'] = $xmlReader->value; } break; case 'RequestId': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['RequestId'] = $xmlReader->value; } break; case 'HostId': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['HostId'] = $xmlReader->value; } break; } } } return $result; }
php
static function parseNormalError(\XMLReader $xmlReader) { $result = array( 'Code' => null, 'Message' => null, 'RequestId' => null, 'HostId' => null ); while ($xmlReader->Read()) { if ($xmlReader->nodeType == \XMLReader::ELEMENT) { switch ($xmlReader->name) { case 'Code': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['Code'] = $xmlReader->value; } break; case 'Message': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['Message'] = $xmlReader->value; } break; case 'RequestId': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['RequestId'] = $xmlReader->value; } break; case 'HostId': $xmlReader->read(); if ($xmlReader->nodeType == \XMLReader::TEXT) { $result['HostId'] = $xmlReader->value; } break; } } } return $result; }
[ "static", "function", "parseNormalError", "(", "\\", "XMLReader", "$", "xmlReader", ")", "{", "$", "result", "=", "array", "(", "'Code'", "=>", "null", ",", "'Message'", "=>", "null", ",", "'RequestId'", "=>", "null", ",", "'HostId'", "=>", "null", ")", ...
Most of the error responses are in same format.
[ "Most", "of", "the", "error", "responses", "are", "in", "same", "format", "." ]
bceb8e02f99cac84f71aad69c8189803333a5f8b
https://github.com/AliyunOpenAPI/php-aliyun-open-api-mns/blob/bceb8e02f99cac84f71aad69c8189803333a5f8b/src/Common/XMLParser.php#L11-L46
train
vanilla/garden-container
src/Container.php
Container.arrayClone
private function arrayClone(array $array) { return array_map(function ($element) { return ((is_array($element)) ? $this->arrayClone($element) : ((is_object($element)) ? clone $element : $element ) ); }, $array); }
php
private function arrayClone(array $array) { return array_map(function ($element) { return ((is_array($element)) ? $this->arrayClone($element) : ((is_object($element)) ? clone $element : $element ) ); }, $array); }
[ "private", "function", "arrayClone", "(", "array", "$", "array", ")", "{", "return", "array_map", "(", "function", "(", "$", "element", ")", "{", "return", "(", "(", "is_array", "(", "$", "element", ")", ")", "?", "$", "this", "->", "arrayClone", "(", ...
Deep clone an array. @param array $array The array to clone. @return array Returns the cloned array. @see http://stackoverflow.com/a/17729234
[ "Deep", "clone", "an", "array", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L56-L66
train
vanilla/garden-container
src/Container.php
Container.rule
public function rule($id) { $id = $this->normalizeID($id); if (!isset($this->rules[$id])) { $this->rules[$id] = []; } $this->currentRuleName = $id; $this->currentRule = &$this->rules[$id]; return $this; }
php
public function rule($id) { $id = $this->normalizeID($id); if (!isset($this->rules[$id])) { $this->rules[$id] = []; } $this->currentRuleName = $id; $this->currentRule = &$this->rules[$id]; return $this; }
[ "public", "function", "rule", "(", "$", "id", ")", "{", "$", "id", "=", "$", "this", "->", "normalizeID", "(", "$", "id", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "rules", "[", "$", "id", "]", ")", ")", "{", "$", "this", "...
Set the current rule. @param string $id The ID of the rule. @return $this
[ "Set", "the", "current", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L93-L103
train
vanilla/garden-container
src/Container.php
Container.setAliasOf
public function setAliasOf($alias) { $alias = $this->normalizeID($alias); if ($alias === $this->currentRuleName) { trigger_error("You cannot set alias '$alias' to itself.", E_USER_NOTICE); } else { $this->currentRule['aliasOf'] = $alias; } return $this; }
php
public function setAliasOf($alias) { $alias = $this->normalizeID($alias); if ($alias === $this->currentRuleName) { trigger_error("You cannot set alias '$alias' to itself.", E_USER_NOTICE); } else { $this->currentRule['aliasOf'] = $alias; } return $this; }
[ "public", "function", "setAliasOf", "(", "$", "alias", ")", "{", "$", "alias", "=", "$", "this", "->", "normalizeID", "(", "$", "alias", ")", ";", "if", "(", "$", "alias", "===", "$", "this", "->", "currentRuleName", ")", "{", "trigger_error", "(", "...
Set the rule that the current rule is an alias of. @param string $alias The name of an entry in the container to point to. @return $this
[ "Set", "the", "rule", "that", "the", "current", "rule", "is", "an", "alias", "of", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L140-L149
train
vanilla/garden-container
src/Container.php
Container.addAlias
public function addAlias(...$alias) { foreach ($alias as $name) { $name = $this->normalizeID($name); if ($name === $this->currentRuleName) { trigger_error("Tried to set alias '$name' to self.", E_USER_NOTICE); } else { $this->rules[$name]['aliasOf'] = $this->currentRuleName; } } return $this; }
php
public function addAlias(...$alias) { foreach ($alias as $name) { $name = $this->normalizeID($name); if ($name === $this->currentRuleName) { trigger_error("Tried to set alias '$name' to self.", E_USER_NOTICE); } else { $this->rules[$name]['aliasOf'] = $this->currentRuleName; } } return $this; }
[ "public", "function", "addAlias", "(", "...", "$", "alias", ")", "{", "foreach", "(", "$", "alias", "as", "$", "name", ")", "{", "$", "name", "=", "$", "this", "->", "normalizeID", "(", "$", "name", ")", ";", "if", "(", "$", "name", "===", "$", ...
Add an alias of the current rule. Setting an alias to the current rule means that getting an item with the alias' name will be like getting the item with the current rule. If the current rule is shared then the same shared instance will be returned. You can add multiple aliases by passing additional arguments to this method. If {@link Container::addAlias()} is called with an alias that is the same as the current rule then an **E_USER_NOTICE** level error is raised and the alias is not added. @param string ...$alias The alias to set. @return $this @since 1.4 Added the ability to pass multiple aliases.
[ "Add", "an", "alias", "of", "the", "current", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L165-L176
train
vanilla/garden-container
src/Container.php
Container.removeAlias
public function removeAlias($alias) { $alias = $this->normalizeID($alias); if (!empty($this->rules[$alias]['aliasOf']) && $this->rules[$alias]['aliasOf'] !== $this->currentRuleName) { trigger_error("Alias '$alias' does not point to the current rule.", E_USER_NOTICE); } unset($this->rules[$alias]['aliasOf']); return $this; }
php
public function removeAlias($alias) { $alias = $this->normalizeID($alias); if (!empty($this->rules[$alias]['aliasOf']) && $this->rules[$alias]['aliasOf'] !== $this->currentRuleName) { trigger_error("Alias '$alias' does not point to the current rule.", E_USER_NOTICE); } unset($this->rules[$alias]['aliasOf']); return $this; }
[ "public", "function", "removeAlias", "(", "$", "alias", ")", "{", "$", "alias", "=", "$", "this", "->", "normalizeID", "(", "$", "alias", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "rules", "[", "$", "alias", "]", "[", "'aliasOf'", ...
Remove an alias of the current rule. If {@link Container::removeAlias()} is called with an alias that references a different rule then an **E_USER_NOTICE** level error is raised, but the alias is still removed. @param string $alias The alias to remove. @return $this
[ "Remove", "an", "alias", "of", "the", "current", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L187-L196
train
vanilla/garden-container
src/Container.php
Container.getAliases
public function getAliases() { $result = []; foreach ($this->rules as $name => $rule) { if (!empty($rule['aliasOf']) && $rule['aliasOf'] === $this->currentRuleName) { $result[] = $name; } } return $result; }
php
public function getAliases() { $result = []; foreach ($this->rules as $name => $rule) { if (!empty($rule['aliasOf']) && $rule['aliasOf'] === $this->currentRuleName) { $result[] = $name; } } return $result; }
[ "public", "function", "getAliases", "(", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "rules", "as", "$", "name", "=>", "$", "rule", ")", "{", "if", "(", "!", "empty", "(", "$", "rule", "[", "'aliasOf'", "]", ...
Get all of the aliases of the current rule. This method is intended to aid in debugging and should not be used in production as it walks the entire rule array. @return array Returns an array of strings representing aliases.
[ "Get", "all", "of", "the", "aliases", "of", "the", "current", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L205-L215
train
vanilla/garden-container
src/Container.php
Container.setInstance
public function setInstance($name, $instance) { $this->instances[$this->normalizeID($name)] = $instance; return $this; }
php
public function setInstance($name, $instance) { $this->instances[$this->normalizeID($name)] = $instance; return $this; }
[ "public", "function", "setInstance", "(", "$", "name", ",", "$", "instance", ")", "{", "$", "this", "->", "instances", "[", "$", "this", "->", "normalizeID", "(", "$", "name", ")", "]", "=", "$", "instance", ";", "return", "$", "this", ";", "}" ]
Set a specific shared instance into the container. When you set an instance into the container then it will always be returned by subsequent retrievals, even if a rule is configured that says that instances should not be shared. @param string $name The name of the container entry. @param mixed $instance This instance. @return $this
[ "Set", "a", "specific", "shared", "instance", "into", "the", "container", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L307-L310
train
vanilla/garden-container
src/Container.php
Container.makeRule
private function makeRule($nid) { $rule = isset($this->rules[$nid]) ? $this->rules[$nid] : []; if (class_exists($nid)) { for ($class = get_parent_class($nid); !empty($class); $class = get_parent_class($class)) { // Don't add the rule if it doesn't say to inherit. if (!isset($this->rules[$class]) || (isset($this->rules[$class]['inherit']) && !$this->rules[$class]['inherit'])) { break; } $rule += $this->rules[$class]; } // Add the default rule. if (!empty($this->rules['*']['inherit'])) { $rule += $this->rules['*']; } // Add interface calls to the rule. $interfaces = class_implements($nid); foreach ($interfaces as $interface) { if (isset($this->rules[$interface])) { $interfaceRule = $this->rules[$interface]; if (isset($interfaceRule['inherit']) && $interfaceRule['inherit'] === false) { continue; } if (!isset($rule['shared']) && isset($interfaceRule['shared'])) { $rule['shared'] = $interfaceRule['shared']; } if (!isset($rule['constructorArgs']) && isset($interfaceRule['constructorArgs'])) { $rule['constructorArgs'] = $interfaceRule['constructorArgs']; } if (!empty($interfaceRule['calls'])) { $rule['calls'] = array_merge( isset($rule['calls']) ? $rule['calls'] : [], $interfaceRule['calls'] ); } } } } elseif (!empty($this->rules['*']['inherit'])) { // Add the default rule. $rule += $this->rules['*']; } return $rule; }
php
private function makeRule($nid) { $rule = isset($this->rules[$nid]) ? $this->rules[$nid] : []; if (class_exists($nid)) { for ($class = get_parent_class($nid); !empty($class); $class = get_parent_class($class)) { // Don't add the rule if it doesn't say to inherit. if (!isset($this->rules[$class]) || (isset($this->rules[$class]['inherit']) && !$this->rules[$class]['inherit'])) { break; } $rule += $this->rules[$class]; } // Add the default rule. if (!empty($this->rules['*']['inherit'])) { $rule += $this->rules['*']; } // Add interface calls to the rule. $interfaces = class_implements($nid); foreach ($interfaces as $interface) { if (isset($this->rules[$interface])) { $interfaceRule = $this->rules[$interface]; if (isset($interfaceRule['inherit']) && $interfaceRule['inherit'] === false) { continue; } if (!isset($rule['shared']) && isset($interfaceRule['shared'])) { $rule['shared'] = $interfaceRule['shared']; } if (!isset($rule['constructorArgs']) && isset($interfaceRule['constructorArgs'])) { $rule['constructorArgs'] = $interfaceRule['constructorArgs']; } if (!empty($interfaceRule['calls'])) { $rule['calls'] = array_merge( isset($rule['calls']) ? $rule['calls'] : [], $interfaceRule['calls'] ); } } } } elseif (!empty($this->rules['*']['inherit'])) { // Add the default rule. $rule += $this->rules['*']; } return $rule; }
[ "private", "function", "makeRule", "(", "$", "nid", ")", "{", "$", "rule", "=", "isset", "(", "$", "this", "->", "rules", "[", "$", "nid", "]", ")", "?", "$", "this", "->", "rules", "[", "$", "nid", "]", ":", "[", "]", ";", "if", "(", "class_...
Make a rule based on an ID. @param string $nid A normalized ID. @return array Returns an array representing a rule.
[ "Make", "a", "rule", "based", "on", "an", "ID", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L365-L414
train
vanilla/garden-container
src/Container.php
Container.makeFactory
private function makeFactory($nid, array $rule) { $className = empty($rule['class']) ? $nid : $rule['class']; if (!empty($rule['factory'])) { // The instance is created with a user-supplied factory function. $callback = $rule['factory']; $function = $this->reflectCallback($callback); if ($function->getNumberOfParameters() > 0) { $callbackArgs = $this->makeDefaultArgs($function, (array)$rule['constructorArgs']); $factory = function ($args) use ($callback, $callbackArgs) { return call_user_func_array($callback, $this->resolveArgs($callbackArgs, $args)); }; } else { $factory = $callback; } // If a class is specified then still reflect on it so that calls can be made against it. if (class_exists($className)) { $class = new \ReflectionClass($className); } } else { // The instance is created by newing up a class. if (!class_exists($className)) { throw new NotFoundException("Class $className does not exist.", 404); } $class = new \ReflectionClass($className); $constructor = $class->getConstructor(); if ($constructor && $constructor->getNumberOfParameters() > 0) { $constructorArgs = $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs']); $factory = function ($args) use ($className, $constructorArgs) { return new $className(...array_values($this->resolveArgs($constructorArgs, $args))); }; } else { $factory = function () use ($className) { return new $className; }; } } // Add calls to the factory. if (isset($class) && !empty($rule['calls'])) { $calls = []; // Generate the calls array. foreach ($rule['calls'] as $call) { list($methodName, $args) = $call; $method = $class->getMethod($methodName); $calls[] = [$methodName, $this->makeDefaultArgs($method, $args)]; } // Wrap the factory in one that makes the calls. $factory = function ($args) use ($factory, $calls) { $instance = $factory($args); foreach ($calls as $call) { call_user_func_array( [$instance, $call[0]], $this->resolveArgs($call[1], [], $instance) ); } return $instance; }; } return $factory; }
php
private function makeFactory($nid, array $rule) { $className = empty($rule['class']) ? $nid : $rule['class']; if (!empty($rule['factory'])) { // The instance is created with a user-supplied factory function. $callback = $rule['factory']; $function = $this->reflectCallback($callback); if ($function->getNumberOfParameters() > 0) { $callbackArgs = $this->makeDefaultArgs($function, (array)$rule['constructorArgs']); $factory = function ($args) use ($callback, $callbackArgs) { return call_user_func_array($callback, $this->resolveArgs($callbackArgs, $args)); }; } else { $factory = $callback; } // If a class is specified then still reflect on it so that calls can be made against it. if (class_exists($className)) { $class = new \ReflectionClass($className); } } else { // The instance is created by newing up a class. if (!class_exists($className)) { throw new NotFoundException("Class $className does not exist.", 404); } $class = new \ReflectionClass($className); $constructor = $class->getConstructor(); if ($constructor && $constructor->getNumberOfParameters() > 0) { $constructorArgs = $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs']); $factory = function ($args) use ($className, $constructorArgs) { return new $className(...array_values($this->resolveArgs($constructorArgs, $args))); }; } else { $factory = function () use ($className) { return new $className; }; } } // Add calls to the factory. if (isset($class) && !empty($rule['calls'])) { $calls = []; // Generate the calls array. foreach ($rule['calls'] as $call) { list($methodName, $args) = $call; $method = $class->getMethod($methodName); $calls[] = [$methodName, $this->makeDefaultArgs($method, $args)]; } // Wrap the factory in one that makes the calls. $factory = function ($args) use ($factory, $calls) { $instance = $factory($args); foreach ($calls as $call) { call_user_func_array( [$instance, $call[0]], $this->resolveArgs($call[1], [], $instance) ); } return $instance; }; } return $factory; }
[ "private", "function", "makeFactory", "(", "$", "nid", ",", "array", "$", "rule", ")", "{", "$", "className", "=", "empty", "(", "$", "rule", "[", "'class'", "]", ")", "?", "$", "nid", ":", "$", "rule", "[", "'class'", "]", ";", "if", "(", "!", ...
Make a function that creates objects from a rule. @param string $nid The normalized ID of the container item. @param array $rule The resolved rule for the ID. @return \Closure Returns a function that when called will create a new instance of the class. @throws NotFoundException No entry was found for this identifier.
[ "Make", "a", "function", "that", "creates", "objects", "from", "a", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L424-L493
train
vanilla/garden-container
src/Container.php
Container.createSharedInstance
private function createSharedInstance($nid, array $rule, array $args) { if (!empty($rule['factory'])) { // The instance is created with a user-supplied factory function. $callback = $rule['factory']; $function = $this->reflectCallback($callback); if ($function->getNumberOfParameters() > 0) { $callbackArgs = $this->resolveArgs( $this->makeDefaultArgs($function, (array)$rule['constructorArgs']), $args ); $this->instances[$nid] = null; // prevent cyclic dependency from infinite loop. $this->instances[$nid] = $instance = call_user_func_array($callback, $callbackArgs); } else { $this->instances[$nid] = $instance = $callback(); } // Reflect on the instance so that calls can be made against it. if (is_object($instance)) { $class = new \ReflectionClass(get_class($instance)); } } else { $className = empty($rule['class']) ? $nid : $rule['class']; if (!class_exists($className)) { throw new NotFoundException("Class $className does not exist.", 404); } $class = new \ReflectionClass($className); $constructor = $class->getConstructor(); if ($constructor && $constructor->getNumberOfParameters() > 0) { // Instantiate the object first so that this instance can be used for cyclic dependencies. $this->instances[$nid] = $instance = $class->newInstanceWithoutConstructor(); $constructorArgs = $this->resolveArgs( $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs'], $rule), $args ); $constructor->invokeArgs($instance, $constructorArgs); } else { $this->instances[$nid] = $instance = new $class->name; } } // Call subsequent calls on the new object. if (isset($class) && !empty($rule['calls'])) { foreach ($rule['calls'] as $call) { list($methodName, $args) = $call; $method = $class->getMethod($methodName); $args = $this->resolveArgs( $this->makeDefaultArgs($method, $args, $rule), [], $instance ); $method->invokeArgs($instance, $args); } } return $instance; }
php
private function createSharedInstance($nid, array $rule, array $args) { if (!empty($rule['factory'])) { // The instance is created with a user-supplied factory function. $callback = $rule['factory']; $function = $this->reflectCallback($callback); if ($function->getNumberOfParameters() > 0) { $callbackArgs = $this->resolveArgs( $this->makeDefaultArgs($function, (array)$rule['constructorArgs']), $args ); $this->instances[$nid] = null; // prevent cyclic dependency from infinite loop. $this->instances[$nid] = $instance = call_user_func_array($callback, $callbackArgs); } else { $this->instances[$nid] = $instance = $callback(); } // Reflect on the instance so that calls can be made against it. if (is_object($instance)) { $class = new \ReflectionClass(get_class($instance)); } } else { $className = empty($rule['class']) ? $nid : $rule['class']; if (!class_exists($className)) { throw new NotFoundException("Class $className does not exist.", 404); } $class = new \ReflectionClass($className); $constructor = $class->getConstructor(); if ($constructor && $constructor->getNumberOfParameters() > 0) { // Instantiate the object first so that this instance can be used for cyclic dependencies. $this->instances[$nid] = $instance = $class->newInstanceWithoutConstructor(); $constructorArgs = $this->resolveArgs( $this->makeDefaultArgs($constructor, (array)$rule['constructorArgs'], $rule), $args ); $constructor->invokeArgs($instance, $constructorArgs); } else { $this->instances[$nid] = $instance = new $class->name; } } // Call subsequent calls on the new object. if (isset($class) && !empty($rule['calls'])) { foreach ($rule['calls'] as $call) { list($methodName, $args) = $call; $method = $class->getMethod($methodName); $args = $this->resolveArgs( $this->makeDefaultArgs($method, $args, $rule), [], $instance ); $method->invokeArgs($instance, $args); } } return $instance; }
[ "private", "function", "createSharedInstance", "(", "$", "nid", ",", "array", "$", "rule", ",", "array", "$", "args", ")", "{", "if", "(", "!", "empty", "(", "$", "rule", "[", "'factory'", "]", ")", ")", "{", "// The instance is created with a user-supplied ...
Create a shared instance of a class from a rule. This method has the side effect of adding the new instance to the internal instances array of this object. @param string $nid The normalized ID of the container item. @param array $rule The resolved rule for the ID. @param array $args Additional arguments passed during creation. @return object Returns the the new instance. @throws NotFoundException Throws an exception if the class does not exist.
[ "Create", "a", "shared", "instance", "of", "a", "class", "from", "a", "rule", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L506-L567
train
vanilla/garden-container
src/Container.php
Container.findRuleClass
private function findRuleClass($nid) { if (!isset($this->rules[$nid])) { return null; } elseif (!empty($this->rules[$nid]['aliasOf'])) { return $this->findRuleClass($this->rules[$nid]['aliasOf']); } elseif (!empty($this->rules[$nid]['class'])) { return $this->rules[$nid]['class']; } return null; }
php
private function findRuleClass($nid) { if (!isset($this->rules[$nid])) { return null; } elseif (!empty($this->rules[$nid]['aliasOf'])) { return $this->findRuleClass($this->rules[$nid]['aliasOf']); } elseif (!empty($this->rules[$nid]['class'])) { return $this->rules[$nid]['class']; } return null; }
[ "private", "function", "findRuleClass", "(", "$", "nid", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "rules", "[", "$", "nid", "]", ")", ")", "{", "return", "null", ";", "}", "elseif", "(", "!", "empty", "(", "$", "this", "->", "...
Find the class implemented by an ID. This tries to see if a rule exists for a normalized ID and what class it evaluates to. @param string $nid The normalized ID to look up. @return string|null Returns the name of the class associated with the rule or **null** if one could not be found.
[ "Find", "the", "class", "implemented", "by", "an", "ID", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L578-L588
train
vanilla/garden-container
src/Container.php
Container.makeDefaultArgs
private function makeDefaultArgs(\ReflectionFunctionAbstract $function, array $ruleArgs) { $ruleArgs = array_change_key_case($ruleArgs); $result = []; $pos = 0; foreach ($function->getParameters() as $i => $param) { $name = strtolower($param->name); $reflectedClass = null; try { $reflectedClass = $param->getClass(); } catch (\ReflectionException $e) { // If the class is not found in the autoloader a reflection exception is thrown. // Unless the parameter is optional we will want to rethrow. if (!$param->isOptional()) { throw new NotFoundException( "Could not find required constructor param $name in the autoloader.", 500, $e ); } } if (array_key_exists($name, $ruleArgs)) { $value = $ruleArgs[$name]; } elseif ($reflectedClass && isset($ruleArgs[$pos]) && // The argument is a reference that matches the type hint. (($ruleArgs[$pos] instanceof Reference && is_a($this->findRuleClass($ruleArgs[$pos]->getName()), $reflectedClass->getName(), true)) || // The argument is an instance that matches the type hint. (is_object($ruleArgs[$pos]) && is_a($ruleArgs[$pos], $reflectedClass->name))) ) { $value = $ruleArgs[$pos]; $pos++; } elseif ($reflectedClass && ($reflectedClass->isInstantiable() || isset($this->rules[$reflectedClass->name]) || array_key_exists($reflectedClass->name, $this->instances)) ) { $value = new DefaultReference($this->normalizeID($reflectedClass->name)); } elseif (array_key_exists($pos, $ruleArgs)) { $value = $ruleArgs[$pos]; $pos++; } elseif ($param->isDefaultValueAvailable()) { $value = $param->getDefaultValue(); } elseif ($param->isOptional()) { $value = null; } else { $value = new RequiredParameter($param); } $result[$name] = $value; } return $result; }
php
private function makeDefaultArgs(\ReflectionFunctionAbstract $function, array $ruleArgs) { $ruleArgs = array_change_key_case($ruleArgs); $result = []; $pos = 0; foreach ($function->getParameters() as $i => $param) { $name = strtolower($param->name); $reflectedClass = null; try { $reflectedClass = $param->getClass(); } catch (\ReflectionException $e) { // If the class is not found in the autoloader a reflection exception is thrown. // Unless the parameter is optional we will want to rethrow. if (!$param->isOptional()) { throw new NotFoundException( "Could not find required constructor param $name in the autoloader.", 500, $e ); } } if (array_key_exists($name, $ruleArgs)) { $value = $ruleArgs[$name]; } elseif ($reflectedClass && isset($ruleArgs[$pos]) && // The argument is a reference that matches the type hint. (($ruleArgs[$pos] instanceof Reference && is_a($this->findRuleClass($ruleArgs[$pos]->getName()), $reflectedClass->getName(), true)) || // The argument is an instance that matches the type hint. (is_object($ruleArgs[$pos]) && is_a($ruleArgs[$pos], $reflectedClass->name))) ) { $value = $ruleArgs[$pos]; $pos++; } elseif ($reflectedClass && ($reflectedClass->isInstantiable() || isset($this->rules[$reflectedClass->name]) || array_key_exists($reflectedClass->name, $this->instances)) ) { $value = new DefaultReference($this->normalizeID($reflectedClass->name)); } elseif (array_key_exists($pos, $ruleArgs)) { $value = $ruleArgs[$pos]; $pos++; } elseif ($param->isDefaultValueAvailable()) { $value = $param->getDefaultValue(); } elseif ($param->isOptional()) { $value = null; } else { $value = new RequiredParameter($param); } $result[$name] = $value; } return $result; }
[ "private", "function", "makeDefaultArgs", "(", "\\", "ReflectionFunctionAbstract", "$", "function", ",", "array", "$", "ruleArgs", ")", "{", "$", "ruleArgs", "=", "array_change_key_case", "(", "$", "ruleArgs", ")", ";", "$", "result", "=", "[", "]", ";", "$"...
Make an array of default arguments for a given function. @param \ReflectionFunctionAbstract $function The function to make the arguments for. @param array $ruleArgs An array of default arguments specifically for the function. @return array Returns an array in the form `name => defaultValue`. @throws NotFoundException If a non-optional class param is reflected and does not exist.
[ "Make", "an", "array", "of", "default", "arguments", "for", "a", "given", "function", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L598-L650
train
vanilla/garden-container
src/Container.php
Container.resolveArgs
private function resolveArgs(array $defaultArgs, array $args, $instance = null) { // First resolve all passed arguments so their types are known. $args = array_map( function ($arg) use ($instance) { return $arg instanceof ReferenceInterface ? $arg->resolve($this, $instance) : $arg; }, array_change_key_case($args) ); $pos = 0; foreach ($defaultArgs as $name => &$default) { if (array_key_exists($name, $args)) { // This is a named arg and should be used. $value = $args[$name]; } elseif (isset($args[$pos]) && (!($default instanceof DefaultReference) || empty($default->getClass()) || is_a($args[$pos], $default->getClass()))) { // There is an arg at this position and it's the same type as the default arg or the default arg is typeless. $value = $args[$pos]; $pos++; } else { // There is no passed arg, so use the default arg. $value = $default; } if ($value instanceof ReferenceInterface) { $value = $value->resolve($this, $instance); } $default = $value; } return $defaultArgs; }
php
private function resolveArgs(array $defaultArgs, array $args, $instance = null) { // First resolve all passed arguments so their types are known. $args = array_map( function ($arg) use ($instance) { return $arg instanceof ReferenceInterface ? $arg->resolve($this, $instance) : $arg; }, array_change_key_case($args) ); $pos = 0; foreach ($defaultArgs as $name => &$default) { if (array_key_exists($name, $args)) { // This is a named arg and should be used. $value = $args[$name]; } elseif (isset($args[$pos]) && (!($default instanceof DefaultReference) || empty($default->getClass()) || is_a($args[$pos], $default->getClass()))) { // There is an arg at this position and it's the same type as the default arg or the default arg is typeless. $value = $args[$pos]; $pos++; } else { // There is no passed arg, so use the default arg. $value = $default; } if ($value instanceof ReferenceInterface) { $value = $value->resolve($this, $instance); } $default = $value; } return $defaultArgs; }
[ "private", "function", "resolveArgs", "(", "array", "$", "defaultArgs", ",", "array", "$", "args", ",", "$", "instance", "=", "null", ")", "{", "// First resolve all passed arguments so their types are known.", "$", "args", "=", "array_map", "(", "function", "(", ...
Replace an array of default args with called args. @param array $defaultArgs The default arguments from {@link Container::makeDefaultArgs()}. @param array $args The arguments passed into a creation. @param mixed $instance An object instance if the arguments are being resolved on an already constructed object. @return array Returns an array suitable to be applied to a function call. @throws MissingArgumentException Throws an exception when a required parameter is missing.
[ "Replace", "an", "array", "of", "default", "args", "with", "called", "args", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L661-L692
train
vanilla/garden-container
src/Container.php
Container.createInstance
private function createInstance($nid, array $args) { $rule = $this->makeRule($nid); // Cache the instance or its factory for future use. if (empty($rule['shared'])) { $factory = $this->makeFactory($nid, $rule); $instance = $factory($args); $this->factories[$nid] = $factory; } else { $instance = $this->createSharedInstance($nid, $rule, $args); } return $instance; }
php
private function createInstance($nid, array $args) { $rule = $this->makeRule($nid); // Cache the instance or its factory for future use. if (empty($rule['shared'])) { $factory = $this->makeFactory($nid, $rule); $instance = $factory($args); $this->factories[$nid] = $factory; } else { $instance = $this->createSharedInstance($nid, $rule, $args); } return $instance; }
[ "private", "function", "createInstance", "(", "$", "nid", ",", "array", "$", "args", ")", "{", "$", "rule", "=", "$", "this", "->", "makeRule", "(", "$", "nid", ")", ";", "// Cache the instance or its factory for future use.", "if", "(", "empty", "(", "$", ...
Create an instance of a container item. This method either creates a new instance or returns an already created shared instance. @param string $nid The normalized ID of the container item. @param array $args Additional arguments to pass to the constructor. @return object Returns an object instance.
[ "Create", "an", "instance", "of", "a", "container", "item", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L703-L715
train
vanilla/garden-container
src/Container.php
Container.call
public function call(callable $callback, array $args = []) { $instance = null; if (is_array($callback)) { $function = new \ReflectionMethod($callback[0], $callback[1]); if (is_object($callback[0])) { $instance = $callback[0]; } } else { $function = new \ReflectionFunction($callback); } $args = $this->resolveArgs($this->makeDefaultArgs($function, $args), [], $instance); return call_user_func_array($callback, $args); }
php
public function call(callable $callback, array $args = []) { $instance = null; if (is_array($callback)) { $function = new \ReflectionMethod($callback[0], $callback[1]); if (is_object($callback[0])) { $instance = $callback[0]; } } else { $function = new \ReflectionFunction($callback); } $args = $this->resolveArgs($this->makeDefaultArgs($function, $args), [], $instance); return call_user_func_array($callback, $args); }
[ "public", "function", "call", "(", "callable", "$", "callback", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "instance", "=", "null", ";", "if", "(", "is_array", "(", "$", "callback", ")", ")", "{", "$", "function", "=", "new", "\\", ...
Call a callback with argument injection. @param callable $callback The callback to call. @param array $args Additional arguments to pass to the callback. @return mixed Returns the result of the callback. @throws ContainerException Throws an exception if the callback cannot be understood.
[ "Call", "a", "callback", "with", "argument", "injection", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L725-L741
train
vanilla/garden-container
src/Container.php
Container.hasRule
public function hasRule($id) { $id = $this->normalizeID($id); return !empty($this->rules[$id]); }
php
public function hasRule($id) { $id = $this->normalizeID($id); return !empty($this->rules[$id]); }
[ "public", "function", "hasRule", "(", "$", "id", ")", "{", "$", "id", "=", "$", "this", "->", "normalizeID", "(", "$", "id", ")", ";", "return", "!", "empty", "(", "$", "this", "->", "rules", "[", "$", "id", "]", ")", ";", "}" ]
Determines whether a rule has been defined at a given ID. @param string $id Identifier of the entry to look for. @return bool Returns **true** if a rule has been defined or **false** otherwise.
[ "Determines", "whether", "a", "rule", "has", "been", "defined", "at", "a", "given", "ID", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L762-L765
train
vanilla/garden-container
src/Container.php
Container.hasInstance
public function hasInstance($id) { $id = $this->normalizeID($id); return isset($this->instances[$id]); }
php
public function hasInstance($id) { $id = $this->normalizeID($id); return isset($this->instances[$id]); }
[ "public", "function", "hasInstance", "(", "$", "id", ")", "{", "$", "id", "=", "$", "this", "->", "normalizeID", "(", "$", "id", ")", ";", "return", "isset", "(", "$", "this", "->", "instances", "[", "$", "id", "]", ")", ";", "}" ]
Returns true if the container already has an instance for the given identifier. Returns false otherwise. @param string $id Identifier of the entry to look for. @return bool
[ "Returns", "true", "if", "the", "container", "already", "has", "an", "instance", "for", "the", "given", "identifier", ".", "Returns", "false", "otherwise", "." ]
aa467fdd050808a65a27a032d4d62d1b0e293ba6
https://github.com/vanilla/garden-container/blob/aa467fdd050808a65a27a032d4d62d1b0e293ba6/src/Container.php#L774-L778
train
ThaDafinser/UserAgentParser
src/Model/Version.php
Version.setComplete
public function setComplete($complete) { // check if the version has only 0 -> so no real result // maybe move this out to the Providers itself? $left = preg_replace('/[0._]/', '', $complete); if ($left === '') { $complete = null; } $this->hydrateFromComplete($complete); $this->complete = $complete; }
php
public function setComplete($complete) { // check if the version has only 0 -> so no real result // maybe move this out to the Providers itself? $left = preg_replace('/[0._]/', '', $complete); if ($left === '') { $complete = null; } $this->hydrateFromComplete($complete); $this->complete = $complete; }
[ "public", "function", "setComplete", "(", "$", "complete", ")", "{", "// check if the version has only 0 -> so no real result", "// maybe move this out to the Providers itself?", "$", "left", "=", "preg_replace", "(", "'/[0._]/'", ",", "''", ",", "$", "complete", ")", ";"...
Set from the complete version string. @param string $complete
[ "Set", "from", "the", "complete", "version", "string", "." ]
199cc8286e593e8e00b99e8df8144981ed948246
https://github.com/ThaDafinser/UserAgentParser/blob/199cc8286e593e8e00b99e8df8144981ed948246/src/Model/Version.php#L151-L163
train
drupal/core-utility
Rectangle.php
Rectangle.rotate
public function rotate($angle) { // PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148: To prevent buggy // behavior on negative multiples of 30 degrees we convert any negative // angle to a positive one between 0 and 360 degrees. $angle -= floor($angle / 360) * 360; // For some rotations that are multiple of 30 degrees, we need to correct // an imprecision between GD that uses C floats internally, and PHP that // uses C doubles. Also, for rotations that are not multiple of 90 degrees, // we need to introduce a correction factor of 0.5 to match the GD // algorithm used in PHP 5.5 (and above) to calculate the width and height // of the rotated image. if ((int) $angle == $angle && $angle % 90 == 0) { $imprecision = 0; $correction = 0; } else { $imprecision = -0.00001; $correction = 0.5; } // Do the trigonometry, applying imprecision fixes where needed. $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); $a = $this->width * $cos; $b = $this->height * $sin + $correction; $c = $this->width * $sin; $d = $this->height * $cos + $correction; if ((int) $angle == $angle && in_array($angle, [60, 150, 300])) { $a = $this->fixImprecision($a, $imprecision); $b = $this->fixImprecision($b, $imprecision); $c = $this->fixImprecision($c, $imprecision); $d = $this->fixImprecision($d, $imprecision); } // This is how GD on PHP5.5 calculates the new dimensions. $this->boundingWidth = abs((int) $a) + abs((int) $b); $this->boundingHeight = abs((int) $c) + abs((int) $d); return $this; }
php
public function rotate($angle) { // PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148: To prevent buggy // behavior on negative multiples of 30 degrees we convert any negative // angle to a positive one between 0 and 360 degrees. $angle -= floor($angle / 360) * 360; // For some rotations that are multiple of 30 degrees, we need to correct // an imprecision between GD that uses C floats internally, and PHP that // uses C doubles. Also, for rotations that are not multiple of 90 degrees, // we need to introduce a correction factor of 0.5 to match the GD // algorithm used in PHP 5.5 (and above) to calculate the width and height // of the rotated image. if ((int) $angle == $angle && $angle % 90 == 0) { $imprecision = 0; $correction = 0; } else { $imprecision = -0.00001; $correction = 0.5; } // Do the trigonometry, applying imprecision fixes where needed. $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); $a = $this->width * $cos; $b = $this->height * $sin + $correction; $c = $this->width * $sin; $d = $this->height * $cos + $correction; if ((int) $angle == $angle && in_array($angle, [60, 150, 300])) { $a = $this->fixImprecision($a, $imprecision); $b = $this->fixImprecision($b, $imprecision); $c = $this->fixImprecision($c, $imprecision); $d = $this->fixImprecision($d, $imprecision); } // This is how GD on PHP5.5 calculates the new dimensions. $this->boundingWidth = abs((int) $a) + abs((int) $b); $this->boundingHeight = abs((int) $c) + abs((int) $d); return $this; }
[ "public", "function", "rotate", "(", "$", "angle", ")", "{", "// PHP 5.5 GD bug: https://bugs.php.net/bug.php?id=65148: To prevent buggy", "// behavior on negative multiples of 30 degrees we convert any negative", "// angle to a positive one between 0 and 360 degrees.", "$", "angle", "-=",...
Rotates the rectangle. @param float $angle Rotation angle. @return $this
[ "Rotates", "the", "rectangle", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Rectangle.php#L83-L124
train
drupal/core-utility
Rectangle.php
Rectangle.fixImprecision
protected function fixImprecision($input, $imprecision) { if ($this->delta($input) < abs($imprecision)) { return $input + $imprecision; } return $input; }
php
protected function fixImprecision($input, $imprecision) { if ($this->delta($input) < abs($imprecision)) { return $input + $imprecision; } return $input; }
[ "protected", "function", "fixImprecision", "(", "$", "input", ",", "$", "imprecision", ")", "{", "if", "(", "$", "this", "->", "delta", "(", "$", "input", ")", "<", "abs", "(", "$", "imprecision", ")", ")", "{", "return", "$", "input", "+", "$", "i...
Performs an imprecision check on the input value and fixes it if needed. GD that uses C floats internally, whereas we at PHP level use C doubles. In some cases, we need to compensate imprecision. @param float $input The input value. @param float $imprecision The imprecision factor. @return float A value, where imprecision is added to input if the delta part of the input is lower than the absolute imprecision.
[ "Performs", "an", "imprecision", "check", "on", "the", "input", "value", "and", "fixes", "it", "if", "needed", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Rectangle.php#L141-L146
train
drupal/core-utility
UrlHelper.php
UrlHelper.buildQuery
public static function buildQuery(array $query, $parent = '') { $params = []; foreach ($query as $key => $value) { $key = ($parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key)); // Recurse into children. if (is_array($value)) { $params[] = static::buildQuery($value, $key); } // If a query parameter value is NULL, only append its key. elseif (!isset($value)) { $params[] = $key; } else { // For better readability of paths in query strings, we decode slashes. $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value)); } } return implode('&', $params); }
php
public static function buildQuery(array $query, $parent = '') { $params = []; foreach ($query as $key => $value) { $key = ($parent ? $parent . rawurlencode('[' . $key . ']') : rawurlencode($key)); // Recurse into children. if (is_array($value)) { $params[] = static::buildQuery($value, $key); } // If a query parameter value is NULL, only append its key. elseif (!isset($value)) { $params[] = $key; } else { // For better readability of paths in query strings, we decode slashes. $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value)); } } return implode('&', $params); }
[ "public", "static", "function", "buildQuery", "(", "array", "$", "query", ",", "$", "parent", "=", "''", ")", "{", "$", "params", "=", "[", "]", ";", "foreach", "(", "$", "query", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "key", "=", ...
Parses an array into a valid, rawurlencoded query string. rawurlencode() is RFC3986 compliant, and as a consequence RFC3987 compliant. The latter defines the required format of "URLs" in HTML5. urlencode() is almost the same as rawurlencode(), except that it encodes spaces as "+" instead of "%20". This makes its result non compliant to RFC3986 and as a consequence non compliant to RFC3987 and as a consequence not valid as a "URL" in HTML5. @todo Remove this function once PHP 5.4 is required as we can use just http_build_query() directly. @param array $query The query parameter array to be processed; for instance, \Drupal::request()->query->all(). @param string $parent (optional) Internal use only. Used to build the $query array key for nested items. Defaults to an empty string. @return string A rawurlencoded string which can be used as or appended to the URL query string. @ingroup php_wrappers
[ "Parses", "an", "array", "into", "a", "valid", "rawurlencoded", "query", "string", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/UrlHelper.php#L45-L66
train
drupal/core-utility
Random.php
Random.image
public function image($destination, $min_resolution, $max_resolution) { $extension = pathinfo($destination, PATHINFO_EXTENSION); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); // Make an image split into 4 sections with random colors. $im = imagecreate($width, $height); for ($n = 0; $n < 4; $n++) { $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $x = $width / 2 * ($n % 2); $y = $height / 2 * (int) ($n >= 2); imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color); } // Make a perfect circle in the image middle. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $smaller_dimension = min($width, $height); imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color); $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension); $save_function($im, $destination); return $destination; }
php
public function image($destination, $min_resolution, $max_resolution) { $extension = pathinfo($destination, PATHINFO_EXTENSION); $min = explode('x', $min_resolution); $max = explode('x', $max_resolution); $width = rand((int) $min[0], (int) $max[0]); $height = rand((int) $min[1], (int) $max[1]); // Make an image split into 4 sections with random colors. $im = imagecreate($width, $height); for ($n = 0; $n < 4; $n++) { $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $x = $width / 2 * ($n % 2); $y = $height / 2 * (int) ($n >= 2); imagefilledrectangle($im, $x, $y, $x + $width / 2, $y + $height / 2, $color); } // Make a perfect circle in the image middle. $color = imagecolorallocate($im, rand(0, 255), rand(0, 255), rand(0, 255)); $smaller_dimension = min($width, $height); imageellipse($im, $width / 2, $height / 2, $smaller_dimension, $smaller_dimension, $color); $save_function = 'image' . ($extension == 'jpg' ? 'jpeg' : $extension); $save_function($im, $destination); return $destination; }
[ "public", "function", "image", "(", "$", "destination", ",", "$", "min_resolution", ",", "$", "max_resolution", ")", "{", "$", "extension", "=", "pathinfo", "(", "$", "destination", ",", "PATHINFO_EXTENSION", ")", ";", "$", "min", "=", "explode", "(", "'x'...
Create a placeholder image. @param string $destination The absolute file path where the image should be stored. @param int $min_resolution @param int $max_resolution @return string Path to image file.
[ "Create", "a", "placeholder", "image", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Random.php#L271-L296
train
drupal/core-utility
Unicode.php
Unicode.setStatus
public static function setStatus($status) { if (!in_array($status, [static::STATUS_SINGLEBYTE, static::STATUS_MULTIBYTE, static::STATUS_ERROR])) { throw new \InvalidArgumentException('Invalid status value for unicode support.'); } static::$status = $status; }
php
public static function setStatus($status) { if (!in_array($status, [static::STATUS_SINGLEBYTE, static::STATUS_MULTIBYTE, static::STATUS_ERROR])) { throw new \InvalidArgumentException('Invalid status value for unicode support.'); } static::$status = $status; }
[ "public", "static", "function", "setStatus", "(", "$", "status", ")", "{", "if", "(", "!", "in_array", "(", "$", "status", ",", "[", "static", "::", "STATUS_SINGLEBYTE", ",", "static", "::", "STATUS_MULTIBYTE", ",", "static", "::", "STATUS_ERROR", "]", ")"...
Sets the value for multibyte support status for the current environment. The following status keys are supported: - \Drupal\Component\Utility\Unicode::STATUS_MULTIBYTE Full unicode support using an extension. - \Drupal\Component\Utility\Unicode::STATUS_SINGLEBYTE Standard PHP (emulated) unicode support. - \Drupal\Component\Utility\Unicode::STATUS_ERROR An error occurred. No unicode support. @param int $status The new status of multibyte support.
[ "Sets", "the", "value", "for", "multibyte", "support", "status", "for", "the", "current", "environment", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Unicode.php#L127-L132
train
drupal/core-utility
Html.php
Html.load
public static function load($html) { $document = <<<EOD <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head> <body>!html</body> </html> EOD; // PHP's \DOMDocument serialization adds extra whitespace when the markup // of the wrapping document contains newlines, so ensure we remove all // newlines before injecting the actual HTML body to be processed. $document = strtr($document, ["\n" => '', '!html' => $html]); $dom = new \DOMDocument(); // Ignore warnings during HTML soup loading. @$dom->loadHTML($document); return $dom; }
php
public static function load($html) { $document = <<<EOD <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head> <body>!html</body> </html> EOD; // PHP's \DOMDocument serialization adds extra whitespace when the markup // of the wrapping document contains newlines, so ensure we remove all // newlines before injecting the actual HTML body to be processed. $document = strtr($document, ["\n" => '', '!html' => $html]); $dom = new \DOMDocument(); // Ignore warnings during HTML soup loading. @$dom->loadHTML($document); return $dom; }
[ "public", "static", "function", "load", "(", "$", "html", ")", "{", "$", "document", "=", " <<<EOD\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head><meta http-equiv=\"Conte...
Parses an HTML snippet and returns it as a DOM object. This function loads the body part of a partial (X)HTML document and returns a full \DOMDocument object that represents this document. Use \Drupal\Component\Utility\Html::serialize() to serialize this \DOMDocument back to a string. @param string $html The partial (X)HTML snippet to load. Invalid markup will be corrected on import. @return \DOMDocument A \DOMDocument that represents the loaded (X)HTML snippet.
[ "Parses", "an", "HTML", "snippet", "and", "returns", "it", "as", "a", "DOM", "object", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Html.php#L273-L291
train
drupal/core-utility
Html.php
Html.transformRootRelativeUrlsToAbsolute
public static function transformRootRelativeUrlsToAbsolute($html, $scheme_and_host) { assert('empty(array_diff(array_keys(parse_url($scheme_and_host)), ["scheme", "host", "port"]))', '$scheme_and_host contains scheme, host and port at most.'); assert('isset(parse_url($scheme_and_host)["scheme"])', '$scheme_and_host is absolute and hence has a scheme.'); assert('isset(parse_url($scheme_and_host)["host"])', '$base_url is absolute and hence has a host.'); $html_dom = Html::load($html); $xpath = new \DOMXpath($html_dom); // Update all root-relative URLs to absolute URLs in the given HTML. foreach (static::$uriAttributes as $attr) { foreach ($xpath->query("//*[starts-with(@$attr, '/') and not(starts-with(@$attr, '//'))]") as $node) { $node->setAttribute($attr, $scheme_and_host . $node->getAttribute($attr)); } foreach ($xpath->query("//*[@srcset]") as $node) { // @see https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-srcset // @see https://html.spec.whatwg.org/multipage/embedded-content.html#image-candidate-string $image_candidate_strings = explode(',', $node->getAttribute('srcset')); $image_candidate_strings = array_map('trim', $image_candidate_strings); for ($i = 0; $i < count($image_candidate_strings); $i++) { $image_candidate_string = $image_candidate_strings[$i]; if ($image_candidate_string[0] === '/' && $image_candidate_string[1] !== '/') { $image_candidate_strings[$i] = $scheme_and_host . $image_candidate_string; } } $node->setAttribute('srcset', implode(', ', $image_candidate_strings)); } } return Html::serialize($html_dom); }
php
public static function transformRootRelativeUrlsToAbsolute($html, $scheme_and_host) { assert('empty(array_diff(array_keys(parse_url($scheme_and_host)), ["scheme", "host", "port"]))', '$scheme_and_host contains scheme, host and port at most.'); assert('isset(parse_url($scheme_and_host)["scheme"])', '$scheme_and_host is absolute and hence has a scheme.'); assert('isset(parse_url($scheme_and_host)["host"])', '$base_url is absolute and hence has a host.'); $html_dom = Html::load($html); $xpath = new \DOMXpath($html_dom); // Update all root-relative URLs to absolute URLs in the given HTML. foreach (static::$uriAttributes as $attr) { foreach ($xpath->query("//*[starts-with(@$attr, '/') and not(starts-with(@$attr, '//'))]") as $node) { $node->setAttribute($attr, $scheme_and_host . $node->getAttribute($attr)); } foreach ($xpath->query("//*[@srcset]") as $node) { // @see https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-srcset // @see https://html.spec.whatwg.org/multipage/embedded-content.html#image-candidate-string $image_candidate_strings = explode(',', $node->getAttribute('srcset')); $image_candidate_strings = array_map('trim', $image_candidate_strings); for ($i = 0; $i < count($image_candidate_strings); $i++) { $image_candidate_string = $image_candidate_strings[$i]; if ($image_candidate_string[0] === '/' && $image_candidate_string[1] !== '/') { $image_candidate_strings[$i] = $scheme_and_host . $image_candidate_string; } } $node->setAttribute('srcset', implode(', ', $image_candidate_strings)); } } return Html::serialize($html_dom); }
[ "public", "static", "function", "transformRootRelativeUrlsToAbsolute", "(", "$", "html", ",", "$", "scheme_and_host", ")", "{", "assert", "(", "'empty(array_diff(array_keys(parse_url($scheme_and_host)), [\"scheme\", \"host\", \"port\"]))'", ",", "'$scheme_and_host contains scheme, ho...
Converts all root-relative URLs to absolute URLs. Does not change any existing protocol-relative or absolute URLs. Does not change other relative URLs because they would result in different absolute URLs depending on the current path. For example: when the same content containing such a relative URL (for example 'image.png'), is served from its canonical URL (for example 'http://example.com/some-article') or from a listing or feed (for example 'http://example.com/all-articles') their "current path" differs, resulting in different absolute URLs: 'http://example.com/some-article/image.png' versus 'http://example.com/all-articles/image.png'. Only one can be correct. Therefore relative URLs that are not root-relative cannot be safely transformed and should generally be avoided. Necessary for HTML that is served outside of a website, for example, RSS and e-mail. @param string $html The partial (X)HTML snippet to load. Invalid markup will be corrected on import. @param string $scheme_and_host The root URL, which has a URI scheme, host and optional port. @return string The updated (X)HTML snippet.
[ "Converts", "all", "root", "-", "relative", "URLs", "to", "absolute", "URLs", "." ]
fb1c262da83fb691bcdf1680c3a69791a1d1a01a
https://github.com/drupal/core-utility/blob/fb1c262da83fb691bcdf1680c3a69791a1d1a01a/Html.php#L453-L481
train
bitpressio/blade-extensions
src/Container/BladeRegistrar.php
BladeRegistrar.register
public static function register($extension, $concrete = null) { app()->singleton($extension, $concrete); app()->tag($extension, 'blade.extension'); }
php
public static function register($extension, $concrete = null) { app()->singleton($extension, $concrete); app()->tag($extension, 'blade.extension'); }
[ "public", "static", "function", "register", "(", "$", "extension", ",", "$", "concrete", "=", "null", ")", "{", "app", "(", ")", "->", "singleton", "(", "$", "extension", ",", "$", "concrete", ")", ";", "app", "(", ")", "->", "tag", "(", "$", "exte...
Register and tag a blade service in the container @param string|array $abstract @param \Closure|string|null $concrete
[ "Register", "and", "tag", "a", "blade", "service", "in", "the", "container" ]
eeb4f3acb7253ee28302530c0bd25c5113248507
https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/Container/BladeRegistrar.php#L13-L17
train
axiom-labs/rivescript-php
src/Cortex/Tags/Tag.php
Tag.getMatches
protected function getMatches($source) { if ($this->hasMatches($source)) { preg_match_all($this->pattern, $source, $matches, PREG_SET_ORDER); return $matches; } }
php
protected function getMatches($source) { if ($this->hasMatches($source)) { preg_match_all($this->pattern, $source, $matches, PREG_SET_ORDER); return $matches; } }
[ "protected", "function", "getMatches", "(", "$", "source", ")", "{", "if", "(", "$", "this", "->", "hasMatches", "(", "$", "source", ")", ")", "{", "preg_match_all", "(", "$", "this", "->", "pattern", ",", "$", "source", ",", "$", "matches", ",", "PR...
Get the regular expression matches from the source. @param string $source @return array
[ "Get", "the", "regular", "expression", "matches", "from", "the", "source", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Tags/Tag.php#L60-L67
train
axiom-labs/rivescript-php
src/Cortex/Output.php
Output.process
public function process() { synapse()->brain->topic()->triggers()->each(function ($data, $trigger) { $this->searchTriggers($trigger); if ($this->output !== 'Error: Response could not be determined.') { return false; } }); return $this->output; }
php
public function process() { synapse()->brain->topic()->triggers()->each(function ($data, $trigger) { $this->searchTriggers($trigger); if ($this->output !== 'Error: Response could not be determined.') { return false; } }); return $this->output; }
[ "public", "function", "process", "(", ")", "{", "synapse", "(", ")", "->", "brain", "->", "topic", "(", ")", "->", "triggers", "(", ")", "->", "each", "(", "function", "(", "$", "data", ",", "$", "trigger", ")", "{", "$", "this", "->", "searchTrigg...
Process the correct output response by the interpreter. @return mixed
[ "Process", "the", "correct", "output", "response", "by", "the", "interpreter", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Output.php#L37-L48
train
axiom-labs/rivescript-php
src/Cortex/Output.php
Output.searchTriggers
protected function searchTriggers($trigger) { synapse()->triggers->each(function ($class) use ($trigger) { $triggerClass = "\\Axiom\\Rivescript\\Cortex\\Triggers\\$class"; $triggerClass = new $triggerClass(); $found = $triggerClass->parse($trigger, $this->input); if ($found === true) { $this->getResponse($trigger); return false; } }); }
php
protected function searchTriggers($trigger) { synapse()->triggers->each(function ($class) use ($trigger) { $triggerClass = "\\Axiom\\Rivescript\\Cortex\\Triggers\\$class"; $triggerClass = new $triggerClass(); $found = $triggerClass->parse($trigger, $this->input); if ($found === true) { $this->getResponse($trigger); return false; } }); }
[ "protected", "function", "searchTriggers", "(", "$", "trigger", ")", "{", "synapse", "(", ")", "->", "triggers", "->", "each", "(", "function", "(", "$", "class", ")", "use", "(", "$", "trigger", ")", "{", "$", "triggerClass", "=", "\"\\\\Axiom\\\\Rivescri...
Search through available triggers to find a possible match. @param string $trigger @return bool
[ "Search", "through", "available", "triggers", "to", "find", "a", "possible", "match", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Output.php#L57-L71
train
axiom-labs/rivescript-php
src/Cortex/Output.php
Output.getResponse
protected function getResponse($trigger) { $trigger = synapse()->brain->topic()->triggers()->get($trigger); if (isset($trigger['redirect'])) { return $this->getResponse($trigger['redirect']); } $key = array_rand($trigger['responses']); $this->output = $this->parseResponse($trigger['responses'][$key]); }
php
protected function getResponse($trigger) { $trigger = synapse()->brain->topic()->triggers()->get($trigger); if (isset($trigger['redirect'])) { return $this->getResponse($trigger['redirect']); } $key = array_rand($trigger['responses']); $this->output = $this->parseResponse($trigger['responses'][$key]); }
[ "protected", "function", "getResponse", "(", "$", "trigger", ")", "{", "$", "trigger", "=", "synapse", "(", ")", "->", "brain", "->", "topic", "(", ")", "->", "triggers", "(", ")", "->", "get", "(", "$", "trigger", ")", ";", "if", "(", "isset", "("...
Fetch a response from the found trigger. @param string $trigger; @return void
[ "Fetch", "a", "response", "from", "the", "found", "trigger", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Output.php#L80-L90
train
axiom-labs/rivescript-php
src/Rivescript.php
Rivescript.load
public function load($files) { $files = (! is_array($files)) ? (array) $files : $files; foreach ($files as $file) { synapse()->brain->teach($file); } }
php
public function load($files) { $files = (! is_array($files)) ? (array) $files : $files; foreach ($files as $file) { synapse()->brain->teach($file); } }
[ "public", "function", "load", "(", "$", "files", ")", "{", "$", "files", "=", "(", "!", "is_array", "(", "$", "files", ")", ")", "?", "(", "array", ")", "$", "files", ":", "$", "files", ";", "foreach", "(", "$", "files", "as", "$", "file", ")",...
Load RiveScript documents from files. @param array|string $files
[ "Load", "RiveScript", "documents", "from", "files", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Rivescript.php#L23-L30
train
axiom-labs/rivescript-php
src/Console/ChatCommand.php
ChatCommand.waitForUserInput
protected function waitForUserInput(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $question = new Question('<info>You > </info>'); $message = $helper->ask($input, $output, $question); $this->listenForConsoleCommands($input, $output, $message); $this->getBotResponse($input, $output, $message); }
php
protected function waitForUserInput(InputInterface $input, OutputInterface $output) { $helper = $this->getHelper('question'); $question = new Question('<info>You > </info>'); $message = $helper->ask($input, $output, $question); $this->listenForConsoleCommands($input, $output, $message); $this->getBotResponse($input, $output, $message); }
[ "protected", "function", "waitForUserInput", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "helper", "=", "$", "this", "->", "getHelper", "(", "'question'", ")", ";", "$", "question", "=", "new", "Question", "(", ...
Wait and listen for user input. @param InputInterface $input @param OutputInterface $output @return null
[ "Wait", "and", "listen", "for", "user", "input", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Console/ChatCommand.php#L78-L88
train
axiom-labs/rivescript-php
src/Console/ChatCommand.php
ChatCommand.listenForConsoleCommands
protected function listenForConsoleCommands(InputInterface $input, OutputInterface $output, $message) { if ($message === '/quit') { $output->writeln('Exiting...'); die(); } if ($message === '/reload') { return $this->execute($input, $output); } if ($message === '/help') { $output->writeln(''); $output->writeln('<comment>Usage:</comment>'); $output->writeln(' Type a message and press Return to send.'); $output->writeln(''); $output->writeln('<comment>Commands:</comment>'); $output->writeln(' <info>/help</info> Show this text'); $output->writeln(' <info>/reload</info> Reload the interactive console'); $output->writeln(' <info>/quit</info> Quit the interative console'); $output->writeln(''); $this->waitForUserInput($input, $output); } return null; }
php
protected function listenForConsoleCommands(InputInterface $input, OutputInterface $output, $message) { if ($message === '/quit') { $output->writeln('Exiting...'); die(); } if ($message === '/reload') { return $this->execute($input, $output); } if ($message === '/help') { $output->writeln(''); $output->writeln('<comment>Usage:</comment>'); $output->writeln(' Type a message and press Return to send.'); $output->writeln(''); $output->writeln('<comment>Commands:</comment>'); $output->writeln(' <info>/help</info> Show this text'); $output->writeln(' <info>/reload</info> Reload the interactive console'); $output->writeln(' <info>/quit</info> Quit the interative console'); $output->writeln(''); $this->waitForUserInput($input, $output); } return null; }
[ "protected", "function", "listenForConsoleCommands", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "$", "message", ")", "{", "if", "(", "$", "message", "===", "'/quit'", ")", "{", "$", "output", "->", "writeln", "(", "'Exit...
Listen for console commands before passing message to interpreter. @param InputInterface $input @param OutputInterface $output @param string $message @return null
[ "Listen", "for", "console", "commands", "before", "passing", "message", "to", "interpreter", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Console/ChatCommand.php#L98-L124
train
axiom-labs/rivescript-php
src/Console/ChatCommand.php
ChatCommand.getBotResponse
protected function getBotResponse(InputInterface $input, OutputInterface $output, $message) { $bot = 'Bot > '; $reply = $this->rivescript->reply($message); $response = "<info>{$reply}</info>"; $output->writeln($bot.$response); $this->waitForUserInput($input, $output); }
php
protected function getBotResponse(InputInterface $input, OutputInterface $output, $message) { $bot = 'Bot > '; $reply = $this->rivescript->reply($message); $response = "<info>{$reply}</info>"; $output->writeln($bot.$response); $this->waitForUserInput($input, $output); }
[ "protected", "function", "getBotResponse", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "$", "message", ")", "{", "$", "bot", "=", "'Bot > '", ";", "$", "reply", "=", "$", "this", "->", "rivescript", "->", "reply", "(", ...
Pass along user message to interpreter and fetch a reply. @param InputInterface $input @param OutputInterface $output @param string $message @return null
[ "Pass", "along", "user", "message", "to", "interpreter", "and", "fetch", "a", "reply", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Console/ChatCommand.php#L134-L143
train
axiom-labs/rivescript-php
src/Console/ChatCommand.php
ChatCommand.loadFiles
private function loadFiles($files) { if (is_dir($files)) { $directory = realpath($files); $files = []; $brains = glob($directory.'/*.rive'); foreach ($brains as $brain) { $files[] = $brain; } return $files; } return (array) $files; }
php
private function loadFiles($files) { if (is_dir($files)) { $directory = realpath($files); $files = []; $brains = glob($directory.'/*.rive'); foreach ($brains as $brain) { $files[] = $brain; } return $files; } return (array) $files; }
[ "private", "function", "loadFiles", "(", "$", "files", ")", "{", "if", "(", "is_dir", "(", "$", "files", ")", ")", "{", "$", "directory", "=", "realpath", "(", "$", "files", ")", ";", "$", "files", "=", "[", "]", ";", "$", "brains", "=", "glob", ...
Load and return an array of files. @param string $files @return array
[ "Load", "and", "return", "an", "array", "of", "files", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Console/ChatCommand.php#L151-L166
train
axiom-labs/rivescript-php
src/Cortex/Memory.php
Memory.user
public function user($user = 0) { if (! $this->user->has($user)) { $data = new Collection([]); $this->user->put($user, $data); } return $this->user->get($user); }
php
public function user($user = 0) { if (! $this->user->has($user)) { $data = new Collection([]); $this->user->put($user, $data); } return $this->user->get($user); }
[ "public", "function", "user", "(", "$", "user", "=", "0", ")", "{", "if", "(", "!", "$", "this", "->", "user", "->", "has", "(", "$", "user", ")", ")", "{", "$", "data", "=", "new", "Collection", "(", "[", "]", ")", ";", "$", "this", "->", ...
Stored user data. @return Collection
[ "Stored", "user", "data", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Memory.php#L91-L100
train
axiom-labs/rivescript-php
src/Cortex/Node.php
Node.determineCommand
protected function determineCommand() { if (mb_strlen($this->source) === 0) { $this->isInterrupted = true; return; } $this->command = mb_substr($this->source, 0, 1); }
php
protected function determineCommand() { if (mb_strlen($this->source) === 0) { $this->isInterrupted = true; return; } $this->command = mb_substr($this->source, 0, 1); }
[ "protected", "function", "determineCommand", "(", ")", "{", "if", "(", "mb_strlen", "(", "$", "this", "->", "source", ")", "===", "0", ")", "{", "$", "this", "->", "isInterrupted", "=", "true", ";", "return", ";", "}", "$", "this", "->", "command", "...
Determine the command type of the node. @return void
[ "Determine", "the", "command", "type", "of", "the", "node", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Node.php#L108-L117
train
axiom-labs/rivescript-php
src/Cortex/Node.php
Node.determineComment
protected function determineComment() { if (starts_with($this->source, '//')) { $this->isInterrupted = true; } elseif (starts_with($this->source, '#')) { log_warning('Using the # symbol for comments is deprecated'); $this->isInterrupted = true; } elseif (starts_with($this->source, '/*')) { if (ends_with($this->source, '*/')) { return; } $this->isComment = true; } elseif (ends_with($this->source, '*/')) { $this->isComment = false; } }
php
protected function determineComment() { if (starts_with($this->source, '//')) { $this->isInterrupted = true; } elseif (starts_with($this->source, '#')) { log_warning('Using the # symbol for comments is deprecated'); $this->isInterrupted = true; } elseif (starts_with($this->source, '/*')) { if (ends_with($this->source, '*/')) { return; } $this->isComment = true; } elseif (ends_with($this->source, '*/')) { $this->isComment = false; } }
[ "protected", "function", "determineComment", "(", ")", "{", "if", "(", "starts_with", "(", "$", "this", "->", "source", ",", "'//'", ")", ")", "{", "$", "this", "->", "isInterrupted", "=", "true", ";", "}", "elseif", "(", "starts_with", "(", "$", "this...
Determine if the current node source is a comment. @return void
[ "Determine", "if", "the", "current", "node", "source", "is", "a", "comment", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Node.php#L124-L139
train
Happyr/GoogleSiteAuthenticatorBundle
Controller/AdminController.php
AdminController.authenticateAction
public function authenticateAction(Request $request, $name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); // This will allow us to get refresh the token $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $request->getSession()->set(self::SESSION_KEY, $name); return $this->redirect($client->createAuthUrl()); }
php
public function authenticateAction(Request $request, $name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); // This will allow us to get refresh the token $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $request->getSession()->set(self::SESSION_KEY, $name); return $this->redirect($client->createAuthUrl()); }
[ "public", "function", "authenticateAction", "(", "Request", "$", "request", ",", "$", "name", ")", "{", "/* @var \\Google_Client $client */", "$", "clientProvider", "=", "$", "this", "->", "get", "(", "'happyr.google_site_authenticator.client_provider'", ")", ";", "$"...
This action starts the authentication. @param Request $request @param $name @return Response
[ "This", "action", "starts", "the", "authentication", "." ]
dcf0f9706ab0864a37b7d8296531fb2971176c55
https://github.com/Happyr/GoogleSiteAuthenticatorBundle/blob/dcf0f9706ab0864a37b7d8296531fb2971176c55/Controller/AdminController.php#L41-L54
train
Happyr/GoogleSiteAuthenticatorBundle
Controller/AdminController.php
AdminController.revokeAction
public function revokeAction($name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); $client->revokeToken(); $clientProvider->setAccessToken(null, $name); $this->get('session')->getFlashbag()->add('msg', 'Token was revoked.'); return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
php
public function revokeAction($name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); $client->revokeToken(); $clientProvider->setAccessToken(null, $name); $this->get('session')->getFlashbag()->add('msg', 'Token was revoked.'); return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
[ "public", "function", "revokeAction", "(", "$", "name", ")", "{", "/* @var \\Google_Client $client */", "$", "clientProvider", "=", "$", "this", "->", "get", "(", "'happyr.google_site_authenticator.client_provider'", ")", ";", "$", "client", "=", "$", "clientProvider"...
This action revokes the authentication token. This make sure the token can not be used on any other site. @param Request $request @param $name @return Response
[ "This", "action", "revokes", "the", "authentication", "token", ".", "This", "make", "sure", "the", "token", "can", "not", "be", "used", "on", "any", "other", "site", "." ]
dcf0f9706ab0864a37b7d8296531fb2971176c55
https://github.com/Happyr/GoogleSiteAuthenticatorBundle/blob/dcf0f9706ab0864a37b7d8296531fb2971176c55/Controller/AdminController.php#L64-L76
train
Happyr/GoogleSiteAuthenticatorBundle
Controller/AdminController.php
AdminController.removeAction
public function removeAction($name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $clientProvider->setAccessToken(null, $name); $this->get('session')->getFlashbag()->add('msg', 'Token was removed.'); return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
php
public function removeAction($name) { /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $clientProvider->setAccessToken(null, $name); $this->get('session')->getFlashbag()->add('msg', 'Token was removed.'); return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
[ "public", "function", "removeAction", "(", "$", "name", ")", "{", "/* @var \\Google_Client $client */", "$", "clientProvider", "=", "$", "this", "->", "get", "(", "'happyr.google_site_authenticator.client_provider'", ")", ";", "$", "clientProvider", "->", "setAccessToke...
This action removes the authentication token form the storage. @param Request $request @param $name @return Response
[ "This", "action", "removes", "the", "authentication", "token", "form", "the", "storage", "." ]
dcf0f9706ab0864a37b7d8296531fb2971176c55
https://github.com/Happyr/GoogleSiteAuthenticatorBundle/blob/dcf0f9706ab0864a37b7d8296531fb2971176c55/Controller/AdminController.php#L86-L95
train
Happyr/GoogleSiteAuthenticatorBundle
Controller/AdminController.php
AdminController.returnAction
public function returnAction(Request $request) { $name = $request->getSession()->get(self::SESSION_KEY, null); /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); $flashBag = $this->get('session')->getFlashbag(); if ($request->query->has('code')) { try { $client->authenticate($request->query->get('code')); $clientProvider->setAccessToken($client->getAccessToken(), $name); $flashBag->add('msg', 'Successfully authenticated!'); } catch (\Google_Auth_Exception $e) { $flashBag->add('error', $e->getMessage()); } } else { $flashBag->add('error', 'Authentication aborted.'); } return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
php
public function returnAction(Request $request) { $name = $request->getSession()->get(self::SESSION_KEY, null); /* @var \Google_Client $client */ $clientProvider = $this->get('happyr.google_site_authenticator.client_provider'); $client = $clientProvider->getClient($name); $flashBag = $this->get('session')->getFlashbag(); if ($request->query->has('code')) { try { $client->authenticate($request->query->get('code')); $clientProvider->setAccessToken($client->getAccessToken(), $name); $flashBag->add('msg', 'Successfully authenticated!'); } catch (\Google_Auth_Exception $e) { $flashBag->add('error', $e->getMessage()); } } else { $flashBag->add('error', 'Authentication aborted.'); } return $this->redirect($this->generateUrl('happyr.google_site_authenticator.index')); }
[ "public", "function", "returnAction", "(", "Request", "$", "request", ")", "{", "$", "name", "=", "$", "request", "->", "getSession", "(", ")", "->", "get", "(", "self", "::", "SESSION_KEY", ",", "null", ")", ";", "/* @var \\Google_Client $client */", "$", ...
This action is used when the user has authenticated with google. @param Request $request @return Response
[ "This", "action", "is", "used", "when", "the", "user", "has", "authenticated", "with", "google", "." ]
dcf0f9706ab0864a37b7d8296531fb2971176c55
https://github.com/Happyr/GoogleSiteAuthenticatorBundle/blob/dcf0f9706ab0864a37b7d8296531fb2971176c55/Controller/AdminController.php#L104-L127
train
Happyr/GoogleSiteAuthenticatorBundle
Model/TokenConfig.php
TokenConfig.getKey
public function getKey(string $key = null): string { if ($key === null) { return $this->defaultKey; } if (!isset($this->tokens[$key])) { throw new \LogicException(sprintf('Token with name %s could not be found', $key)); } return $key; }
php
public function getKey(string $key = null): string { if ($key === null) { return $this->defaultKey; } if (!isset($this->tokens[$key])) { throw new \LogicException(sprintf('Token with name %s could not be found', $key)); } return $key; }
[ "public", "function", "getKey", "(", "string", "$", "key", "=", "null", ")", ":", "string", "{", "if", "(", "$", "key", "===", "null", ")", "{", "return", "$", "this", "->", "defaultKey", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->",...
Get the key from the argument or the default key.
[ "Get", "the", "key", "from", "the", "argument", "or", "the", "default", "key", "." ]
dcf0f9706ab0864a37b7d8296531fb2971176c55
https://github.com/Happyr/GoogleSiteAuthenticatorBundle/blob/dcf0f9706ab0864a37b7d8296531fb2971176c55/Model/TokenConfig.php#L38-L49
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.createCard
public function createCard(BasePaymentForm $paymentForm, Order $order = null): CreditCard { $card = new CreditCard; if ($paymentForm instanceof CreditCardPaymentForm) { $this->populateCard($card, $paymentForm); } if ($order) { if ($billingAddress = $order->getBillingAddress()) { // Set top level names to the billing names $card->setFirstName($billingAddress->firstName); $card->setLastName($billingAddress->lastName); $card->setBillingFirstName($billingAddress->firstName); $card->setBillingLastName($billingAddress->lastName); $card->setBillingAddress1($billingAddress->address1); $card->setBillingAddress2($billingAddress->address2); $card->setBillingCity($billingAddress->city); $card->setBillingPostcode($billingAddress->zipCode); if ($billingAddress->getCountry()) { $card->setBillingCountry($billingAddress->getCountry()->iso); } if ($billingAddress->getState()) { $state = $billingAddress->getState()->abbreviation ?: $billingAddress->getState()->name; $card->setBillingState($state); } $card->setBillingPhone($billingAddress->phone); $card->setBillingCompany($billingAddress->businessName); $card->setCompany($billingAddress->businessName); } if ($shippingAddress = $order->getShippingAddress()) { $card->setShippingFirstName($shippingAddress->firstName); $card->setShippingLastName($shippingAddress->lastName); $card->setShippingAddress1($shippingAddress->address1); $card->setShippingAddress2($shippingAddress->address2); $card->setShippingCity($shippingAddress->city); $card->setShippingPostcode($shippingAddress->zipCode); if ($shippingAddress->getCountry()) { $card->setShippingCountry($shippingAddress->getCountry()->iso); } if ($shippingAddress->getState()) { $state = $shippingAddress->getState()->abbreviation ?: $shippingAddress->getState()->name; $card->setShippingState($state); } $card->setShippingPhone($shippingAddress->phone); $card->setShippingCompany($shippingAddress->businessName); } $card->setEmail($order->getEmail()); } return $card; }
php
public function createCard(BasePaymentForm $paymentForm, Order $order = null): CreditCard { $card = new CreditCard; if ($paymentForm instanceof CreditCardPaymentForm) { $this->populateCard($card, $paymentForm); } if ($order) { if ($billingAddress = $order->getBillingAddress()) { // Set top level names to the billing names $card->setFirstName($billingAddress->firstName); $card->setLastName($billingAddress->lastName); $card->setBillingFirstName($billingAddress->firstName); $card->setBillingLastName($billingAddress->lastName); $card->setBillingAddress1($billingAddress->address1); $card->setBillingAddress2($billingAddress->address2); $card->setBillingCity($billingAddress->city); $card->setBillingPostcode($billingAddress->zipCode); if ($billingAddress->getCountry()) { $card->setBillingCountry($billingAddress->getCountry()->iso); } if ($billingAddress->getState()) { $state = $billingAddress->getState()->abbreviation ?: $billingAddress->getState()->name; $card->setBillingState($state); } $card->setBillingPhone($billingAddress->phone); $card->setBillingCompany($billingAddress->businessName); $card->setCompany($billingAddress->businessName); } if ($shippingAddress = $order->getShippingAddress()) { $card->setShippingFirstName($shippingAddress->firstName); $card->setShippingLastName($shippingAddress->lastName); $card->setShippingAddress1($shippingAddress->address1); $card->setShippingAddress2($shippingAddress->address2); $card->setShippingCity($shippingAddress->city); $card->setShippingPostcode($shippingAddress->zipCode); if ($shippingAddress->getCountry()) { $card->setShippingCountry($shippingAddress->getCountry()->iso); } if ($shippingAddress->getState()) { $state = $shippingAddress->getState()->abbreviation ?: $shippingAddress->getState()->name; $card->setShippingState($state); } $card->setShippingPhone($shippingAddress->phone); $card->setShippingCompany($shippingAddress->businessName); } $card->setEmail($order->getEmail()); } return $card; }
[ "public", "function", "createCard", "(", "BasePaymentForm", "$", "paymentForm", ",", "Order", "$", "order", "=", "null", ")", ":", "CreditCard", "{", "$", "card", "=", "new", "CreditCard", ";", "if", "(", "$", "paymentForm", "instanceof", "CreditCardPaymentFor...
Create a card object using the payment form and the optional order @param BasePaymentForm $paymentForm @param Order $order @return CreditCard
[ "Create", "a", "card", "object", "using", "the", "payment", "form", "and", "the", "optional", "order" ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L189-L246
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.populateCard
public function populateCard($card, CreditCardPaymentForm $paymentForm) { if (!$card instanceof CreditCard) { return; } $card->setFirstName($paymentForm->firstName); $card->setLastName($paymentForm->lastName); $card->setNumber($paymentForm->number); $card->setExpiryMonth($paymentForm->month); $card->setExpiryYear($paymentForm->year); $card->setCvv($paymentForm->cvv); }
php
public function populateCard($card, CreditCardPaymentForm $paymentForm) { if (!$card instanceof CreditCard) { return; } $card->setFirstName($paymentForm->firstName); $card->setLastName($paymentForm->lastName); $card->setNumber($paymentForm->number); $card->setExpiryMonth($paymentForm->month); $card->setExpiryYear($paymentForm->year); $card->setCvv($paymentForm->cvv); }
[ "public", "function", "populateCard", "(", "$", "card", ",", "CreditCardPaymentForm", "$", "paymentForm", ")", "{", "if", "(", "!", "$", "card", "instanceof", "CreditCard", ")", "{", "return", ";", "}", "$", "card", "->", "setFirstName", "(", "$", "payment...
Populate a credit card from the paymnent form. @param CreditCard $card The credit card to populate. @param CreditCardPaymentForm $paymentForm The payment form. @return void
[ "Populate", "a", "credit", "card", "from", "the", "paymnent", "form", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L320-L332
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.createItemBagForOrder
protected function createItemBagForOrder(Order $order) { if (!$this->sendCartInfo) { return null; } $items = $this->getItemListForOrder($order); $itemBagClassName = $this->getItemBagClassName(); return new $itemBagClassName($items); }
php
protected function createItemBagForOrder(Order $order) { if (!$this->sendCartInfo) { return null; } $items = $this->getItemListForOrder($order); $itemBagClassName = $this->getItemBagClassName(); return new $itemBagClassName($items); }
[ "protected", "function", "createItemBagForOrder", "(", "Order", "$", "order", ")", "{", "if", "(", "!", "$", "this", "->", "sendCartInfo", ")", "{", "return", "null", ";", "}", "$", "items", "=", "$", "this", "->", "getItemListForOrder", "(", "$", "order...
Create a gateway specific item bag for the order. @param Order $order The order. @return ItemBag|null
[ "Create", "a", "gateway", "specific", "item", "bag", "for", "the", "order", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L472-L482
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.createPaymentRequest
protected function createPaymentRequest(Transaction $transaction, $card = null, $itemBag = null): array { $params = ['commerceTransactionId' => $transaction->id, 'commerceTransactionHash' => $transaction->hash]; $request = [ 'amount' => $transaction->paymentAmount, 'currency' => $transaction->paymentCurrency, 'transactionId' => $transaction->hash, 'description' => Craft::t('commerce', 'Order').' #'.$transaction->orderId, 'clientIp' => Craft::$app->getRequest()->userIP, 'transactionReference' => $transaction->hash, 'returnUrl' => UrlHelper::actionUrl('commerce/payments/complete-payment', $params), 'cancelUrl' => UrlHelper::siteUrl($transaction->order->cancelUrl), ]; // Set the webhook url. if ($this->supportsWebhooks()) { $request['notifyUrl'] = $this->getWebhookUrl($params); $request['notifyUrl'] = str_replace('rc.craft.local', 'umbushka.eu.ngrok.io', $request['notifyUrl']); } // Do not use IPv6 loopback if ($request['clientIp'] === '::1') { $request['clientIp'] = '127.0.0.1'; } // custom gateways may wish to access the order directly $request['order'] = $transaction->order; $request['orderId'] = $transaction->order->id; // Stripe only params $request['receiptEmail'] = $transaction->order->email; // Paypal only params $request['noShipping'] = 1; $request['allowNote'] = 0; $request['addressOverride'] = 1; $request['buttonSource'] = 'ccommerce_SP'; if ($card) { $request['card'] = $card; } if ($itemBag) { $request['items'] = $itemBag; } return $request; }
php
protected function createPaymentRequest(Transaction $transaction, $card = null, $itemBag = null): array { $params = ['commerceTransactionId' => $transaction->id, 'commerceTransactionHash' => $transaction->hash]; $request = [ 'amount' => $transaction->paymentAmount, 'currency' => $transaction->paymentCurrency, 'transactionId' => $transaction->hash, 'description' => Craft::t('commerce', 'Order').' #'.$transaction->orderId, 'clientIp' => Craft::$app->getRequest()->userIP, 'transactionReference' => $transaction->hash, 'returnUrl' => UrlHelper::actionUrl('commerce/payments/complete-payment', $params), 'cancelUrl' => UrlHelper::siteUrl($transaction->order->cancelUrl), ]; // Set the webhook url. if ($this->supportsWebhooks()) { $request['notifyUrl'] = $this->getWebhookUrl($params); $request['notifyUrl'] = str_replace('rc.craft.local', 'umbushka.eu.ngrok.io', $request['notifyUrl']); } // Do not use IPv6 loopback if ($request['clientIp'] === '::1') { $request['clientIp'] = '127.0.0.1'; } // custom gateways may wish to access the order directly $request['order'] = $transaction->order; $request['orderId'] = $transaction->order->id; // Stripe only params $request['receiptEmail'] = $transaction->order->email; // Paypal only params $request['noShipping'] = 1; $request['allowNote'] = 0; $request['addressOverride'] = 1; $request['buttonSource'] = 'ccommerce_SP'; if ($card) { $request['card'] = $card; } if ($itemBag) { $request['items'] = $itemBag; } return $request; }
[ "protected", "function", "createPaymentRequest", "(", "Transaction", "$", "transaction", ",", "$", "card", "=", "null", ",", "$", "itemBag", "=", "null", ")", ":", "array", "{", "$", "params", "=", "[", "'commerceTransactionId'", "=>", "$", "transaction", "-...
Create the parameters for a payment request based on a trasaction and optional card and item list. @param Transaction $transaction The transaction that is basis for this request. @param CreditCard $card The credit card being used @param ItemBag $itemBag The item list. @return array @throws \yii\base\Exception
[ "Create", "the", "parameters", "for", "a", "payment", "request", "based", "on", "a", "trasaction", "and", "optional", "card", "and", "item", "list", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L494-L542
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.createRequest
protected function createRequest(Transaction $transaction, BasePaymentForm $form = null) { // For authorize and capture we're referring to a transaction that already took place so no card or item shenanigans. if (in_array($transaction->type, [TransactionRecord::TYPE_REFUND, TransactionRecord::TYPE_CAPTURE], false)) { $request = $this->createPaymentRequest($transaction); } else { $order = $transaction->getOrder(); $card = null; if ($form) { $card = $this->createCard($form, $order); } $itemBag = $this->getItemBagForOrder($order); $request = $this->createPaymentRequest($transaction, $card, $itemBag); $this->populateRequest($request, $form); } return $request; }
php
protected function createRequest(Transaction $transaction, BasePaymentForm $form = null) { // For authorize and capture we're referring to a transaction that already took place so no card or item shenanigans. if (in_array($transaction->type, [TransactionRecord::TYPE_REFUND, TransactionRecord::TYPE_CAPTURE], false)) { $request = $this->createPaymentRequest($transaction); } else { $order = $transaction->getOrder(); $card = null; if ($form) { $card = $this->createCard($form, $order); } $itemBag = $this->getItemBagForOrder($order); $request = $this->createPaymentRequest($transaction, $card, $itemBag); $this->populateRequest($request, $form); } return $request; }
[ "protected", "function", "createRequest", "(", "Transaction", "$", "transaction", ",", "BasePaymentForm", "$", "form", "=", "null", ")", "{", "// For authorize and capture we're referring to a transaction that already took place so no card or item shenanigans.", "if", "(", "in_ar...
Prepare a request for execution by transaction and a populated payment form. @param Transaction $transaction @param BasePaymentForm $form Optional for capture/refund requests. @return mixed @throws \yii\base\Exception
[ "Prepare", "a", "request", "for", "execution", "by", "transaction", "and", "a", "populated", "payment", "form", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L554-L575
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.extractCardReference
protected function extractCardReference(ResponseInterface $response): string { if (!$response->isSuccessful()) { throw new PaymentException($response->getMessage()); } return (string) $response->getTransactionReference(); }
php
protected function extractCardReference(ResponseInterface $response): string { if (!$response->isSuccessful()) { throw new PaymentException($response->getMessage()); } return (string) $response->getTransactionReference(); }
[ "protected", "function", "extractCardReference", "(", "ResponseInterface", "$", "response", ")", ":", "string", "{", "if", "(", "!", "$", "response", "->", "isSuccessful", "(", ")", ")", "{", "throw", "new", "PaymentException", "(", "$", "response", "->", "g...
Extract a card reference from a response @param ResponseInterface $response The response to use @return string @throws PaymentException on failure
[ "Extract", "a", "card", "reference", "from", "a", "response" ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L585-L592
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.getItemBagForOrder
protected function getItemBagForOrder(Order $order) { $itemBag = $this->createItemBagForOrder($order); $event = new ItemBagEvent([ 'items' => $itemBag, 'order' => $order ]); $this->trigger(self::EVENT_AFTER_CREATE_ITEM_BAG, $event); return $event->items; }
php
protected function getItemBagForOrder(Order $order) { $itemBag = $this->createItemBagForOrder($order); $event = new ItemBagEvent([ 'items' => $itemBag, 'order' => $order ]); $this->trigger(self::EVENT_AFTER_CREATE_ITEM_BAG, $event); return $event->items; }
[ "protected", "function", "getItemBagForOrder", "(", "Order", "$", "order", ")", "{", "$", "itemBag", "=", "$", "this", "->", "createItemBagForOrder", "(", "$", "order", ")", ";", "$", "event", "=", "new", "ItemBagEvent", "(", "[", "'items'", "=>", "$", "...
Get the item bag for the order. @param Order $order @return mixed
[ "Get", "the", "item", "bag", "for", "the", "order", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L641-L652
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.getItemListForOrder
protected function getItemListForOrder(Order $order): array { $items = []; $priceCheck = 0; $count = -1; /** @var LineItem $item */ foreach ($order->lineItems as $item) { $price = Currency::round($item->salePrice); // Can not accept zero amount items. See item (4) here: // https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page if ($price !== 0) { $count++; /** @var Purchasable $purchasable */ $purchasable = $item->getPurchasable(); $defaultDescription = Craft::t('commerce', 'Item ID').' '.$item->id; $purchasableDescription = $purchasable ? $purchasable->getDescription() : $defaultDescription; $description = isset($item->snapshot['description']) ? $item->snapshot['description'] : $purchasableDescription; $description = empty($description) ? 'Item '.$count : $description; $items[] = [ 'name' => $description, 'description' => $description, 'quantity' => $item->qty, 'price' => $price, ]; $priceCheck += ($item->qty * $item->salePrice); } } $count = -1; /** @var OrderAdjustment $adjustment */ foreach ($order->adjustments as $adjustment) { $price = Currency::round($adjustment->amount); // Do not include the 'included' adjustments, and do not send zero value items // See item (4) https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page if (($adjustment->included == 0 || $adjustment->included == false) && $price !== 0) { $count++; $items[] = [ 'name' => empty($adjustment->name) ? $adjustment->type." ".$count : $adjustment->name, 'description' => empty($adjustment->description) ? $adjustment->type.' '.$count : $adjustment->description, 'quantity' => 1, 'price' => $price, ]; $priceCheck += $adjustment->amount; } } $priceCheck = Currency::round($priceCheck); $totalPrice = Currency::round($order->totalPrice); $same = (bool)($priceCheck === $totalPrice); if (!$same) { Craft::error('Item bag total price does not equal the orders totalPrice, some payment gateways will complain.', __METHOD__); } return $items; }
php
protected function getItemListForOrder(Order $order): array { $items = []; $priceCheck = 0; $count = -1; /** @var LineItem $item */ foreach ($order->lineItems as $item) { $price = Currency::round($item->salePrice); // Can not accept zero amount items. See item (4) here: // https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page if ($price !== 0) { $count++; /** @var Purchasable $purchasable */ $purchasable = $item->getPurchasable(); $defaultDescription = Craft::t('commerce', 'Item ID').' '.$item->id; $purchasableDescription = $purchasable ? $purchasable->getDescription() : $defaultDescription; $description = isset($item->snapshot['description']) ? $item->snapshot['description'] : $purchasableDescription; $description = empty($description) ? 'Item '.$count : $description; $items[] = [ 'name' => $description, 'description' => $description, 'quantity' => $item->qty, 'price' => $price, ]; $priceCheck += ($item->qty * $item->salePrice); } } $count = -1; /** @var OrderAdjustment $adjustment */ foreach ($order->adjustments as $adjustment) { $price = Currency::round($adjustment->amount); // Do not include the 'included' adjustments, and do not send zero value items // See item (4) https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#setting-order-details-on-the-paypal-review-page if (($adjustment->included == 0 || $adjustment->included == false) && $price !== 0) { $count++; $items[] = [ 'name' => empty($adjustment->name) ? $adjustment->type." ".$count : $adjustment->name, 'description' => empty($adjustment->description) ? $adjustment->type.' '.$count : $adjustment->description, 'quantity' => 1, 'price' => $price, ]; $priceCheck += $adjustment->amount; } } $priceCheck = Currency::round($priceCheck); $totalPrice = Currency::round($order->totalPrice); $same = (bool)($priceCheck === $totalPrice); if (!$same) { Craft::error('Item bag total price does not equal the orders totalPrice, some payment gateways will complain.', __METHOD__); } return $items; }
[ "protected", "function", "getItemListForOrder", "(", "Order", "$", "order", ")", ":", "array", "{", "$", "items", "=", "[", "]", ";", "$", "priceCheck", "=", "0", ";", "$", "count", "=", "-", "1", ";", "/** @var LineItem $item */", "foreach", "(", "$", ...
Generate the item list for an Order. @param Order $order @return array
[ "Generate", "the", "item", "list", "for", "an", "Order", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L661-L722
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.performRequest
protected function performRequest($request, $transaction): RequestResponseInterface { //raising event $event = new GatewayRequestEvent([ 'type' => $transaction->type, 'request' => $request, 'transaction' => $transaction ]); // Raise 'beforeGatewayRequestSend' event $this->trigger(self::EVENT_BEFORE_GATEWAY_REQUEST_SEND, $event); $response = $this->sendRequest($request); return $this->prepareResponse($response, $transaction); }
php
protected function performRequest($request, $transaction): RequestResponseInterface { //raising event $event = new GatewayRequestEvent([ 'type' => $transaction->type, 'request' => $request, 'transaction' => $transaction ]); // Raise 'beforeGatewayRequestSend' event $this->trigger(self::EVENT_BEFORE_GATEWAY_REQUEST_SEND, $event); $response = $this->sendRequest($request); return $this->prepareResponse($response, $transaction); }
[ "protected", "function", "performRequest", "(", "$", "request", ",", "$", "transaction", ")", ":", "RequestResponseInterface", "{", "//raising event", "$", "event", "=", "new", "GatewayRequestEvent", "(", "[", "'type'", "=>", "$", "transaction", "->", "type", ",...
Perform a request and return the response. @param $request @param $transaction @return RequestResponseInterface @throws GatewayRequestCancelledException
[ "Perform", "a", "request", "and", "return", "the", "response", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L733-L748
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.prepareCaptureRequest
protected function prepareCaptureRequest($request, string $reference): RequestInterface { /** @var AbstractRequest $captureRequest */ $captureRequest = $this->gateway()->capture($request); $captureRequest->setTransactionReference($reference); return $captureRequest; }
php
protected function prepareCaptureRequest($request, string $reference): RequestInterface { /** @var AbstractRequest $captureRequest */ $captureRequest = $this->gateway()->capture($request); $captureRequest->setTransactionReference($reference); return $captureRequest; }
[ "protected", "function", "prepareCaptureRequest", "(", "$", "request", ",", "string", "$", "reference", ")", ":", "RequestInterface", "{", "/** @var AbstractRequest $captureRequest */", "$", "captureRequest", "=", "$", "this", "->", "gateway", "(", ")", "->", "captu...
Prepare a capture request from request data and reference of the transaction being captured. @param array $request @param string $reference @return RequestInterface
[ "Prepare", "a", "capture", "request", "from", "request", "data", "and", "reference", "of", "the", "transaction", "being", "captured", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L794-L801
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.prepareRefundRequest
protected function prepareRefundRequest($request, string $reference): RequestInterface { /** @var AbstractRequest $refundRequest */ $refundRequest = $this->gateway()->refund($request); $refundRequest->setTransactionReference($reference); return $refundRequest; }
php
protected function prepareRefundRequest($request, string $reference): RequestInterface { /** @var AbstractRequest $refundRequest */ $refundRequest = $this->gateway()->refund($request); $refundRequest->setTransactionReference($reference); return $refundRequest; }
[ "protected", "function", "prepareRefundRequest", "(", "$", "request", ",", "string", "$", "reference", ")", ":", "RequestInterface", "{", "/** @var AbstractRequest $refundRequest */", "$", "refundRequest", "=", "$", "this", "->", "gateway", "(", ")", "->", "refund",...
Prepare a refund request from request data and reference of the transaction being refunded. @param array $request @param string $reference @return RequestInterface
[ "Prepare", "a", "refund", "request", "from", "request", "data", "and", "reference", "of", "the", "transaction", "being", "refunded", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L837-L845
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.sendRequest
protected function sendRequest(RequestInterface $request): ResponseInterface { $data = $request->getData(); $event = new SendPaymentRequestEvent([ 'requestData' => $data ]); // Raise 'beforeSendPaymentRequest' event $this->trigger(self::EVENT_BEFORE_SEND_PAYMENT_REQUEST, $event); // We can't merge the $data with $modifiedData since the $data is not always an array. // For example it could be a XML object, json, or anything else really. if ($event->modifiedRequestData !== null) { return $request->sendData($event->modifiedRequestData); } return $request->send(); }
php
protected function sendRequest(RequestInterface $request): ResponseInterface { $data = $request->getData(); $event = new SendPaymentRequestEvent([ 'requestData' => $data ]); // Raise 'beforeSendPaymentRequest' event $this->trigger(self::EVENT_BEFORE_SEND_PAYMENT_REQUEST, $event); // We can't merge the $data with $modifiedData since the $data is not always an array. // For example it could be a XML object, json, or anything else really. if ($event->modifiedRequestData !== null) { return $request->sendData($event->modifiedRequestData); } return $request->send(); }
[ "protected", "function", "sendRequest", "(", "RequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "$", "data", "=", "$", "request", "->", "getData", "(", ")", ";", "$", "event", "=", "new", "SendPaymentRequestEvent", "(", "[", "'requestData'...
Send a request to the actual gateway. @param RequestInterface $request @return ResponseInterface
[ "Send", "a", "request", "to", "the", "actual", "gateway", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L854-L872
train
craftcms/commerce-omnipay
src/base/Gateway.php
Gateway.createOmnipayGateway
protected static function createOmnipayGateway(string $gatewayClassName): GatewayInterface { $craftClient = Craft::createGuzzleClient(); $adapter = new Client($craftClient); $httpClient = new OmnipayClient($adapter); return Omnipay::create($gatewayClassName, $httpClient); }
php
protected static function createOmnipayGateway(string $gatewayClassName): GatewayInterface { $craftClient = Craft::createGuzzleClient(); $adapter = new Client($craftClient); $httpClient = new OmnipayClient($adapter); return Omnipay::create($gatewayClassName, $httpClient); }
[ "protected", "static", "function", "createOmnipayGateway", "(", "string", "$", "gatewayClassName", ")", ":", "GatewayInterface", "{", "$", "craftClient", "=", "Craft", "::", "createGuzzleClient", "(", ")", ";", "$", "adapter", "=", "new", "Client", "(", "$", "...
Create the omnipay gateway. @param string $gatewayClassName @return GatewayInterface
[ "Create", "the", "omnipay", "gateway", "." ]
91fd24ebe3fc19a776915e7636e432a41d7deace
https://github.com/craftcms/commerce-omnipay/blob/91fd24ebe3fc19a776915e7636e432a41d7deace/src/base/Gateway.php#L880-L887
train
ddeboer/transcoder
src/Transcoder.php
Transcoder.create
public static function create($defaultEncoding = 'UTF-8') { if (isset(self::$chain[$defaultEncoding])) { return self::$chain[$defaultEncoding]; } $transcoders = []; try { $transcoders[] = new MbTranscoder($defaultEncoding); } catch (ExtensionMissingException $mb) { // Ignore missing mbstring extension; fall back to iconv } try { $transcoders[] = new IconvTranscoder($defaultEncoding); } catch (ExtensionMissingException $iconv) { // Neither mbstring nor iconv throw $iconv; } self::$chain[$defaultEncoding] = new self($transcoders); return self::$chain[$defaultEncoding]; }
php
public static function create($defaultEncoding = 'UTF-8') { if (isset(self::$chain[$defaultEncoding])) { return self::$chain[$defaultEncoding]; } $transcoders = []; try { $transcoders[] = new MbTranscoder($defaultEncoding); } catch (ExtensionMissingException $mb) { // Ignore missing mbstring extension; fall back to iconv } try { $transcoders[] = new IconvTranscoder($defaultEncoding); } catch (ExtensionMissingException $iconv) { // Neither mbstring nor iconv throw $iconv; } self::$chain[$defaultEncoding] = new self($transcoders); return self::$chain[$defaultEncoding]; }
[ "public", "static", "function", "create", "(", "$", "defaultEncoding", "=", "'UTF-8'", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "chain", "[", "$", "defaultEncoding", "]", ")", ")", "{", "return", "self", "::", "$", "chain", "[", "$", "de...
Create a transcoder @param string $defaultEncoding @return TranscoderInterface @throws ExtensionMissingException
[ "Create", "a", "transcoder" ]
e56652fe3b97908def6f53d97498952bbf13a9f6
https://github.com/ddeboer/transcoder/blob/e56652fe3b97908def6f53d97498952bbf13a9f6/src/Transcoder.php#L47-L71
train
axiom-labs/rivescript-php
src/Cortex/Tags/Bot.php
Bot.parse
public function parse($source, Input $input) { if (! $this->sourceAllowed()) { return $source; } if ($this->hasMatches($source)) { $matches = $this->getMatches($source); $variables = synapse()->memory->variables(); foreach ($matches as $match) { $source = str_replace($match[0], $variables[$match[1]], $source); } } return $source; }
php
public function parse($source, Input $input) { if (! $this->sourceAllowed()) { return $source; } if ($this->hasMatches($source)) { $matches = $this->getMatches($source); $variables = synapse()->memory->variables(); foreach ($matches as $match) { $source = str_replace($match[0], $variables[$match[1]], $source); } } return $source; }
[ "public", "function", "parse", "(", "$", "source", ",", "Input", "$", "input", ")", "{", "if", "(", "!", "$", "this", "->", "sourceAllowed", "(", ")", ")", "{", "return", "$", "source", ";", "}", "if", "(", "$", "this", "->", "hasMatches", "(", "...
Parse the source. @param string $source @return string
[ "Parse", "the", "source", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Tags/Bot.php#L28-L44
train
bitpressio/blade-extensions
src/BladeExtensionServiceProvider.php
BladeExtensionServiceProvider.defineBladeExtensions
protected function defineBladeExtensions() { foreach ($this->app->tagged('blade.extension') as $extension) { if (! $extension instanceof BladeExtension) { throw new InvalidBladeExtension($extension); } foreach ($extension->getDirectives() as $name => $callable) { $this->app['blade.compiler']->directive($name, $callable); } foreach ($extension->getConditionals() as $name => $callable) { $this->app['blade.compiler']->if($name, $callable); } } }
php
protected function defineBladeExtensions() { foreach ($this->app->tagged('blade.extension') as $extension) { if (! $extension instanceof BladeExtension) { throw new InvalidBladeExtension($extension); } foreach ($extension->getDirectives() as $name => $callable) { $this->app['blade.compiler']->directive($name, $callable); } foreach ($extension->getConditionals() as $name => $callable) { $this->app['blade.compiler']->if($name, $callable); } } }
[ "protected", "function", "defineBladeExtensions", "(", ")", "{", "foreach", "(", "$", "this", "->", "app", "->", "tagged", "(", "'blade.extension'", ")", "as", "$", "extension", ")", "{", "if", "(", "!", "$", "extension", "instanceof", "BladeExtension", ")",...
Register Blade Extension directives and conditionals with the blade compiler @return void
[ "Register", "Blade", "Extension", "directives", "and", "conditionals", "with", "the", "blade", "compiler" ]
eeb4f3acb7253ee28302530c0bd25c5113248507
https://github.com/bitpressio/blade-extensions/blob/eeb4f3acb7253ee28302530c0bd25c5113248507/src/BladeExtensionServiceProvider.php#L48-L63
train
axiom-labs/rivescript-php
src/Cortex/Commands/Trigger.php
Trigger.determineTriggerType
protected function determineTriggerType($trigger) { $wildcards = [ 'alphabetic' => '/_/', 'numeric' => '/#/', 'global' => '/\*/', ]; foreach ($wildcards as $type => $pattern) { if (@preg_match_all($pattern, $trigger, $stars)) { return $type; } } return 'atomic'; }
php
protected function determineTriggerType($trigger) { $wildcards = [ 'alphabetic' => '/_/', 'numeric' => '/#/', 'global' => '/\*/', ]; foreach ($wildcards as $type => $pattern) { if (@preg_match_all($pattern, $trigger, $stars)) { return $type; } } return 'atomic'; }
[ "protected", "function", "determineTriggerType", "(", "$", "trigger", ")", "{", "$", "wildcards", "=", "[", "'alphabetic'", "=>", "'/_/'", ",", "'numeric'", "=>", "'/#/'", ",", "'global'", "=>", "'/\\*/'", ",", "]", ";", "foreach", "(", "$", "wildcards", "...
Determine the type of trigger to aid in sorting. @param string $trigger @return string
[ "Determine", "the", "type", "of", "trigger", "to", "aid", "in", "sorting", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Commands/Trigger.php#L45-L60
train
axiom-labs/rivescript-php
src/Cortex/Commands/Trigger.php
Trigger.sortTriggers
protected function sortTriggers($triggers) { $triggers = $this->determineWordCount($triggers); $triggers = $this->determineTypeCount($triggers); $triggers = $triggers->sort(function ($current, $previous) { return ($current['order'] < $previous['order']) ? -1 : 1; })->reverse(); return $triggers; }
php
protected function sortTriggers($triggers) { $triggers = $this->determineWordCount($triggers); $triggers = $this->determineTypeCount($triggers); $triggers = $triggers->sort(function ($current, $previous) { return ($current['order'] < $previous['order']) ? -1 : 1; })->reverse(); return $triggers; }
[ "protected", "function", "sortTriggers", "(", "$", "triggers", ")", "{", "$", "triggers", "=", "$", "this", "->", "determineWordCount", "(", "$", "triggers", ")", ";", "$", "triggers", "=", "$", "this", "->", "determineTypeCount", "(", "$", "triggers", ")"...
Sort triggers based on type and word count from largest to smallest. @param Collection $triggers @return Collection
[ "Sort", "triggers", "based", "on", "type", "and", "word", "count", "from", "largest", "to", "smallest", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Commands/Trigger.php#L70-L80
train
axiom-labs/rivescript-php
src/Cortex/Commands/Trigger.php
Trigger.determineWordCount
protected function determineWordCount($triggers) { $triggers = $triggers->each(function ($data, $trigger) use ($triggers) { $data['order'] = count(explode(' ', $trigger)); $triggers->put($trigger, $data); }); return $triggers; }
php
protected function determineWordCount($triggers) { $triggers = $triggers->each(function ($data, $trigger) use ($triggers) { $data['order'] = count(explode(' ', $trigger)); $triggers->put($trigger, $data); }); return $triggers; }
[ "protected", "function", "determineWordCount", "(", "$", "triggers", ")", "{", "$", "triggers", "=", "$", "triggers", "->", "each", "(", "function", "(", "$", "data", ",", "$", "trigger", ")", "use", "(", "$", "triggers", ")", "{", "$", "data", "[", ...
Sort triggers based on word count from largest to smallest. @param Collection $triggers @return Collection
[ "Sort", "triggers", "based", "on", "word", "count", "from", "largest", "to", "smallest", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Commands/Trigger.php#L114-L123
train
axiom-labs/rivescript-php
src/Cortex/Input.php
Input.cleanOriginalSource
protected function cleanOriginalSource() { $patterns = synapse()->memory->substitute()->keys()->all(); $replacements = synapse()->memory->substitute()->values()->all(); $this->source = mb_strtolower($this->original); $this->source = preg_replace($patterns, $replacements, $this->source); $this->source = preg_replace('/[^\pL\d\s]+/u', '', $this->source); $this->source = remove_whitespace($this->source); }
php
protected function cleanOriginalSource() { $patterns = synapse()->memory->substitute()->keys()->all(); $replacements = synapse()->memory->substitute()->values()->all(); $this->source = mb_strtolower($this->original); $this->source = preg_replace($patterns, $replacements, $this->source); $this->source = preg_replace('/[^\pL\d\s]+/u', '', $this->source); $this->source = remove_whitespace($this->source); }
[ "protected", "function", "cleanOriginalSource", "(", ")", "{", "$", "patterns", "=", "synapse", "(", ")", "->", "memory", "->", "substitute", "(", ")", "->", "keys", "(", ")", "->", "all", "(", ")", ";", "$", "replacements", "=", "synapse", "(", ")", ...
Clean the source input, so its in a state easily readable by the interpreter. @return void
[ "Clean", "the", "source", "input", "so", "its", "in", "a", "state", "easily", "readable", "by", "the", "interpreter", "." ]
44989e73556ab2cac9a68ec5f6fb340affd4c724
https://github.com/axiom-labs/rivescript-php/blob/44989e73556ab2cac9a68ec5f6fb340affd4c724/src/Cortex/Input.php#L62-L71
train