_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q252000
SetTrait.set
validation
public function set($col, $value = ClauseInterface::NO_VALUE) { if (is_array($col)) { return $this->setWithArrayData($col); } // update column name if (!isset($this->clause_set[$col])) { $this->clause_set[$col] = true; } // store data by row if (ClauseInterface::NO_VALUE !== $value) { $this->clause_data[$this->clause_rownum][$col] = $value; } return $this; }
php
{ "resource": "" }
q252001
SetTrait.buildUpdateSet
validation
protected function buildUpdateSet()/*# : array */ { $result = []; // build set $data = $this->clause_data[0]; foreach ($data as $col => $val) { $result[] = $this->quote($col) . ' = ' . $this->processValue($val); } return $result; }
php
{ "resource": "" }
q252002
FirstClass.encodeString
validation
public function encodeString($string) { $string=strtolower($string); $src="abcdefghijklmnopqrstuvwxyz0123456789 "; $dst="jklmnopqrstuvwxyz0123456789abcdefghi "; for ($i=0; $i<strlen($string); $i++) { $pos=strpos($src, $string[$i]); if ($pos===false) { throw new \Exception("Please provide only numbers and alphanumerical characters"); } $string[$i]=$dst[$pos]; } return $string; }
php
{ "resource": "" }
q252003
QRPayment.setAlternativeAccount
validation
public function setAlternativeAccount($iban1, $swift1 = null, $iban2 = null, $swift2 = null) { if ($swift1 !== null) { $iban1 .= '+' . $swift1; } if ($iban2 !== null) { if ($swift2 !== null) { $iban2 .= '+' . $swift2; } $iban1 .= ',' . $iban2; } return $this->add('ALT-ACC', $iban1); }
php
{ "resource": "" }
q252004
QRPayment.setPaymentType
validation
public function setPaymentType($paymentType) { if (self::PAYMENT_PEER_TO_PEER !== $paymentType) { throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid payment type.')); } return $this->add('PT', $paymentType); }
php
{ "resource": "" }
q252005
QRPayment.generateText
validation
public function generateText() { $result = 'SPD' . self::DELIMITER . $this->version . self::DELIMITER . $this->implodeContent(); if ($this->appendCRC32) { $result .= self::DELIMITER . 'CRC32:' . sprintf('%x', crc32($result)); } return $result; }
php
{ "resource": "" }
q252006
QRPayment.generateImage
validation
public function generateImage($filename = false, $level = Constants::QR_ECLEVEL_L, $size = 3, $margin = 4) { $result = 'SPD' . self::DELIMITER . $this->version . self::DELIMITER . $this->implodeContent(); if ($this->appendCRC32) { $result .= self::DELIMITER . 'CRC32:' . sprintf('%x', crc32($result)); } QRcode::png($result, $filename, $level, $size, $margin); die(); }
php
{ "resource": "" }
q252007
QRPayment.implodeContent
validation
private function implodeContent() { ksort($this->content); $output = ''; foreach ($this->content as $key => $value) { $output .= $key . self::KV_DELIMITER . $value . self::DELIMITER; } return rtrim($output, self::DELIMITER); }
php
{ "resource": "" }
q252008
QRPayment.normalizeAccountNumber
validation
public static function normalizeAccountNumber($account) { $account = str_replace(' ', '', $account); if (false === strpos($account, '-')) { $account = '000000-' . $account; } $parts = explode('-', $account); $parts[0] = str_pad($parts[0], 6, '0', STR_PAD_LEFT); $parts2 = explode('/', $parts[1]); $parts2[0] = str_pad($parts2[0], 10, '0', STR_PAD_LEFT); $parts2[1] = str_pad($parts2[1], 4, '0', STR_PAD_LEFT); $parts[1] = implode('/', $parts2); return implode('-', $parts); }
php
{ "resource": "" }
q252009
QRPayment.accountToIBAN
validation
public static function accountToIBAN($account, $country = 'CZ') { $allowedCountries = ['AT', 'BE', 'BG', 'CZ', 'CY', 'DK', 'EE', 'FI', 'FR', 'DE', 'GI', 'GR', 'HU', 'IE', 'IS', 'IT', 'LI', 'LT', 'LU', 'LV', 'MC', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'SE', 'CH', 'SI', 'SK', 'ES', 'GB']; $account = self::normalizeAccountNumber($account); $accountArray = explode('/', str_replace('-', '', $account)); if (2 !== \count($accountArray)) { throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Wrong bank account (some part missing).')); } $country = strtoupper($country); if (!\in_array($country, $allowedCountries, true)) { throw new RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid country code.')); } $accountStr = str_pad($accountArray[1], 4, '0', STR_PAD_LEFT) . str_pad($accountArray[0], 16, '0', STR_PAD_LEFT) . (\ord($country[0]) - 55) . (\ord($country[1]) - 55) . '00'; $crc = ''; $pos = 0; while (\strlen($accountStr) > 0) { $len = 9 - \strlen($crc); $crc = (int)($crc . substr($accountStr, $pos, $len)) % 97; $accountStr = substr($accountStr, $len); } return ($country . str_pad(98 - $crc, 2, '0', STR_PAD_LEFT) . $accountArray[1] . $accountArray[0]); }
php
{ "resource": "" }
q252010
ViewAction.run
validation
public function run() { $viewName = $this->resolveViewName(); $this->controller->actionParams[$this->viewParam] = Yii::$app->request->get($this->viewParam); $controllerLayout = null; if ($this->layout !== null) { $controllerLayout = $this->controller->layout; $this->controller->layout = $this->layout; } try { $output = $this->render($viewName); if ($controllerLayout) { $this->controller->layout = $controllerLayout; } } catch (InvalidParamException $e) { if ($controllerLayout) { $this->controller->layout = $controllerLayout; } if (YII_DEBUG) { throw new NotFoundHttpException($e->getMessage()); } else { throw new NotFoundHttpException( Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName]) ); } } return $output; }
php
{ "resource": "" }
q252011
ViewAction.resolveViewName
validation
protected function resolveViewName() { $viewName = Yii::$app->request->get($this->viewParam, $this->defaultView); if (!is_string($viewName) || !preg_match('~^\w(?:(?!\/\.{0,2}\/)[\w\/\-\.])*$~', $viewName)) { if (YII_DEBUG) { throw new NotFoundHttpException("The requested view \"$viewName\" must start with a word character, must not contain /../ or /./, can contain only word characters, forward slashes, dots and dashes."); } else { throw new NotFoundHttpException(Yii::t('yii', 'The requested view "{name}" was not found.', ['name' => $viewName])); } } return empty($this->viewPrefix) ? $viewName : $this->viewPrefix . '/' . $viewName; }
php
{ "resource": "" }
q252012
MediaTypeManager.registerMediaType
validation
public function registerMediaType($mediaType) { if ($this->check($mediaType)) { $this->mediaTypes[(new \ReflectionClass($mediaType))->getConstant('NAME')] = $mediaType; return $this; } else { throw new \Exception('registered MediaType must implement \MandarinMedien\MMMediaBundle\Model\MediaTypeInterface'); } }
php
{ "resource": "" }
q252013
MediaTypeManager.getMediaTypeMatch
validation
public function getMediaTypeMatch($data) { foreach ($this->getMediaTypes() as $mediaTypeClass) { $instance = forward_static_call(array($mediaTypeClass, 'check'), $data); if ($instance) { return $instance; } } }
php
{ "resource": "" }
q252014
IdentityMap.with
validation
public static function with(array $theseObjects): MapsObjectsByIdentity { $objects = []; $entityIds = []; foreach ($theseObjects as $id => $object) { $objects = IdentityMap::addTo($objects, (string) $id, $object); $entityIds[theInstanceIdOf($object)] = (string) $id; } return new self($objects, $entityIds); }
php
{ "resource": "" }
q252015
User.loginByCookie
validation
protected function loginByCookie() { $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']); if ($value === null) { return; } $data = json_decode($value, true); if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) { return; } list ($id, $authKey, $duration) = $data; /* @var $class IdentityInterface */ $class = $this->identityClass; $identity = $class::findIdentity($id); if ($identity === null) { return; } elseif (!$identity instanceof IdentityInterface) { throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface."); } if ($identity->validateAuthKey($authKey)) { if ($this->beforeLogin($identity, true, $duration)) { $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0); $ip = Yii::$app->getRequest()->getUserIP(); Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__); $this->afterLogin($identity, true, $duration); } } else { Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__); } }
php
{ "resource": "" }
q252016
User.loginRequired
validation
public function loginRequired($checkAjax = true) { $request = Yii::$app->getRequest(); if ($this->enableSession && (!$checkAjax || !$request->getIsAjax())) { $this->setReturnUrl($request->getUrl()); } if ($this->loginUrl !== null) { $loginUrl = (array) $this->loginUrl; if ($loginUrl[0] !== Yii::$app->requestedRoute) { return Yii::$app->getResponse()->redirect($this->loginUrl); } } throw new ForbiddenHttpException(Yii::t('yii', 'Login Required')); }
php
{ "resource": "" }
q252017
Factory.fromArray
validation
public function fromArray(array $array) { $root = new Node(null); $map = array(); $map[0] = $root; // Create an entry in $map for every item in $a foreach ($array as $element) { if (3 !== count($element)) { throw new Exception('Each array must have 3 elements.'); } $map[$element[0]] = new Node($element[2]); } // foreach ($array as $element) { if (empty($element[1])) { $element[1] = 0; } $found = false; $i = 0; $keys = array_keys($map); $cnt = count($keys); while (!$found && $i < $cnt) { if ($keys[$i] === $element[1]) { $map[$keys[$i]]->addChild($map[$element[0]]); $found = true; } else { $i++; } } if (!$found) { // Error throw new Exception('Data structure does not seem to be consistent. ' . 'Key "' . $element[1] . '" could not be found.'); } } return $root; }
php
{ "resource": "" }
q252018
Spritify.total_size
validation
private function total_size() { $arr = array("width" => 0, "height" => 0); foreach ($this->images as $image) { if ($arr["width"] < $image["width"]) { $arr["width"] = $image["width"]; } $arr["height"] += $image["height"]; } return $arr; }
php
{ "resource": "" }
q252019
Spritify.create_image
validation
private function create_image() { $total = $this->total_size(); $sprite = imagecreatetruecolor($total["width"], $total["height"]); imagesavealpha($sprite, true); $transparent = imagecolorallocatealpha($sprite, 0, 0, 0, 127); imagefill($sprite, 0, 0, $transparent); $top = 0; foreach ($this->images as $image) { $func = "imagecreatefrom" . $image['type']; $img = $func($image["path"]); imagecopy($sprite, $img, ($total["width"] - $image["width"]), $top, 0, 0, $image["width"], $image["height"]); $top += $image["height"]; } return $sprite; }
php
{ "resource": "" }
q252020
PhpSessionMiddleware.addSessionCookie
validation
private function addSessionCookie(ResponseInterface $response):ResponseInterface { $params = session_get_cookie_params(); $cookie = new SetCookie( session_name(), session_id(), time() + $params["lifetime"], $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); return $cookie->addToResponse($response); }
php
{ "resource": "" }
q252021
PhpSessionMiddleware.addCacheLimiterHeaders
validation
private function addCacheLimiterHeaders(ResponseInterface $response):ResponseInterface { $cache = new CacheUtil(); switch (session_cache_limiter()) { case 'public': $response = $cache->withExpires($response, time() + session_cache_limiter() * 60); $response = $cache->withCacheControl($response, (new ResponseCacheControl()) ->withPublic() ->withMaxAge(session_cache_limiter() * 60) ); break; case 'private_no_expire': $response = $cache->withCacheControl($response, (new ResponseCacheControl()) ->withPrivate() ->withMaxAge(session_cache_limiter() * 60) ); break; case 'private': $response = $cache->withExpires($response, 'Thu, 19 Nov 1981 08:52:00 GMT'); $response = $cache->withCacheControl($response, (new ResponseCacheControl()) ->withPrivate() ->withMaxAge(session_cache_limiter() * 60) ); break; case 'nocache': $response = $cache->withExpires($response, 'Thu, 19 Nov 1981 08:52:00 GMT'); $response = $cache->withCacheControl($response, (new ResponseCacheControl()) ->withPrivate() ->withCachePrevention() ); $response = $response->withHeader("Pragma", "no-cache"); break; } return $response; }
php
{ "resource": "" }
q252022
AssetExtension.assetFunction
validation
public function assetFunction($asset, $serverPath = false) { /** @var Request|null $request */ $request = isset($this->container['request']) ? $this->container['request'] : null; $path = \ltrim($asset, '/\\'); $assetPath = Utils::fixPath($this->container->getRootDir() . '/' . $path); // if(!\file_exists($assetPath)) // throw new FileException("Asset '$asset' with path '$assetPath' not found"); if(!$serverPath) if($request instanceof Request) $assetPath = $request->getSchemeAndHttpHost() . '/' . $path; else $assetPath = '/' . $path; return $assetPath; }
php
{ "resource": "" }
q252023
Having.andHaving
validation
public function andHaving($column, $op, $value, $isParam = true) { $this->clauses[] = array("AND", $column, $op, $value, $isParam); return $this; }
php
{ "resource": "" }
q252024
Having.orHaving
validation
public function orHaving($column, $op, $value, $isParam = true) { $this->clauses[] = array("OR", $column, $op, $value, $isParam); return $this; }
php
{ "resource": "" }
q252025
RegexURLParser.parse
validation
public function parse(UriInterface $uri): ParsedURL { $matches = []; if(preg_match($this->pattern, $uri->getPath(), $matches) === 0) { throw new InvalidRequestURLException("Unable to parse request path: did not match regex"); } if(!($endpoint = $matches["endpoint"] ?? null)) { throw new InvalidRequestURLException("Unable to match endpoint in url"); } $element = $matches["element"] ?? null; $version = $matches["version"] ?? null; $apiKey = $matches["apiKey"] ?? null; $acceptableMimeTypes = []; if(($acceptableExtension = $matches["acceptableExtension"] ?? null)) { if(!$this->MIMEProvider) { throw new UnableToParseURLException("Unable to accept acceptable extensions"); } else { try { $acceptableMimeTypes[] = $this->MIMEProvider->provideMIME($acceptableExtension); } catch (UnableToProvideMIMEException $exception) { throw new UnableToParseURLException($exception->getMessage()); } } } return new ParsedURL($endpoint, $element, $version, $apiKey, $acceptableMimeTypes, $uri->getQuery()); }
php
{ "resource": "" }
q252026
PDO.runQuery
validation
public function runQuery(\Peyote\Query $query) { return $this->run($query->compile(), $query->getParams()); }
php
{ "resource": "" }
q252027
PDO.run
validation
public function run($query, array $params = array()) { $statement = $this->pdo->prepare($query); $statement->execute($params); return $statement; }
php
{ "resource": "" }
q252028
SearchControllerTrait.onlineHelpAction
validation
public function onlineHelpAction(Request $request) { $template = $this->searchService->getOnlineHelp($request->getLocale(), $this->getDefaultLocale()); return $this->render($template ?: 'StingerSoftEntitySearchBundle:Help:no_help.html.twig'); }
php
{ "resource": "" }
q252029
SearchControllerTrait.getSearchFacets
validation
protected function getSearchFacets(SessionInterface $session) { $facets = $session->get($this->getSessionPrefix() . '_facets', false); return $facets ? \json_decode($facets, true) : $this->getDefaultFacets(); }
php
{ "resource": "" }
q252030
SearchControllerTrait.setSearchFacets
validation
protected function setSearchFacets(SessionInterface $session, $facets) { $session->set($this->getSessionPrefix() . '_facets', \json_encode($facets)); }
php
{ "resource": "" }
q252031
UtilityTrait.quote
validation
protected function quote(/*# string */ $str)/*# : string */ { return $this->getDialect()->quote( $str, $this->getSettings()['autoQuote'] ? DialectInterface::QUOTE_YES : DialectInterface::QUOTE_NO ); }
php
{ "resource": "" }
q252032
TwigExtensionTagServiceProvider.register
validation
public function register(SilexApp $app) { $app['twig'] = $app->share($app->extend('twig', function (\Twig_Environment $twig, SilexApp $app) { $class = $this->getServiceConfig()->getProviderClass(); $twig->addExtension(new $class); return $twig; })); }
php
{ "resource": "" }
q252033
User.get
validation
public function get($idOrUser) { // All the services we need $main = $this->getServiceLocator()->get('neobazaar.service.main'); $userRepository = $main->getUserEntityRepository(); if('current' == $idOrUser) { return $userRepository->get($idOrUser, $this->getServiceLocator()); } $user = $this->getEntity($idOrUser); if(!$this->checkIfOwnerOrAdmin($user)) { throw new \Exception('Non possiedi i permessi per agire su questo documento'); } return $userRepository->get($user, $this->getServiceLocator()); }
php
{ "resource": "" }
q252034
User.delete
validation
public function delete($idOrUser, $forceLogout = true) { // All the services we need $main = $this->getServiceLocator()->get('neobazaar.service.main'); $em = $main->getEntityManager(); $user = $this->getEntity($idOrUser); $classifiedService = $this->getServiceLocator()->get('document.service.classified'); if(!$this->checkIfOwnerOrAdmin($user)) { throw new \Exception('Non possiedi i permessi per agire su questo documento'); } $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user)); $user->setState(UserEntity::USER_STATE_DELETED); $em->persist($user); $em->flush(); $documents = $user->getDocument(); foreach($documents as $document) { try { $classifiedService->delete($document); } catch(\Exception $e) { } } $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, array('user' => $user)); if($forceLogout) { $this->logout(); } return $user; }
php
{ "resource": "" }
q252035
User.passwordRecovery
validation
public function passwordRecovery(array $data) { $main = $this->getServiceLocator()->get('neobazaar.service.main'); $userRepository = $main->getUserEntityRepository(); $form = $this->getServiceLocator()->get('user.form.passwordrecovery'); $form->setData($data); if (!$form->isValid()) { throw new \Exception(serialize($form->getMessages())); } $data = $form->getData(); $email = isset($data['email']) ? $data['email'] : null; $user = $userRepository->findOneBy(array('email' => $email)); if(null === $user) { throw new \Exception('No user found'); } $userModel = $this->getServiceLocator()->get('user.model.user'); $userModel->init($user, $this->getServiceLocator()); // What's this? When the user will visit the link sent via email // we will check if the passed hash is equal of the current bcrypt hash // passed on shai. So the link will be always valid until password changes // or the hash will be updated even for the same password. $hash = $userModel->hashId . sha1($user->getPassword()); $url = $this->getServiceLocator()->get('ControllerPluginManager')->get('Url'); $event = new PasswordRecoveryEvent(__FUNCTION__, null, array( 'user' => $user, 'form' => $form, 'hash' => $hash, 'email' => $email, 'siteurl' => $url->fromRoute('home', array(), array('force_canonical' => true)) )); $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, $event); $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $event); return $user; }
php
{ "resource": "" }
q252036
User.contact
validation
public function contact(array $data, $destination = null) { $authService = $this->getServiceLocator()->get('ControllerPluginManager')->get('zfcUserAuthentication'); if(null === $destination && !$authService->hasIdentity()) { throw new \Exception("Errore si sistema."); } // Manually set email from identity $identity = $authService->getIdentity(); $data['email'] = null !== $destination ? $destination : $identity->getEmail(); $form = $this->getServiceLocator()->get('user.form.contact'); $form->setData($data); if(!$form->isValid()) { throw new \Exception(serialize($form->getMessages())); } $url = $this->getServiceLocator()->get('ControllerPluginManager')->get('Url'); $data = array_merge($form->getData(), array( 'siteurl' => $url->fromRoute('home', array(), array('force_canonical' => true)) )); $event = new UserContactEvent(__FUNCTION__, null, $data); $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, $event); $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $event); }
php
{ "resource": "" }
q252037
User.classifiedAnswer
validation
public function classifiedAnswer(array $data) { $id = isset($data['id']) ? $data['id'] : null; if(empty($id)) { throw new \Exception("Errore si sistema."); } $main = $this->getServiceLocator()->get('neobazaar.service.main'); $documentRepository = $main->getDocumentEntityRepository(); $classified = $documentRepository->getEntity($id); $classifiedModel = $this->getServiceLocator()->get('document.model.classifiedAdminListing'); $classifiedModel->init($classified, $this->getServiceLocator()); $form = $this->getServiceLocator()->get('user.form.classifiedanswer'); $form->setData($data); if(!$form->isValid()) { throw new \Exception(serialize($form->getMessages())); } $url = $this->getServiceLocator()->get('ControllerPluginManager')->get('Url'); $data = array_merge($form->getData(), array( 'siteurl' => $url->fromRoute('home', array(), array('force_canonical' => true)), 'to' => $classifiedModel->email, 'fullname' => $classifiedModel->fullname, 'title' => $classifiedModel->title, 'address' => $classifiedModel->address )); $event = new ClassifiedAnswerEvent(__FUNCTION__, null, $data); $this->getEventManager()->trigger(__FUNCTION__ . '.pre', $this, $event); $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $event); }
php
{ "resource": "" }
q252038
User.getCryptedPassword
validation
public function getCryptedPassword($password) { $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); return $bcrypt->create($password); }
php
{ "resource": "" }
q252039
User.dateToSqlFormat
validation
public function dateToSqlFormat($dateString) { $dateFormatter = new \IntlDateFormatter( \Locale::getDefault(), \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, \date_default_timezone_get(), \IntlDateFormatter::GREGORIAN, "dd MMM yyyy" ); $time = $dateFormatter->parse($dateString); $date = new \DateTime(); $date->setTimestamp($time); return $date->format('Y-m-d'); }
php
{ "resource": "" }
q252040
PageHistoricController.renderPageHistoricAction
validation
public function renderPageHistoricAction() { $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $melisKey = $this->params()->fromRoute('melisKey', ''); $view = new ViewModel(); $view->idPage = $idPage; $view->melisKey = $melisKey; return $view; }
php
{ "resource": "" }
q252041
PageHistoricController.renderPageHistoricTableAction
validation
public function renderPageHistoricTableAction() { $translator = $this->getServiceLocator()->get('translator'); $melisKey = $this->params()->fromRoute('melisKey', ''); $melisTool = $this->getServiceLocator()->get('MelisCoreTool'); $melisTool->setMelisToolKey(self::PLUGIN_INDEX, self::TOOL_KEY); $columns = $melisTool->getColumns(); $idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', '')); $container = new Container('meliscore'); $locale = $container['melis-lang-locale']; $view = new ViewModel(); $view->melisKey = $melisKey; $view->tableColumns = $columns; $view->getToolDataTableConfig = $melisTool->getDataTableConfiguration('#tableHistoricPageId'.$idPage, true); $view->idPage = $idPage; $view->tableId = 'tableHistoricPageId'.$idPage; return $view; }
php
{ "resource": "" }
q252042
PageHistoricController.renderPageHistoricContentFiltersActionsAction
validation
public function renderPageHistoricContentFiltersActionsAction() { $melisPageHistoricTable = $this->getServiceLocator()->get('MelisPagehistoricTable'); //get distinct actions on database $actions = $melisPageHistoricTable->getPageHistoricListOfActions()->toArray(); $translator = $this->getServiceLocator()->get('translator'); $options = '<option value="">' . $translator->translate('tr_melispagehistoric_filter_action_select') . '</option>'; foreach ($actions as $action) { $options .= '<option value="' . $action['action'] . '">' . $action['action'] . '</option>'; } $view = new ViewModel(); $view->options = $options; return $view; }
php
{ "resource": "" }
q252043
PageHistoricController.savePageHistoricAction
validation
public function savePageHistoricAction() { $responseData = $this->params()->fromRoute('datas', $this->params()->fromQuery('datas', '')); $idPage = isset($responseData['idPage']) ? $responseData['idPage'] : (!empty($responseData[0]['idPage'])?($responseData[0]['idPage']):0); $isNew = isset($responseData['isNew']) ? $responseData['isNew'] : (!empty($responseData[0]['isNew'])?($responseData[0]['isNew']):0); $response = array( 'idPage' => $idPage, 'isNew' => $isNew ); $this->getEventManager()->trigger('meliscmspagehistoric_historic_save_start', $this, $response); $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth'); $melisPageHistoricTable = $this->getServiceLocator()->get('MelisPageHistoricTable'); $pageAction = $this->params()->fromRoute('pageActionUsed', $this->params()->fromQuery('pageActionUsed','')); $histDatas = array(); $container = new Container('meliscms'); $datas = array(); if (isset($container['action-page-tmp']['success']) && $container['action-page-tmp']['success'] == 0) return; // Update from the different save actions done if (!empty($container['action-page-tmp'])) { if (!empty($container['action-page-tmp']['datas'])) $datas = $container['action-page-tmp']['datas']; } $description = ''; switch ($pageAction) { case 'Save': if ($isNew) { $description = 'tr_melispagehistoric_description_text_new'; } else { $description = 'tr_melispagehistoric_description_text_save'; } break; case 'Publish': $description = 'tr_melispagehistoric_description_text_publish'; break; case 'Unpublish': $description = 'tr_melispagehistoric_description_text_unpublished'; break; } if ($idPage) { $userId = (int) null; $userAuthDatas = $melisCoreAuth->getStorage()->read(); if ($userAuthDatas) $userId = $userAuthDatas->usr_id; $histDatas = array( 'hist_page_id' => $idPage, 'hist_action' => $pageAction, 'hist_date' => date('Y-m-d H:i:s'), 'hist_user_id' => $userId, 'hist_description' => $description ); $melisPageHistoricTable->save($histDatas); } $this->getEventManager()->trigger('meliscmspagehistoric_historic_save_end', $this, $histDatas); }
php
{ "resource": "" }
q252044
PageHistoricController.deletePageHistoricAction
validation
public function deletePageHistoricAction() { $responseData = $this->params()->fromRoute('datas', $this->params()->fromQuery('datas', '')); $idPage = $responseData[0]['idPage']; $response = array('idPage' => $idPage); $this->getEventManager()->trigger('meliscmspagehistoric_historic_delete_start', $this, $response); $melisPageHistoricTable = $this->getServiceLocator()->get('MelisPageHistoricTable'); $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth'); $userId = (int) null; $userAuthDatas = $melisCoreAuth->getStorage()->read(); if($userAuthDatas) $userId = $userAuthDatas->usr_id; $histDatas = array( 'hist_page_id' => $idPage, 'hist_action' => 'Delete', 'hist_date' => date('Y-m-d H:i:s'), 'hist_user_id' => $userId, 'hist_description' => 'tr_melispagehistoric_action_text_Delete' ); $melisPageHistoricTable->save($histDatas); $this->getEventManager()->trigger('meliscmspagehistoric_historic_delete_end', $this, $responseData); }
php
{ "resource": "" }
q252045
PageHistoricController.getBackOfficeUsersAction
validation
public function getBackOfficeUsersAction() { $melisPageHistoricTable = $this->getServiceLocator()->get('MelisPageHistoricTable'); $users = $melisPageHistoricTable->getUsers()->toArray(); return new JsonModel(array( 'users' => $users, )); }
php
{ "resource": "" }
q252046
StatementAbstract.build
validation
protected function build()/*# : string */ { // settings $settings = $this->getSettings(); // before build() $this->beforeBuild(); // configs $configs = $this->getConfig(); // start of result array $result = [$this->getType()]; // seperator & indent $sp = $settings['seperator']; $in = $settings['indent']; $si = $sp . $in; foreach ($configs as $pos => $part) { // before clause if (isset($this->before[$pos])) { $result[] = join($sp, $this->before[$pos]); } $built = call_user_func([$this, $part['func']]); if (!empty($built)) { $prefix = $part['prefix'] . (empty($part['prefix']) ? ($part['indent'] ? $in : '') : $si); $result[] = $prefix . join($part['join'] . $si, $built); } // after clause if (isset($this->after[$pos])) { $result[] = join($sp, $this->after[$pos]); } } return join($sp, $result); }
php
{ "resource": "" }
q252047
StatementAbstract.getConfig
validation
protected function getConfig()/*# : array */ { $config = array_replace($this->config, $this->dialect_config); ksort($config); return $config; }
php
{ "resource": "" }
q252048
CreateTableTrait.select
validation
public function select()/*# : SelectStatementInterface */ { $cols = func_get_args(); return $this->getBuilder()->setPrevious($this) ->select(false)->col($cols); }
php
{ "resource": "" }
q252049
RestfulApi.isRender
validation
public static function isRender($request) { return true; $accept = $request->header('accept') ?? ''; if (static::isHas($accept, 'json') || static::isHas($accept, 'api')) { return true; } else if (static::isHas($accept, 'html') || static::isHas($accept, 'xml') || static::isHas($accept, 'text')) { return false; } else if ($request->header('x-ddv-restful-api')) { return true; } else if ($request->header('authorization')) { foreach ($request->headers->keys() as $value) { if (static::isHas($accept, 'x-ddv-')) { return true; } } } return false; }
php
{ "resource": "" }
q252050
CheckboxSetField.__templates
validation
protected function __templates($customTemplate = null, $customTemplateSuffix = null) { $templates = SSViewer::get_templates_by_class($this->class, $customTemplateSuffix, \FormField::class); //$templates = \SSViewer::get_templates_by_class($this->class, '', __CLASS__); if (!$templates) { throw new \Exception("No template found for {$this->class}"); } if($customTemplate) { array_unshift($templates, $customTemplate); } return $templates; }
php
{ "resource": "" }
q252051
DefaultController.actionIndex
validation
public function actionIndex($option = null) { // todo: вынести в конфиг домена $allNames = [ 'web/assets', 'runtime', 'runtime/cache', 'tests/_output', ]; $answer = Select::display('Select objects', $allNames, 1); $result = ClearHelper::run($answer); if($result) { Output::items($result, "Clear completed: " . count($result) . " objects"); } else { Output::block("Not fount object for clear!"); } }
php
{ "resource": "" }
q252052
ParameterAwareTrait.bindValues
validation
protected function bindValues( /*# string */ $sql, array $settings )/*# : string */ { $bindings = &$this->bindings; $escape = $this->getEscapeCallable($settings['escapeFunction']); $params = $this->getBuilder()->getPlaceholderMapping(); // real function $function = function($v) use ($settings, &$bindings, $escape) { // positioend parameters if ($settings['positionedParam']) { $bindings[] = $v; return '?'; // named parameters } elseif ($settings['namedParam'] && isset($v[0]) && ':' == $v[0]) { return $v; // use value, but NOT escaping int or float } elseif (is_numeric($v) && !is_string($v)) { return $v; // use value, but escape it @todo boolean? } else { return $escape($v); } }; // replace placeholders with '?' or real value return preg_replace_callback( '/\b__PH_[0-9]++__\b/', function($m) use (&$params, $function) { return $function($params[$m[0]]); }, $sql); }
php
{ "resource": "" }
q252053
AbstractFinisher.callAPI
validation
protected function callAPI($data) { $apiUtility = new PipedriveApi($this->apiEndpoint); $apiUtility->setData($data); $formState = $this->finisherContext->getFormRuntime()->getFormState(); $response = $apiUtility->execute(); if($response->data->id) { $formState->setFormValue($this->getIdentifier() . ".ID", $response->data->id); return true; } else { throw new FinisherException("Something went wrong while calling the API!"); } }
php
{ "resource": "" }
q252054
InstanceWrapperTrait.callMethodInWrappedInst
validation
public function callMethodInWrappedInst($method, $args) { $i = $this->getWrappedInst(); if (method_exists($i, $method)) { return call_user_method_array($method, $i, $args); } throw new UnknownMethodException('Calling unknown method: ' . get_class($i) . "::$method()"); }
php
{ "resource": "" }
q252055
DataStoreAwareContainerTrait._setDataStore
validation
protected function _setDataStore($dataStore) { if (!is_null($dataStore)) { $dataStore = $this->_normalizeContainer($dataStore); } $this->dataStore = $dataStore; }
php
{ "resource": "" }
q252056
Client.authenticate
validation
public function authenticate($authMethod, $options) { $sm = $this->getServiceManager(); $authListener = $sm->get($authMethod); $authListener->setOptions($options); $this->getHttpClient()->getEventManager()->attachAggregate($authListener); }
php
{ "resource": "" }
q252057
Console.write
validation
public static function write($messages, $style = '', $length = 0, $suffix = '') { if (self::$silent) { return; } if (!is_array($messages)) { $messages = [(string)$messages]; } if (count($messages) > 0) { foreach ($messages as $message) { if ($length > 0) { $message = str_pad($message, $length, ' ', STR_PAD_RIGHT); } print(Style::applyStyle($message, $style)); if ($suffix != '') { print($suffix); } } } }
php
{ "resource": "" }
q252058
Console.info
validation
public static function info($messages, $linebreak = true, $length = 0) { $separator = $linebreak ? "\n" : ''; self::write($messages, 'info', $length, $separator); }
php
{ "resource": "" }
q252059
Console.error
validation
public static function error($messages, $linebreak = true, $length = 0) { $separator = $linebreak ? "\n" : ''; self::write($messages, 'error', $length, $separator); }
php
{ "resource": "" }
q252060
Console.comment
validation
public static function comment($messages, $linebreak = true, $length = 0) { $separator = $linebreak ? "\n" : ''; self::write($messages, 'comment', $length, $separator); }
php
{ "resource": "" }
q252061
Console.warning
validation
public static function warning($messages, $linebreak = true, $length = 0) { $separator = $linebreak ? "\n" : ''; self::write($messages, 'warning', $length, $separator); }
php
{ "resource": "" }
q252062
Console.title
validation
public static function title($messages, $linebreak = true, $length = 0) { $separator = $linebreak ? "\n" : ''; self::write($messages, 'title', $length, $separator); }
php
{ "resource": "" }
q252063
Console.block
validation
public static function block($messages, $style) { if (is_string($messages)) { $messages = [$messages]; } if (count($messages) > 0) { self::writeln(str_repeat(' ', self::$lineLength), $style); foreach ($messages as $message) { $message = ' ' . $message; while (strlen($message) < self::$lineLength) { $message .= ' '; } self::writeln($message, $style); } self::writeln(str_repeat(' ', self::$lineLength), $style); } }
php
{ "resource": "" }
q252064
Console.ask
validation
public static function ask($question, $defaultValue = null, $secret = false) { $value = ''; while (trim($value) == '') { self::writeln(''); self::write(' ' . $question, 'info'); if ($defaultValue !== null) { self::write(' ['); self::write($defaultValue, 'comment'); self::write(']'); } self::writeln(':'); if ($secret) { self::write(' > '); if (self::$testValue === null) { // @codeCoverageIgnoreStart system('stty -echo'); $value = trim(fgets(STDIN)); system('stty echo'); // @codeCoverageIgnoreEnd } else { $value = self::$testValue; } } else { if (self::$testValue === null) { // @codeCoverageIgnoreStart $value = readline(' > '); // @codeCoverageIgnoreEnd } else { $value = self::$testValue; } } if (trim($value) == '') { // @codeCoverageIgnoreStart $value = $defaultValue; // @codeCoverageIgnoreEnd } if (trim($value) == '') { // @codeCoverageIgnoreStart self::writeln(''); self::block('[ERROR] A value is required', 'error'); // @codeCoverageIgnoreEnd } self::writeln(''); } return trim($value); }
php
{ "resource": "" }
q252065
Console.confirm
validation
public static function confirm($question, $allowShort, $defaultValue = false) { $value = $defaultValue ? 'yes' : 'no'; $value = self::ask($question . ' (yes/no)', $value); return $value == 'yes' || ($value == 'y' && $allowShort); }
php
{ "resource": "" }
q252066
Console.choice
validation
public static function choice($question, array $choices, $defaultValue = null) { $value = ''; while (trim($value) == '') { // Write prompt. self::writeln(''); self::write(' ' . $question, 'info'); if ($defaultValue !== null) { // @codeCoverageIgnoreStart self::write(' ['); self::write((string)$defaultValue, 'comment'); self::write(']'); // @codeCoverageIgnoreEnd } self::writeln(':'); // Write choices. if (count($choices) > 0) { foreach ($choices as $index => $choice) { self::write(' ['); self::write((string)($index + 1), 'comment'); self::writeln('] ' . $choice); } } // Input. if (self::$testValue === null) { // @codeCoverageIgnoreStart $value = readline(' > '); // @codeCoverageIgnoreEnd } else { $value = self::$testValue; } if (trim($value) == '') { // @codeCoverageIgnoreStart $value = $defaultValue; // @codeCoverageIgnoreEnd } if (!isset($choices[intval($value) - 1])) { // @codeCoverageIgnoreStart self::writeln(''); self::block('[ERROR] Value "' . $value . '" is invalid', 'error'); $value = ''; // @codeCoverageIgnoreEnd } elseif (trim($value) == '') { // @codeCoverageIgnoreStart self::writeln(''); self::block('[ERROR] A value is required', 'error'); // @codeCoverageIgnoreEnd } self::writeln(''); } return trim($value); }
php
{ "resource": "" }
q252067
Console.table
validation
public static function table(array $rows, array $headers = []) { $table = new Table(); $table->setRows($rows); if (count($headers) > 0) { $table->setHeaders($headers); } $output = $table->render(); self::writeln($output); }
php
{ "resource": "" }
q252068
Console.words
validation
public static function words(array $words, $style = '', $separator = ', ') { self::write(implode($separator, $words), $style); }
php
{ "resource": "" }
q252069
Fs.sanitizeName
validation
public static function sanitizeName(string $name): string { $basename = basename($name); $dir = ($basename === $name) ? null : dirname($name); $basename = preg_replace("/[^a-zA-Z0-9-_.]/", "_", $basename); return ($dir === null) ? $basename : "$dir/$basename"; }
php
{ "resource": "" }
q252070
Fs.dir
validation
public static function dir(string $path): fs\entity\DirEntity { return (new fs\entity\DirEntity($path))->normalize(); }
php
{ "resource": "" }
q252071
Fs.file
validation
public static function file(string $path): fs\entity\FileEntity { return (new fs\entity\FileEntity($path))->normalize(); }
php
{ "resource": "" }
q252072
Fs.createFromSplFileInfo
validation
public static function createFromSplFileInfo(\SplFileInfo $info) { $realpath = $info->getRealPath(); if ($info->isFile()) { return new fs\entity\FileEntity($realpath); } return new fs\entity\DirEntity($realpath); }
php
{ "resource": "" }
q252073
StateController.actionIndex
validation
public function actionIndex() { $searchModel = new SearchState(Yii::$app->request->get()); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel , 'dataProvider' => $dataProvider ]); }
php
{ "resource": "" }
q252074
Join.on
validation
public function on($column1, $op, $column2) { if ($this->active_join === null) { throw new \Peyote\Exception("You need to start a join before calling \Peyote\Join::on()"); } list($table, $type) = $this->active_join; $this->active_join = null; $this->joins[] = array("ON", $table, $type, $column1, $op, $column2); return $this; }
php
{ "resource": "" }
q252075
Join.using
validation
public function using($column) { if ($this->active_join === null) { throw new \Peyote\Exception("You need to start a join before calling \Peyote\Join::using()"); } list($table, $type) = $this->active_join; $this->active_join = null; $this->joins[] = array("USING", $table, $type, $column); return $this; }
php
{ "resource": "" }
q252076
Join.compileOn
validation
private function compileOn(array $join) { $sql = array(); list($on, $table, $type, $c1, $op, $c2) = $join; if ($type !== null) { $sql[] = $type; } array_push($sql, "JOIN", $table, "ON", $c1, $op, $c2); return join(' ', $sql); }
php
{ "resource": "" }
q252077
Join.compileUsing
validation
private function compileUsing(array $join) { $sql = array(); list($using, $table, $type, $column) = $join; if ($type !== null) { $sql[] = $type; } array_push($sql, "JOIN", $table, "USING({$column})"); return join(' ', $sql); }
php
{ "resource": "" }
q252078
OrderByTrait.buildOrderBy
validation
protected function buildOrderBy()/*# : array */ { $result = []; foreach ($this->clause_orderby as $ord) { $result[] = $ord[0] ? $ord[1] : ($this->quote($ord[1]) . ' ' . $ord[2]); } return $result; }
php
{ "resource": "" }
q252079
File.setRaw
validation
protected function setRaw($Key, $Val, $expire = 0) { $CacheFile = $this->getCacheFile($Key); return file_put_contents($CacheFile, serialize($Val)) > 0; }
php
{ "resource": "" }
q252080
File.deleteRaw
validation
protected function deleteRaw($Key) { $CacheFile = $this->getCacheFile($Key); if (file_exists($CacheFile)) { return unlink($CacheFile); } return true; }
php
{ "resource": "" }
q252081
File.getRaw
validation
protected function getRaw($Key) { $CacheFile = $this->getCacheFile($Key); if (!file_exists($CacheFile)) { return false; } return unserialize(file_get_contents($CacheFile)); }
php
{ "resource": "" }
q252082
HAL.sayHello
validation
public function sayHello() { $text = $this->getHALLogo(); if ($this->showText) { $text .= $this->getHelloDave(); } $lines = explode("\n", $text); $spaces = ''; if ($this->center) { $max_length = 0; foreach ($lines as $line) { $max_length = max($max_length, Helper::strlenWithoutDecoration($this->output->getFormatter(), $line)); } $numberOfSpaces = floor(($this->screenSize[0] - $max_length) / 2); if ($numberOfSpaces > 0) { $spaces = str_repeat(' ', $numberOfSpaces); } } foreach ($lines as $line) { $this->output->writeln($spaces.$line); } }
php
{ "resource": "" }
q252083
ProductDoctrineEventSubscriber.refreshProductSellPrices
validation
protected function refreshProductSellPrices(ProductInterface $product) { $sellPrice = $product->getSellPrice(); $grossAmount = $sellPrice->getGrossAmount(); $discountedGrossAmount = $sellPrice->getDiscountedGrossAmount(); $taxRate = $product->getSellPriceTax()->getValue(); $netAmount = TaxHelper::calculateNetPrice($grossAmount, $taxRate); $discountedNetAmount = TaxHelper::calculateNetPrice($discountedGrossAmount, $taxRate); $sellPrice->setTaxRate($taxRate); $sellPrice->setTaxAmount($grossAmount - $netAmount); $sellPrice->setNetAmount($netAmount); $sellPrice->setDiscountedTaxAmount($discountedGrossAmount - $discountedNetAmount); $sellPrice->setDiscountedNetAmount($discountedNetAmount); }
php
{ "resource": "" }
q252084
ProductDoctrineEventSubscriber.refreshProductVariantSellPrice
validation
protected function refreshProductVariantSellPrice(VariantInterface $variant) { $product = $variant->getProduct(); $sellPrice = $product->getSellPrice(); $grossAmount = $this->calculateAttributePrice($variant, $sellPrice->getGrossAmount()); $discountedGrossAmount = $this->calculateAttributePrice($variant, $sellPrice->getDiscountedGrossAmount()); $taxRate = $product->getSellPriceTax()->getValue(); $netAmount = TaxHelper::calculateNetPrice($grossAmount, $taxRate); $discountedNetAmount = TaxHelper::calculateNetPrice($discountedGrossAmount, $taxRate); $productAttributeSellPrice = $variant->getSellPrice(); $productAttributeSellPrice->setTaxRate($taxRate); $productAttributeSellPrice->setTaxAmount($grossAmount - $netAmount); $productAttributeSellPrice->setGrossAmount($grossAmount); $productAttributeSellPrice->setNetAmount($netAmount); $productAttributeSellPrice->setDiscountedGrossAmount($discountedGrossAmount); $productAttributeSellPrice->setDiscountedTaxAmount($discountedGrossAmount - $discountedNetAmount); $productAttributeSellPrice->setDiscountedNetAmount($discountedNetAmount); $productAttributeSellPrice->setValidFrom($sellPrice->getValidFrom()); $productAttributeSellPrice->setValidTo($sellPrice->getValidTo()); $productAttributeSellPrice->setCurrency($sellPrice->getCurrency()); }
php
{ "resource": "" }
q252085
ProductDoctrineEventSubscriber.calculateAttributePrice
validation
protected function calculateAttributePrice(VariantInterface $variant, $amount) { $modifierType = $variant->getModifierType(); $modifierValue = $variant->getModifierValue(); switch ($modifierType) { case '+': $amount = $amount + $modifierValue; break; case '-': $amount = $amount - $modifierValue; break; case '%': $amount = $amount * ($modifierValue / 100); break; } return round($amount, 2); }
php
{ "resource": "" }
q252086
ProductDoctrineEventSubscriber.refreshProductBuyPrices
validation
protected function refreshProductBuyPrices(ProductInterface $product) { $buyPrice = $product->getBuyPrice(); $grossAmount = $buyPrice->getGrossAmount(); $taxRate = $product->getBuyPriceTax()->getValue(); $netAmount = TaxHelper::calculateNetPrice($grossAmount, $taxRate); $buyPrice->setTaxRate($taxRate); $buyPrice->setTaxAmount($grossAmount - $netAmount); $buyPrice->setNetAmount($netAmount); }
php
{ "resource": "" }
q252087
Pluralize.restoreWordCase
validation
protected function restoreWordCase($token) { if ($token === strtoupper($token)) { return function ($word) { return strtoupper($word); }; } if ($token === ucfirst($token)) { return function ($word) { return ucfirst($word); }; } return function ($word) { return $word; }; }
php
{ "resource": "" }
q252088
AssetConverter.runCommand
validation
protected function runCommand($command, $basePath, $asset, $result) { $command = Yii::getAlias($command); $command = strtr($command, [ '{from}' => escapeshellarg("$basePath/$asset"), '{to}' => escapeshellarg("$basePath/$result"), ]); $descriptor = [ 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $pipes = []; $proc = proc_open($command, $descriptor, $pipes, $basePath); $stdout = stream_get_contents($pipes[1]); $stderr = stream_get_contents($pipes[2]); foreach ($pipes as $pipe) { fclose($pipe); } $status = proc_close($proc); if ($status === 0) { Yii::trace("Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", __METHOD__); } elseif (YII_DEBUG) { throw new Exception("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr"); } else { Yii::error("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr", __METHOD__); } return $status === 0; }
php
{ "resource": "" }
q252089
FromTrait.getTableName
validation
protected function getTableName($returnAlias = false)/*# : string */ { $result = ''; foreach ($this->clause_table as $k => $v) { if (!is_int($k) && $returnAlias) { return $k; } else { return $v; } } return $result; }
php
{ "resource": "" }
q252090
EntityToDocumentMapper.fillDocument
validation
protected function fillDocument(Document $document, object $object) : bool { if($object instanceof SearchableEntity) { return $object->indexEntity($document); } $mapping = $this->getMapping(\get_class($object)); $accessor = PropertyAccess::createPropertyAccessor(); foreach($mapping as $fieldName => $propertyPath) { $document->addField($fieldName, $accessor->getValue($object, $propertyPath)); } return true; }
php
{ "resource": "" }
q252091
EntityToDocumentMapper.getMapping
validation
protected function getMapping(string $clazz) : array { if(isset($this->cachedMapping[$clazz])) { return $this->cachedMapping[$clazz]; } $ref = new \ReflectionClass($clazz); $mapping = array(); foreach($this->mapping as $className => $config) { if($clazz === $className || $ref->isSubclassOf($className)) { $mapping = \array_merge($mapping, $config); } } $this->cachedMapping[$clazz] = $mapping; return $mapping; }
php
{ "resource": "" }
q252092
Install.executeProcess
validation
public function executeProcess($command, $beforeNotice = false, $afterNotice = false):void { $this->echo('info', $beforeNotice ? ' '.$beforeNotice : $command); $process = new Process($command, null, null, null, $this->option('timeout'), null); $process->run(function ($type, $buffer) { if (Process::ERR === $type) { $this->echo('comment', $buffer); } else { $this->echo('line', $buffer); } }); // executes after the command finishes if (!$process->isSuccessful()) { throw new ProcessFailedException($process); } if ($this->progressBar) { $this->progressBar->advance(); } if ($afterNotice) { $this->echo('info', $afterNotice); } }
php
{ "resource": "" }
q252093
Install.echo
validation
public function echo($type, $content) { if ($this->option('debug') == false) { return; } // skip empty lines if (trim($content)) { $this->{$type}($content); } }
php
{ "resource": "" }
q252094
Limit.setLimit
validation
public function setLimit($num, $offset = 0) { $this->limit = (int) $num; $this->offset = (int) $offset; }
php
{ "resource": "" }
q252095
ColDefinitionTrait.buildCol
validation
protected function buildCol()/*# : array */ { $result = []; foreach ($this->col_defs as $col) { $res = []; // name $res[] = $this->quote($col['name']); // type $res[] = $col['type']; // not null ? if (isset($col['notNull'])) { $res[] = 'NOT NULL' . ($col['notNull'] ? (' '.$col['notNull']) : ''); } // default ? if (isset($col['default'])) { $res[] = 'DEFAULT ' . ($col['default'][1] ? $col['default'][0] : $this->processValue($col['default'][0])); } // auto if (isset($col['autoincrement'])) { $res[] = 'AUTO_INCREMENT'; } // unique if (isset($col['unique'])) { $res[] = 'UNIQUE' . ($col['unique'] ? (' ' . $col['unique']) : ''); } // primary if (isset($col['primary'])) { $res[] = 'PRIMARY KEY' . ($col['primary'] ? (' ' . $col['primary']) : ''); } // other constraints if (isset($col['constraint'])) { $res[] = join(' ', $col['constraint']); } array_walk($res, function($m) { return trim($m); }); $result[] = join(' ', $res); } return $result; }
php
{ "resource": "" }
q252096
Location.getLocationString
validation
public function getLocationString() { $normalized = ''; if ($this->city !== null) { $normalized .= $this->city->name; } if ($this->region !== null) { $normalized .= ' ' . $this->region->name; } if ($this->postal_code !== null) { $normalized .= ' ' . $this->postal_code; } return $normalized; }
php
{ "resource": "" }
q252097
Container.has
validation
public function has(string $typeName): bool { if (isset($this->shared[$typeName]) || isset($this->definitions[$typeName])) { return true; } if (!isset($this->typeCache[$typeName])) { if (\class_exists($typeName) || \interface_exists($typeName, false)) { $this->typeCache[$typeName] = new \ReflectionClass($typeName); } else { $this->typeCache[$typeName] = false; } } return $this->typeCache[$typeName] !== false && $this->typeCache[$typeName]->isInstantiable(); }
php
{ "resource": "" }
q252098
Container.getMarked
validation
public function getMarked(string $marker): array { if (!\is_subclass_of($marker, Marker::class)) { throw new \InvalidArgumentException(\sprintf('Marker implementation %s must extend %s', $marker, Marker::class)); } if (!isset($this->marked[$marker])) { $this->cacheMarkers($marker); } return \array_map(function (array $marked) { return $this->shared[$marked[0]->typeName] ?? $this->get($marked[0]->typeName); }, $this->marked[$marker]); }
php
{ "resource": "" }
q252099
Container.eachMarked
validation
public function eachMarked(callable $callback, $result = null) { $ref = new \ReflectionFunction($callback); $params = $ref->getParameters(); if (\count($params) < 2) { throw new \InvalidArgumentException(\sprintf('Callback for marker processing must declare at least 2 arguments (object and marker)')); } try { $markerType = $params[1]->getClass(); } catch (\ReflectionException $e) { throw new \InvalidArgumentException(\sprintf('Marker class not found: %s', $params[1]->getType()), 0, $e); } if ($markerType === null) { throw new \InvalidArgumentException(\sprintf('Argument #2 of marker callback needs to declare a type-hint for the marker')); } $marker = $markerType->getName(); if (!$markerType->isSubclassOf(Marker::class)) { throw new \InvalidArgumentException(\sprintf('Marker implementation %s must extend %s', $marker, Marker::class)); } if (!isset($this->marked[$marker])) { $this->cacheMarkers($marker); } foreach ($this->marked[$marker] as list ($definition, $registration)) { $result = $callback($this->shared[$definition->typeName] ?? $this->get($definition->typeName), clone $registration, $result); } return $result; }
php
{ "resource": "" }