_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q261000
TwigView.loadTwig
test
public function loadTwig() { $loader = new \Twig_Loader_Filesystem( array ( $this->viewsFolder ) ); // Set up environment $params = array( //'cache' => $this->viewsFolder . "cache", ); $this->twig = new \Twig_Environment($loader, $params); }
php
{ "resource": "" }
q261001
AuthAPI.setDefaultLanguage
test
private function setDefaultLanguage($userId) { if ($this->language !== null) { $languageModel = new \Mmf\Language\LanguageModel($this->connection); $userLanguageProperties = $languageModel->getUserLanguage($userId); if ($userLanguageProperties !== false) { $this->language->setLocale($userLanguageProperties['code']); } } }
php
{ "resource": "" }
q261002
AuthAPI.checkIfTokenIsValidAndUpdateTheExpireDate
test
private function checkIfTokenIsValidAndUpdateTheExpireDate() { $userInfo = $this->authModel->getRoleAndUserFromToken($this->token); if ($userInfo === false) { throw new AuthException('The token is not valid', 2000); } if ($userInfo['expire'] !== null && $userInfo['expire'] < $userInfo['db_date']) { throw new AuthException('The token expires', 2001); } if ($userInfo['expire'] !== null) { $futureExpiredate = date('Y-m-d H:i:s', strtotime($userInfo['db_date']) + $this->config->get('auth')['sessionTimeLife'] * 60); $this->authModel->updateExpireDate($this->token, $futureExpiredate); } return $userInfo; }
php
{ "resource": "" }
q261003
BasicViewAbstract.get
test
public function get($name, $template = '', $vars = array(), $globalScriptVars = '') { if ($template !== '') { $this->setTemplate($template); } //Creation the full path of the view $path = $this->viewsFolder . '/html/' . $name; //If exists vars to assign, we assing one by one. $viewVars = (count($vars) > 0) ? $vars : $this->viewVars; //Include the style if exists some style to include if (isset($this->styles)) { $vars['styles'] = $this->styles; } //Finalmente, incluimos la plantilla con las variables de los scripts. $this->contentView = $this->getFileContent($path, $viewVars) . $globalScriptVars; return $this; }
php
{ "resource": "" }
q261004
BasicViewAbstract.addJsVar
test
public function addJsVar($vars, $value, $encode = false) { if (is_array($vars)) { foreach ($vars as $key => $value) { // if JSONencode it's enable then is because it doesn't want json_encode. $this->addJsVar($key, $value); } } else { // apply the logic $this->scriptVars = $this->scriptVars . "var $vars = " . ($encode ? json_encode($value) : $value) . ";"; } }
php
{ "resource": "" }
q261005
BasicViewAbstract.addScript
test
public function addScript($jsfile, $min = FALSE, $type = 'text/javascript') { //Check if we must minified the style $minTag = "<script type='$type' src='min/?f=" . $this->asset($jsfile, TRUE) . "' ></script>"; $maxTag = "<script type='$type' src='" . $this->asset($jsfile, TRUE) . "' ></script>"; //TODO: min files $includeTag = $maxTag; $minPos = strpos($this->scripts, $minTag); $maxPos = strpos($this->scripts, $maxTag); if ($minPos === FALSE && $maxPos === FALSE) { // Si no esta, concatenamos $this->scripts .= $includeTag; } }
php
{ "resource": "" }
q261006
BasicViewAbstract.addStyles
test
public function addStyles($cssfile, $min = FALSE) { //Check if we must minified the style $minTag = "<link href='min/?f=" . $this->asset($cssfile, TRUE) . "' rel='stylesheet' type='text/css'/>"; $maxTag = "<link href='" . $this->asset($cssfile, TRUE) . "' rel='stylesheet' type='text/css'/>"; //TODO: min styles $includeTag = $maxTag; $minPos = strpos($this->styles, $minTag); $maxPos = strpos($this->styles, $maxTag); //If it doesn't exist, we concat with the actual styles if ($minPos === FALSE && $maxPos === FALSE) { $value = $this->styles . $includeTag; $this->styles = $value; } }
php
{ "resource": "" }
q261007
BasicViewAbstract.getFileContent
test
protected function getFileContent($path, $vars = array()) { //If there is vars to assign. if (is_array($vars)) { foreach ($vars as $key => $value) { /* @var $value BasicViewInterface */ //If is a view, get the content of the view. if (is_object($value) && is_a($value, '\Mmf\View\BasicViewInterface')) { $$key = $value->getContentView(); } else { $$key = $value; } } } ob_start(); /** @noinspection PhpIncludeInspection */ include($path); $output = ob_get_clean(); return $output; }
php
{ "resource": "" }
q261008
BasicViewAbstract.getContentWithTemplate
test
public function getContentWithTemplate() { $vars = $this->viewVars; //If there is vars to assign. if (is_array($vars)) { foreach ($vars as $key => $value) { /* @var $value BasicViewInterface */ //If is a view, get the content of the view. if (is_object($value) && is_a($value, '\Mmf\View\BasicViewInterface')) { $$key = $value->getContentView(); } else { $$key = $value; } } } $content = $this->getContentView(); if ($this->template == "") { $output = $content; } else { $scripts = ''; if (strlen($this->scriptVars) > 0) { $scripts = "<script>/* Global Vars */".$this->scriptVars."</script>"; } $styles = $this->getAllCss(); $scripts .= $this->getAllScripts(); ob_start(); $path = $this->viewsFolder . '/template/' . $this->template; if (file_exists($path)) { /** @noinspection PhpIncludeInspection */ include ($path); } else { $output = ob_get_clean(); throw new \Exception('Template does not exists', 1502); } $output = ob_get_clean(); } return $output; }
php
{ "resource": "" }
q261009
BasicViewAbstract.getAllScripts
test
public function getAllScripts() { $return = ''; foreach ($this->config->get('mvc')['defaultScripts'] as $script) { //If the script includes the // is for example http or https absolute route if (strpos($script, '//') !== FALSE) { $return .= '<script type="text/javascript" src="' . $script . '"></script>'; } else { $return .= '<script type="text/javascript" src="' . $this->asset($script, TRUE) . '"></script>'; } } $return .= $this->scripts; return $return; }
php
{ "resource": "" }
q261010
BasicViewAbstract.getAllCss
test
public function getAllCss() { $return = ''; foreach ($this->config->get('mvc')['defaultCSS'] as $script) { //If the script includes the // is for example http or https absolute route if (strpos($script, '//') !== FALSE) { $return .= "<link href='" . $script . "' rel='stylesheet' type='text/css'/>"; } else { $return .= "<link href='" . $this->asset($script, TRUE) . "' rel='stylesheet' type='text/css'/>"; } } $return .= $this->styles; return $return; }
php
{ "resource": "" }
q261011
BasicViewAbstract.asset
test
public function asset($path = "/", $return = FALSE) { $installFolder = $this->config->get('mvc')['installFolder']; if (!$return) { echo $installFolder . $path; } return $installFolder . $path; }
php
{ "resource": "" }
q261012
ACL.isAllowed
test
public function isAllowed(RoutingRuleAbstract $routingRule) { $controller = $routingRule->getController(); if (substr($controller, -10) == "Controller") { $controller = substr($controller,0, -10); } //$function = new \ReflectionClass($routingRule->getController() . 'Controller'); /* var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); */ //$controller = str_ireplace("Controller", "", $function->getShortName()); $action = $routingRule->getAction(); $access = $this->getAccess(); $allowed = FALSE; if (array_key_exists($controller, $access)) { foreach ($access[$controller] as $rule) { if ($rule == "*") { $allowed = TRUE; } else { if ($allowed) { //After general acceptation like * can be an exception $negation = FALSE; if ($rule[0] == "!") { $negation = TRUE; $rule = substr($rule, 1); } if ($negation) { //By the moment is allowed but maybe there is an exception rule if ($rule == $action) { $allowed = FALSE; } } } else { if ($rule == $action) { $allowed = TRUE; } } } } } return $allowed; }
php
{ "resource": "" }
q261013
ACL.getAccess
test
private function getAccess() { if (is_null($this->access)) { $chain = $this->getRolesChain(); $tmpAccess = array(); foreach ($chain as $role) { $arrAccess = $this->aclModel->getAccessForARole($role['id_role']); foreach ($arrAccess as $accessItem) { $tmpAccess[$accessItem['controller']] = explode("|", $accessItem['rules']); } } $this->access = $tmpAccess; return $this->access; } else { return $this->access; } }
php
{ "resource": "" }
q261014
ACL.getRolesChain
test
private function getRolesChain() { if (is_null($this->rolesChain)) { $chain = array(); $role = $this->aclModel->getRoleById($this->roleId); while ($role != FALSE) { $chain[] = $role; $currId = $role['id_parent']; $role = $this->aclModel->getRoleById($currId); } $this->rolesChain = array_reverse($chain); } return $this->rolesChain; }
php
{ "resource": "" }
q261015
LanguageModel.getUserLanguage
test
public function getUserLanguage($userId) { $sql = 'SELECT language.id_language, language.name, language.code, language.default FROM user INNER JOIN language ON language.id_language = user.id_language WHERE user.id_user=\''.$userId.'\''; $language = $this->select($sql); if (count($language)>0) { return $language[0]; } else { return false; } }
php
{ "resource": "" }
q261016
Translator.translateChoice
test
public function translateChoice($id, $number, array $parameters = array(), $locale = null) { if (null === $locale) { $locale = $this->getLocale(); } else { $this->assertValidLocale($locale); } //Get the translations $translations = $this->getTranslation($locale); //Calculate the translation and replace the parameters return strtr($this->getTranslationForId($id, $translations, $number), $parameters); }
php
{ "resource": "" }
q261017
Translator.getTranslation
test
public function getTranslation($locale) { if (!isset($this->translations[$locale])) { $this->translations[$locale] = $this->getFileTranslations($locale, $this->translatePath); } return $this->translations[$locale]; }
php
{ "resource": "" }
q261018
Translator.getFileTranslations
test
protected function getFileTranslations($locale, $translatePath) { $fileToInclude = $translatePath.$locale.'.php'; if (file_exists($fileToInclude)) { /** @noinspection PhpIncludeInspection */ require $fileToInclude; return $translation; } else { throw new \InvalidArgumentException('Invalid path file'); } }
php
{ "resource": "" }
q261019
Translator.getTranslationForId
test
protected function getTranslationForId($id, $translationArray, $number = 0) { $translation = ''; if(isset($translationArray[$id])) { //Id all join $translation = $this->getBasicTranslationForId($translationArray[$id], $number); } else { //Id separataly $arrayOfIds = explode(' ', $id); $constructTranslateArray = $translationArray; foreach ($arrayOfIds as $subId) { if(!isset($constructTranslateArray[$subId])) { throw new TranslateException('Translation id not exists.('.$id.')'); } $constructTranslateArray = $constructTranslateArray[$subId]; } $translation = $this->getBasicTranslationForId($constructTranslateArray, $number); } //Return the string translate with the parameters include into the placeholders return $translation; }
php
{ "resource": "" }
q261020
Translator.getBasicTranslationForId
test
private function getBasicTranslationForId($translationId, $number) { if(is_array($translationId) //Is array and we get the translate given for number array && isset($translationId[$number]) && is_string($translationId[$number])) { $translation = $translationId[$number]; } else if (is_string($translationId)) { //Is string directly $translation = $translationId; } return $translation; }
php
{ "resource": "" }
q261021
BuildMetaModelOperationsListener.generateToggleCommand
test
protected function generateToggleCommand($commands, $attribute, $commandName, $class, $language) { if (!$commands->hasCommandNamed($commandName)) { $toggle = new TranslatedToggleCommand(); $toggle ->setLanguage($language) ->setToggleProperty($attribute->getColName()) ->setName($commandName) ->setLabel($GLOBALS['TL_LANG']['MSC']['metamodelattribute_translatedcheckbox']['toggle'][0]) ->setDescription( \sprintf( $GLOBALS['TL_LANG']['MSC']['metamodelattribute_translatedcheckbox']['toggle'][1], $attribute->getName(), $language ) ); $extra = $toggle->getExtra(); $extra['icon'] = 'visible.svg'; $extra['class'] = $class; if ($commands->hasCommandNamed('show')) { $info = $commands->getCommandNamed('show'); } else { $info = null; } $commands->addCommand($toggle, $info); } }
php
{ "resource": "" }
q261022
BuildMetaModelOperationsListener.buildCommandsFor
test
protected function buildCommandsFor($attribute, $commands) { $activeLanguage = $attribute->getMetaModel()->getActiveLanguage(); $commandName = 'publishtranslatedcheckboxtoggle_' . $attribute->getColName(); $this->generateToggleCommand( $commands, $attribute, $commandName . '_' . $activeLanguage, 'contextmenu', $activeLanguage ); foreach (\array_diff($attribute->getMetaModel()->getAvailableLanguages(), [$activeLanguage]) as $langCode) { $this->generateToggleCommand( $commands, $attribute, $commandName . '_' . $langCode, 'edit-header', $langCode ); } }
php
{ "resource": "" }
q261023
BuildMetaModelOperationsListener.handle
test
public function handle(BuildMetaModelOperationsEvent $event) { foreach ($event->getMetaModel()->getAttributes() as $attribute) { if (($attribute instanceof TranslatedCheckbox) && ($attribute->get('check_publish') == 1)) { $container = $event->getContainer(); if ($container->hasDefinition(Contao2BackendViewDefinitionInterface::NAME)) { $view = $container->getDefinition(Contao2BackendViewDefinitionInterface::NAME); } else { $view = new Contao2BackendViewDefinition(); $container->setDefinition(Contao2BackendViewDefinitionInterface::NAME, $view); } $this->buildCommandsFor($attribute, $view->getModelCommands()); } } }
php
{ "resource": "" }
q261024
FrontController.main
test
public function main() { $this->config->set('URLBase', $this->autoload->getURLBase()); $this->setAndAppLibraries(); //Load All library paths, not include in try because ErrorController is not present. $this->loadAppFilesystem(); //Include the app filesystem structure into the loader path. $this->errorController = $this->getLibraryInstance('mvc', 'errorClass'); //Create error controller. //TODO log try { return $this->createMVCAction(); //Load Event, Plugin, Language, Routing, Auth, ACL, View, and controllers. } catch (ControllerException $e) { //Catch the false response from controller, not catch the problem errors. return $this->routingRule->getOutput()->formatResponseBad(['errorCode' => $e->getCode(), 'errorMessage' => $e->getMessage()]); } catch (RoutingException $e) { //Catch the routing not resolve. $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config); /* @var $respAutoClass ResponseInterface */ return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(), 'errorMessage' => 'The URL not match with any of our defined routes']); //TODO translate all the texts } catch (Exception $e) { //Catch the All other frameworks exceptions. $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config); /* @var $respAutoClass ResponseInterface */ return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(), 'errorMessage' => $e->getMessage()]); } catch (\Exception $e) { //Catch not controlled errors $this->executionErrors = 1; $this->messageErrors = 'File:' . $e->getFile() . ' File line:' . $e->getLine() . ', Message:' . $e->getMessage() . ', Traceroute:' . $e->getTraceAsString(); $this->traceRouteErrors = $e->getTrace(); $this->errorController->displayError(500); $respAutoClass = $this->getLibraryInstance('io', 'respAutoClass', $this->config); /* @var $respAutoClass ResponseInterface */ return $respAutoClass->formatResponseBad(['errorCode' => $e->getCode(), 'errorMessage' => 'Internal Server Error']); } }
php
{ "resource": "" }
q261025
FrontController.prepareAndCreateControllerAction
test
protected function prepareAndCreateControllerAction() { //Create the view controller $this->view = $this->getLibraryInstance('mvc', 'viewClass', $this->config); //Create the controller with the core. $controller = $this->createCoreAndController( $this->routingRule->getController() . 'Controller', $this->eventManager, $this->routingRule->getInput(), $this->routingRule->getOutput(), $this->view, $this->language, $this->routingResolver, $this->errorController, $this->session, $this->connection, $this->auth ); //Execute the controller action with the parameters. $actionReturn = $this->callClassAndMethodWithInputArguments($controller, $this->routingRule->getAction(), $this->routingRule->getInput()); //Format the response return $this->routingRule->getOutput()->formatResponse($actionReturn); }
php
{ "resource": "" }
q261026
FrontController.executeACL
test
protected function executeACL() { //Create the ACL $this->acl = $this->getLibraryInstance('acl', 'aclClass', $this->auth, $this->connection, $this->language); $isAllowed = $this->acl->isAllowed($this->routingRule); //Check if is allow to create the controller and call the action if (!$isAllowed) { throw new ControllerException('User not allow to access', 1500); } }
php
{ "resource": "" }
q261027
FrontController.executeAuth
test
protected function executeAuth() { //Create Auth controller $this->auth = $this->getLibraryInstance('auth', 'authClass', $this->session, $this->routingRule->getInput(), $this->connection, $this->config, $this->language); }
php
{ "resource": "" }
q261028
FrontController.executeResolveRoute
test
protected function executeResolveRoute() { //Add bulk routes $routingIniFile = $this->autoload->getURLBase() . $this->config->get('routing')['bulkRoutePath']; $this->routingResolver->addBulkRoutes($routingIniFile); //Resolve route $this->routingRule = $this->routingResolver->resolve(); }
php
{ "resource": "" }
q261029
FrontController.setAndAppLibraries
test
private function setAndAppLibraries() { //Get the libraries and application libraries $this->appLibraries = $this->config->get('app')['paths']; //Get the Structure $this->Structure = $this->config->get('Structure')['filesystem']; //Set to Autoloader the internal Structure $this->autoload->setStructure($this->Structure); }
php
{ "resource": "" }
q261030
FrontController.getLibraryInstance
test
private function getLibraryInstance($libraryName, $libraryClass) { $instance = null; $libraryClassName = $this->config->get($libraryName)[$libraryClass]; if (class_exists($libraryClassName)) { if (count(func_get_args()) > 2) { $arguments = array_slice(func_get_args(), 2, count(func_get_args()) - 2); $ref = new \ReflectionClass($libraryClassName); $instance = $ref->newInstanceArgs($arguments); //$instance = new $libraryClassName(array_slice(func_get_args(), 2, count(func_get_args())-2)); } else { $instance = new $libraryClassName(); } return $instance; } else { throw new \InvalidArgumentException('Invalid library class(' . $libraryClassName . ')'); } throw new \InvalidArgumentException('We can not instantiate the library class (' . $libraryClassName . ')'); }
php
{ "resource": "" }
q261031
FrontController.createCoreAndController
test
public function createCoreAndController( $class, \Mmf\Event\EventManagerInterface $eventManager, \Mmf\IO\RequestInterface $request, \Mmf\IO\ResponseInterface $response, \Mmf\View\BasicViewInterface $view, \Mmf\Language\LanguageInterface $language, \Mmf\Routing\RoutingResolverAbstract $router, ErrorControllerInterface $error, \Mmf\Parameter\SessionInterface $session, \Mmf\Model\ConnectionInterface $connection, \Mmf\Auth\AuthInterface $auth ) { $coreClass = $this->config->get('mvc')['coreClass']; if (class_exists($class) && class_exists($coreClass)) { $this->core = new $coreClass( $this->autoload, $this->config, $eventManager, $request, $response, $view, $language, $router, $error, $session, $connection, $auth ); $this->controller = new $class($this->core); return $this->controller; } else { $className = is_object($class) ? get_class($class) : $class; throw new \Mmf\Core\CoreException('Is not unable to create the controller' . ' (' . $className . '), check if the path is correct and if ' . 'exists the controller or if The CoreClass is correct (' . $coreClass . ')'); } }
php
{ "resource": "" }
q261032
FrontController.callClassAndMethodWithInputArguments
test
public function callClassAndMethodWithInputArguments( $class, $method, \Mmf\IO\RequestInterface $request ) { $params = $this->getFunctionArguments($class, $method); $listOfParams = []; foreach ($params as $param) { $paramValue = $request->input($param['name']); if ($paramValue === null && $param['isOptional'] === false) { throw new ControllerException('The param ' . $param['name'] . ' is mandatory', 1501); } elseif ($paramValue === null && $param['isOptional'] === true) { $paramValue = $param['initialValue']; } $listOfParams[] = $paramValue; } if (!is_object($class)) { $class = new $class(); } $returnOfAction = call_user_func_array(array($class, $method), $listOfParams); if ($returnOfAction !== false) { return $returnOfAction; } else { throw new \Mmf\Core\CoreException('FrontController::callClassAndMethodWithInputArguments' . ', Is not unable to call the action (' . $method . ') with ' . 'the parameters(' . print_r($listOfParams, true) . '), the expected name of parameters are' . '(' . print_r($params, true) . ')'); } }
php
{ "resource": "" }
q261033
FrontController.getFunctionArguments
test
public function getFunctionArguments($class, $method) { $ReflectionMethod = new \ReflectionMethod($class, $method); $paramsArray = array(); foreach ($ReflectionMethod->getParameters() as $param) { $auxParam = array('name' => $param->getName(), 'isOptional' => false, 'initialValue' => null); if ($param->isOptional()) { $auxParam['isOptional'] = true; $auxParam['initialValue'] = $param->getDefaultValue(); } $paramsArray[] = $auxParam; } return $paramsArray; }
php
{ "resource": "" }
q261034
AuthModel.getRoleAndUserFromToken
test
public function getRoleAndUserFromToken($token) { $sql = 'SELECT user.username, user.id_user, role.name, role.id_role, role.id_parent, NOW() AS db_date, token.expire FROM role INNER JOIN user ON user.id_role = role.id_role INNER JOIN token ON user.id_user = token.id_user WHERE token.token="'.$token.'" '; $role = $this->select($sql); if(is_array($role) && count($role)>0) { return $role[0]; } else { return false; } }
php
{ "resource": "" }
q261035
AuthModel.getRoleAndUserFromIdUser
test
public function getRoleAndUserFromIdUser($userId) { $sql = 'SELECT user.username, user.id_user, role.name, role.id_role, role.id_parent, NOW() AS db_date FROM role INNER JOIN user ON user.id_role = role.id_role WHERE user.id_user="'.$userId.'" '; $role = $this->select($sql); if(is_array($role) && count($role)>0) { return $role[0]; } else { return false; } }
php
{ "resource": "" }
q261036
Combo.getCurrentOptions
test
protected function getCurrentOptions() { $value = Html::getAttributeValue($this->model, $this->attribute); if (!isset($value) || empty($value)) { return []; } if (!empty($this->current)) { return $this->current; } if ($this->getHasId()) { if (!is_scalar($value)) { Yii::error('When Combo has ID, property $current must be set manually, or attribute value must be a scalar. Value ' . var_export($value, true) . ' is not a scalar.', __METHOD__); return []; } return [$value => $value]; } else { if (is_array($value)) { return array_combine(array_values($value), array_values($value)); } return [$value => $value]; } }
php
{ "resource": "" }
q261037
RequestHtml.setBulkOfInputGivenArray
test
protected function setBulkOfInputGivenArray($arrayOfParameters) { if(is_array($arrayOfParameters)) { foreach ($arrayOfParameters as $nameOfParameter => $valueOfParameter) { $this->setInput($nameOfParameter, $valueOfParameter); } } }
php
{ "resource": "" }
q261038
RequestHtml.input
test
public function input($varName) { if (isset($this->parameters[$varName])) { return $this->filterVar($this->parameters[$varName]); } else { return null; } }
php
{ "resource": "" }
q261039
RequestHtml.filterVar
test
public function filterVar($var) { $response = NULL; if (is_bool($var)) { $response = $var; } elseif(is_int($var)) { $response = $var; } elseif(is_float($var)) { $response = $var; } if($var != 'null') { if(is_string($var)) { $response = filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS); } elseif(is_array($var)) { $response = array(); foreach ($var as $key => $value) { if(is_array($value)) { $response[$key] = $this->filterVar($value); } else { $response[$key] = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS); } } } } return $response; }
php
{ "resource": "" }
q261040
PDO.openConnection
test
public function openConnection($name='db_default') { foreach ($this->connections as $connection) { if($connection['name'] == $name) { return $connection['lynk']; } } //Open new connection try { //Get the configuration of the connection. $dbConfig = $this->config->get($name); //Create the new connection. $connection = new \PDO('mysql:host=' . $dbConfig['host'] . ';port=' . $dbConfig['port'] . ';dbname=' . $dbConfig['name'], $dbConfig['user'], $dbConfig['pass'], array(\PDO::MYSQL_ATTR_FOUND_ROWS => true, \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $this->connections[] = array('name'=>$name,'lynk'=>$connection); return $connection; } catch (\Exception $e) { throw new ModelException('Error trying to connect to db'); } }
php
{ "resource": "" }
q261041
PDO.closeConnection
test
public function closeConnection($name='db_default') { foreach ($this->connections as $key => $connection) { if($connection['name'] == $name) { $this->connections[$key]['lynk'] = null; //closing the connection array_splice($this->connections, $key, 1); return true; } } return false; }
php
{ "resource": "" }
q261042
MySQLModelAbstract.executeSQL
test
private function executeSQL($SQL, $parameters = null) { try { $queryPrepare = $this->connection->prepare($SQL); if (is_array($parameters)) { $queryPrepare->execute($parameters); } else { $queryPrepare->execute(); } } catch (\PDOException $e) { throw new ModelException('Error in the Select QUERY ('.$SQL.') ' . 'and error message('.$e->getMessage().')'); } return $queryPrepare; }
php
{ "resource": "" }
q261043
MySQLModelAbstract.select
test
public function select($SQL, $parameters = null) { $queryResult = $this->executeSQL($SQL, $parameters); return $queryResult->fetchAll(\PDO::FETCH_ASSOC); }
php
{ "resource": "" }
q261044
MySQLModelAbstract.insert
test
public function insert($SQL, $parameters = null) { $this->executeSQL($SQL, $parameters); return $this->connection->lastInsertId(); }
php
{ "resource": "" }
q261045
MySQLModelAbstract.delete
test
public function delete($SQL, $parameters = null) { $queryResult = $this->executeSQL($SQL, $parameters); return $queryResult->rowCount(); }
php
{ "resource": "" }
q261046
MySQLModelAbstract.update
test
public function update($SQL, $parameters = null) { $queryResult = $this->executeSQL($SQL, $parameters); return $queryResult->rowCount(); }
php
{ "resource": "" }
q261047
Auth.logout
test
public function logout() { $this->setUserId($this->guestUserId); $this->setUsername($this->guestUsername); $this->setRoleId($this->guestRoleId); $this->setRoleName($this->guestRoleName); }
php
{ "resource": "" }
q261048
Auth.setUserId
test
public function setUserId($userId) { $this->userId = $userId; if ($this->session !== null) { $this->session->set('userId', $userId); } }
php
{ "resource": "" }
q261049
Auth.setUsername
test
public function setUsername($username) { $this->username = $username; if ($this->session !== null) { $this->session->set('username', $username); } }
php
{ "resource": "" }
q261050
Auth.setRoleId
test
public function setRoleId($roleId) { $this->roleId = $roleId; if ($this->session !== null) { $this->session->set('roleId', $roleId); } }
php
{ "resource": "" }
q261051
Auth.setRoleName
test
public function setRoleName($roleName) { $this->roleName = $roleName; if ($this->session !== null) { $this->session->set('roleName', $roleName); } }
php
{ "resource": "" }
q261052
GenericValidator.validate
test
public function validate($value, Constraint $constraint) { $method = $constraint->method; if (!$this->getManager()->$method($value, $constraint)) { $this->setMessage($constraint->message, array( '%property%' => $constraint->property )); return false; } return true; }
php
{ "resource": "" }
q261053
FileSystemPluginLocator.getInstalledPlugins
test
public function getInstalledPlugins($path) { $searchPluginDirectories = $this->searchPluginDirectories($path); $validPluginDirectories = array(); $factoryPluginClasses = array(); foreach ($searchPluginDirectories as $pluginDirectory) { if (is_file($pluginDirectory. '/enable.php')) { $validPluginClass = $this->searchPluginFactoryClass($pluginDirectory); if ($validPluginClass) { $validPluginDirectories[] = $pluginDirectory; $factoryPluginClasses[] = $validPluginClass; } } } return array('pluginClasses' => $factoryPluginClasses, 'pluginDirectories'=> $validPluginDirectories, 'pluginEnabled' => true ); }
php
{ "resource": "" }
q261054
FileSystemPluginLocator.searchPluginDirectories
test
protected function searchPluginDirectories($path) { $pluginDirectories = array(); if ( ($directoryHandle = opendir($path)) == true ) { while (($fileOrDir = readdir( $directoryHandle )) !== false) { if (is_dir($path. $fileOrDir ) && $fileOrDir !== '.' && $fileOrDir !=='..') { $pluginDirectories[] = $path. $fileOrDir; } } } else { throw new PluginException('Invalid plugin path, check the main config.ini file'); } return $pluginDirectories; }
php
{ "resource": "" }
q261055
FileSystemPluginLocator.searchPluginFactoryClass
test
protected function searchPluginFactoryClass($pluginDirectory) { foreach ($this->internalPluginStructure as $pluginStructure) { $path = $pluginDirectory.'/'.$pluginStructure.'/'; if ( ($directoryHandle = opendir($path)) == true ) { while (($fileOrDir = readdir( $directoryHandle )) !== false) { if (is_file($path. $fileOrDir) && $this->isPhpFile($path.$fileOrDir)) { $classImplementation = $this->haveTheFileImplementationOf($path. $fileOrDir); if ($classImplementation) { return $classImplementation; } } } } else { throw new PluginException('Invalid plugin structure path, check the main config.ini file'); } } return null; }
php
{ "resource": "" }
q261056
FileSystemPluginLocator.haveTheFileImplementationOf
test
public function haveTheFileImplementationOf($file, $implementation = 'PluginInterface') { $matches = array(); $fp = fopen($file, 'r'); while (!feof($fp)) { $line = stream_get_line($fp, 1000000, "\n"); if (preg_match('/class\s+(\w+)(.*)\simplements\s+(\w+)(.*)?\{/', $line, $matches)) { if ($matches[3] === $implementation) { return $matches[1]; //Return the class name } } } return false; }
php
{ "resource": "" }
q261057
FunctionReflection.toString
test
public static function toString(Closure $closure) { $functionStringValue = ''; $functionReflection = new ReflectionFunction($closure); $file = file($functionReflection->getFileName()); $lastLine = ($functionReflection->getEndLine() - 1); for ($codeline = $functionReflection->getStartLine(); $codeline < $lastLine; $codeline++) { $functionStringValue .= $file[$codeline]; } return $functionStringValue; }
php
{ "resource": "" }
q261058
Operation.execute
test
public function execute(Closure $closure) { $temporaryFile = tempnam(sys_get_temp_dir(), 'covert'); $temporaryContent = '<?php'.PHP_EOL.PHP_EOL; if ($this->autoload !== false) { $temporaryContent .= "require('$this->autoload');".PHP_EOL.PHP_EOL; } $temporaryContent .= FunctionReflection::toString($closure).PHP_EOL.PHP_EOL; $temporaryContent .= 'unlink(__FILE__);'.PHP_EOL.PHP_EOL; $temporaryContent .= 'exit;'; file_put_contents($temporaryFile, $temporaryContent); $this->processId = $this->executeFile($temporaryFile); return $this; }
php
{ "resource": "" }
q261059
Operation.executeFile
test
private function executeFile($file) { if (OperatingSystem::isWindows()) { return $this->runCommandForWindows($file); } return $this->runCommandForNix($file); }
php
{ "resource": "" }
q261060
Operation.runCommandForWindows
test
private function runCommandForWindows($file) { if ($this->logging) { $stdoutPipe = ['file', $this->logging, 'w']; $stderrPipe = ['file', $this->logging, 'w']; } else { $stdoutPipe = fopen('NUL', 'c'); $stderrPipe = fopen('NUL', 'c'); } $desc = [ ['pipe', 'r'], $stdoutPipe, $stderrPipe, ]; $cmd = "START /b php {$file}"; $handle = proc_open( $cmd, $desc, $pipes, getcwd() ); if (!is_resource($handle)) { throw new Exception('Could not create a background resource. Try using a better operating system.'); } $pid = proc_get_status($handle)['pid']; try { proc_close($handle); $resource = array_filter(explode(' ', shell_exec("wmic process get parentprocessid, processid | find \"$pid\""))); array_pop($resource); $pid = end($resource); } catch (Exception $e) { } return $pid; }
php
{ "resource": "" }
q261061
Operation.setAutoloadFile
test
public function setAutoloadFile($autoload) { if ($autoload !== false && !file_exists($autoload)) { throw new Exception("The autoload path '{$autoload}' doesn't exist."); } $this->autoload = $autoload; return $this; }
php
{ "resource": "" }
q261062
Operation.isRunning
test
public function isRunning() { $processId = $this->getProcessId(); if (OperatingSystem::isWindows()) { $pids = shell_exec("wmic process get processid | find \"{$processId}\""); $resource = array_filter(explode(' ', $pids)); $isRunning = count($resource) > 0 && $processId == reset($resource); } else { $isRunning = (bool) posix_getsid($processId); } return $isRunning; }
php
{ "resource": "" }
q261063
Operation.kill
test
public function kill() { if ($this->isRunning()) { $processId = $this->getProcessId(); if (OperatingSystem::isWindows()) { $cmd = "taskkill /pid {$processId} -t -f"; } else { $cmd = "kill -9 {$processId}"; } shell_exec($cmd); } return $this; }
php
{ "resource": "" }
q261064
ProfilerBase.reset
test
protected function reset() { $this->log_sections = []; $this->max_memory_usage = null; $this->start_time = null; $this->end_time = null; }
php
{ "resource": "" }
q261065
Uri.createFromString
test
public static function createFromString(string $str): self { $parsedUrl = parse_url($str); return new self($parsedUrl['scheme'] ?? '', $parsedUrl['host'] ?? null, $parsedUrl['port'] ?? null, $parsedUrl['path'] ?? '/', $parsedUrl['query'] ?? '', $parsedUrl['fragment'] ?? '', $parsedUrl['user'] ?? '', $parsedUrl['pass'] ?? ''); }
php
{ "resource": "" }
q261066
image.getDriver
test
final static function getDriver(array $drivers=array('gd')) { foreach ($drivers as $driver) { if (!preg_match('/^[a-z0-9\_]+$/i', $driver)) continue; $class = __NAMESPACE__ . "\\image_$driver"; if (class_exists($class) && method_exists($class, "available")) { eval("\$avail = $class::available();"); if ($avail) return $driver; } } return false; }
php
{ "resource": "" }
q261067
image.buildImage
test
final protected function buildImage($image) { $class = get_class($this); if ($image instanceof $class) { $width = $image->width; $height = $image->height; $img = $image->image; } elseif (is_array($image)) { list($key, $width) = each($image); list($key, $height) = each($image); $img = $this->getBlankImage($width, $height); } else $img = $this->getImage($image, $width, $height); return ($img !== false) ? array($img, $width, $height) : false; }
php
{ "resource": "" }
q261068
image.getPropWidth
test
final public function getPropWidth($resizedHeight) { $width = round(($this->width * $resizedHeight) / $this->height); if (!$width) $width = 1; return $width; }
php
{ "resource": "" }
q261069
image.getPropHeight
test
final public function getPropHeight($resizedWidth) { $height = round(($this->height * $resizedWidth) / $this->width); if (!$height) $height = 1; return $height; }
php
{ "resource": "" }
q261070
ByteSize.formatBinary
test
public static function formatBinary($bytes, $precision = null) { static $formatter = null; if (!$formatter) { $formatter = new Formatter\Binary(); } return $formatter->format($bytes, $precision); }
php
{ "resource": "" }
q261071
ByteSize.formatMetric
test
public static function formatMetric($bytes, $precision = null) { static $formatter = null; if (!$formatter) { $formatter = new Formatter\Metric(); } return $formatter->format($bytes, $precision); }
php
{ "resource": "" }
q261072
Session.create
test
public static function create($driverClass = self::DRIVER_SERVER, array $options = []) { $session = new Session($driverClass, $options); return $session->initialize(); }
php
{ "resource": "" }
q261073
Session.initialize
test
public function initialize() { $this->checkClassExistence(); $this->checkClassType(); $className = $this->driverClass; return new $className($this->options); }
php
{ "resource": "" }
q261074
UrlEncodedParser.parse
test
public function parse() { $this->stream->rewind(); parse_str($this->stream->getContents(), $parsed); return array_merge($_POST, $parsed); }
php
{ "resource": "" }
q261075
RequestUriFactory.generateUrl
test
private function generateUrl() { $hostHeader = $this->request->getHeaderLine('host'); $defaultHost = strlen($hostHeader) > 0 ? $hostHeader : 'unknown-host'; $host = $this->getServerParam('SERVER_NAME', $defaultHost); $scheme = $this->getServerParam('REQUEST_SCHEME', 'http'); $uri = $this->getServerParam('REQUEST_URI', '/'); $port = $this->getServerParam('SERVER_PORT', '80'); $port = in_array($port, ['80', '443']) ? '' : ":{$port}"; return "{$scheme}://{$host}{$port}{$uri}"; }
php
{ "resource": "" }
q261076
RequestUriFactory.getServerParam
test
private function getServerParam($name, $default = null) { $data = $this->request->getServerParams(); if (array_key_exists($name, $data)) { $default = trim($data[$name]); } return $default; }
php
{ "resource": "" }
q261077
Application.getDefaultInputDefinition
test
protected function getDefaultInputDefinition() { return new InputDefinition( [ new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), new InputOption( '--env', '-e', InputOption::VALUE_REQUIRED, 'The environment to be used', getenv('BLUZ_ENV') ?: 'dev' ), new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'), new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'), new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages'), new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version') ] ); }
php
{ "resource": "" }
q261078
Application.registerCommands
test
protected function registerCommands() { $this->addCommands( [ new Command\MagicCommand, new Command\RunCommand, new Command\TestCommand, new Command\Db\CreateCommand, new Command\Db\MigrateCommand, new Command\Db\RollbackCommand, new Command\Db\StatusCommand, new Command\Db\SeedCreateCommand, new Command\Db\SeedRunCommand, new Command\Generate\ModuleCommand, new Command\Generate\ControllerCommand, new Command\Generate\ModelCommand, new Command\Generate\CrudCommand, new Command\Generate\GridCommand, new Command\Generate\RestCommand, new Command\Generate\ScaffoldCommand, new Command\Module\InstallCommand, new Command\Module\ListCommand, new Command\Module\RemoveCommand, new Command\Server\StartCommand, new Command\Server\StopCommand, new Command\Server\StatusCommand, ] ); }
php
{ "resource": "" }
q261079
Application.getModelPath
test
public function getModelPath($name) : string { return $this->getWorkingPath() . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . ucfirst(strtolower($name)); }
php
{ "resource": "" }
q261080
AbstractGenerateCommand.addForceOption
test
protected function addForceOption() : void { $force = new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Rewrite previously generated files'); $this->getDefinition()->addOption($force); }
php
{ "resource": "" }
q261081
AbstractGenerateCommand.addModelArgument
test
protected function addModelArgument() : void { $model = new InputArgument('model', InputArgument::REQUIRED, 'Model name is required'); $this->getDefinition()->addArgument($model); }
php
{ "resource": "" }
q261082
AbstractGenerateCommand.validateModelArgument
test
protected function validateModelArgument() : void { $model = $this->getInput()->getArgument('model'); $validator = Validator::create() ->string() ->alphaNumeric() ->noWhitespace(); if ($this->getDefinition()->getArgument('model')->isRequired() && !$validator->validate($model)) { throw new InputException($validator->getError()); } }
php
{ "resource": "" }
q261083
AbstractGenerateCommand.addTableArgument
test
protected function addTableArgument() : void { $table = new InputArgument('table', InputArgument::REQUIRED, 'Table name is required'); $this->getDefinition()->addArgument($table); }
php
{ "resource": "" }
q261084
AbstractGenerateCommand.validateTableArgument
test
protected function validateTableArgument() : void { $table = $this->getInput()->getArgument('table'); $validator = Validator::create() ->string() ->alphaNumeric('_') ->noWhitespace(); if ($this->getDefinition()->getArgument('table')->isRequired() && !$validator->validate($table)) { throw new InputException($validator->getError()); } }
php
{ "resource": "" }
q261085
AbstractGenerateCommand.getTableInstance
test
protected function getTableInstance($model) : Table { $file = $this->getApplication()->getModelPath($model) . DS . 'Table.php'; if (!file_exists($file)) { throw new GeneratorException( "Model $model is not exist, run command `bluzman generate:model $model` before" ); } include_once $file; $class = '\\Application\\' . ucfirst($model) . '\\Table'; if (!class_exists($class)) { throw new GeneratorException("Bluzman can't found `Table` class for model `$model`"); } return $class::getInstance(); }
php
{ "resource": "" }
q261086
AbstractGenerateCommand.generateFile
test
protected function generateFile($class, $file, array $data = []) : void { if (file_exists($file) && !$this->getInput()->getOption('force')) { $this->comment(" |> File <info>$file</info> already exists"); return; } $template = $this->getTemplate($class); $template->setFilePath($file); $template->setTemplateData($data); $generator = new Generator($template); $generator->make(); }
php
{ "resource": "" }
q261087
RequestHandler.handle
test
public function handle(ServerRequestInterface $request): ResponseInterface { $response = call_user_func($this->callback, $request); return $response; }
php
{ "resource": "" }
q261088
AbstractStream.isSeekable
test
public function isSeekable() { $seekable = false; if ($this->stream) { $meta = stream_get_meta_data($this->stream); $seekable = $meta['seekable']; } return $seekable; }
php
{ "resource": "" }
q261089
BodyParser.createParserWith
test
private function createParserWith(StreamInterface $body) { $class = NullParser::class; foreach (self::$parsers as $parser => $contentTypes) { foreach ($contentTypes as $contentType) { if (stripos($this->contentType, $contentType) !== false) { $class = $parser; } } } return new $class($body); }
php
{ "resource": "" }
q261090
BodyParser.addParser
test
public static function addParser($className, array $contentTypes) { if (! is_a($className, BodyParserInterface::class)) { throw new InvalidArgumentException( "Parser objects MUST implement the BodyParserInterface interface." ); } $existing = isset(self::$parsers[$className]) ? self::$parsers[$className] : []; array_unshift( self::$parsers[$className], array_merge($existing, $contentTypes) ); }
php
{ "resource": "" }
q261091
AbstractCommand.addModuleArgument
test
protected function addModuleArgument($required = InputArgument::REQUIRED) : void { $module = new InputArgument('module', $required, 'Module name is required'); $this->getDefinition()->addArgument($module); }
php
{ "resource": "" }
q261092
AbstractCommand.addControllerArgument
test
protected function addControllerArgument($required = InputArgument::REQUIRED) : void { $controller = new InputArgument('controller', $required, 'Controller name is required'); $this->getDefinition()->addArgument($controller); }
php
{ "resource": "" }
q261093
HttpFactory.createRequest
test
public function createRequest(string $method, $uri, array $headers = [], $body = null, $protocolVersion = '1.1'): RequestInterface { $request = new Request($method, $this->createUri($uri)); // Headers ? if (!empty($headers)) { $request = $request->withHeaders($headers); } // Body ? if (!is_null($body)) { if ($body instanceof StreamInterface) { $request = $request->withBody($body); } if (is_resource($body)) { $request = $request->withBody($this->createStreamFromResource($body)); } if (is_string($body)) { $request = $request->withBody($this->createStream($body)); } } // Protocol version ? if ($protocolVersion != $request->getProtocolVersion()) { $request = $request->withProtocolVersion($protocolVersion); } return $request; }
php
{ "resource": "" }
q261094
HttpFactory.createServerRequest
test
public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface { if (is_string($uri)) { $uri = Uri::createFromString($uri); } return new ServerRequest($method, $uri, [], [], $serverParams, new Stream()); }
php
{ "resource": "" }
q261095
HttpFactory.createStream
test
public function createStream(string $content = ''): StreamInterface { $stream = new Stream(); $stream->write($content); return $stream; }
php
{ "resource": "" }
q261096
HttpFactory.createStreamFromFile
test
public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface { if (!in_array($mode, ['r', 'r+', 'w+', 'a+', 'c+'])) { throw new \InvalidArgumentException(sprintf('Invalid mode "%s" to read file "%s"', $mode)); } if (($resource = @fopen($filename, $mode)) === false) { throw new \RuntimeException(sprintf('Unable to open file "%s" with mode "%s"', $filename, $mode)); } // Read file rewind($resource); $content = fread($resource, filesize($filename)); fclose($resource); return $this->createStream($content); }
php
{ "resource": "" }
q261097
HttpFactory.createUploadedFile
test
public function createUploadedFile( StreamInterface $stream, int $size = null, int $error = \UPLOAD_ERR_OK, string $clientFilename = null, string $clientMediaType = null, string $filename = '' ): UploadedFileInterface { if (is_null($size)) { $size = $stream->getSize(); } $uploadedFile = new UploadedFile($filename, $clientFilename, $clientMediaType, $size, $error); $uploadedFile->setStream($stream); return $uploadedFile; }
php
{ "resource": "" }
q261098
HttpFactory.createUri
test
public function createUri(string $uri = ''): UriInterface { if (is_string($uri)) { return Uri::createFromString($uri); } else { throw new \InvalidArgumentException('Not valid URI given'); } }
php
{ "resource": "" }
q261099
AbstractFormatter.format
test
public function format($bytes, $precision = null) { $bytes = $this->normalizeBytes($bytes); $out = $bytes . 'B'; foreach ($this->suffixes as $power => $suffix) { if (bccomp($calc = $this->divPow($bytes, $this->base, $power), 1) >= 0) { $out = $this->formatNumber($calc, $suffix, $precision); break; } } return $out; }
php
{ "resource": "" }