_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q263800
Tokenizer._findEndOfQuotedString
test
protected function _findEndOfQuotedString($quote, $start) { $nextEscape = strpos($this->_css, '\\', $start + 1); $end = strpos($this->_css, $quote, $start + 1); if ($end === false) { // Invalid string return false; } while ($nextEscape !== false && $nextEscape < $end) { if ($end === $nextEscape + 1) { $end = strpos($this->_css, $quote, $end + 1); if ($end === false) { // Invalid string return false; } } $nextEscape = strpos($this->_css, '\\', $nextEscape + 2); } return $end + 1; }
php
{ "resource": "" }
q263801
Tokenizer._findEndOfURL
test
protected function _findEndOfURL($start = 0) { $length = strlen($this->_css); $index = $start + 4; while ($index < $length) { $next = substr($this->_css, $index, 1); switch ($next) { case '"': case '\'': // quoted url $end = $this->_findEndOfQuotedString($next, $index); if ($end === false) { return new ParseError('Incomplete string', $this->_css, $index); } $end = strpos($this->_css, ')', $end); return $end === false ? new ParseError('Cannot find end of URL', $this->_css, $start) : $end + 1; case ' ': case "\t": case "\r": case "\n": // skip whitespace $index ++; break; default: // unquoted url while (true) { switch ($next) { case ')': return $index + 1; case '"': case '\'': case '(': case ' ': case "\t": case "\r": case "\n": return new ParseError('Invalid URL', $this->_css, $start); default: if (ord(substr($this->_css, $index, 1)) < 32) { return new ParseError('Invalid URL', $this->_css, $start); } } $index ++; if ($index >= $length) { return new ParseError('Cannot find end of URL', $this->_css, $start); } $next = substr($this->_css, $index, 1); } } } return new ParseError('Cannot find end of URL', $this->_css, $start); }
php
{ "resource": "" }
q263802
Tokenizer._checkRule
test
protected function _checkRule($words, $extra, $ignoreErrors) { $pairs = $this->_findRulePairs($words); if (is_bool($pairs)) { $value = $this->_mergeWords($words) . $extra; if (!strlen($value)) { return false; } $index = $words[0]['index']; if ($pairs === false && !$this->ignoreErrors && !$ignoreErrors) { $this->errors[] = new ParseError('Invalid css rule', $this->_css, $index); } return [ 'token' => 'code', 'code' => $value, 'index' => $index, ]; } return $pairs; }
php
{ "resource": "" }
q263803
Tokenizer._mergeWords
test
protected function _mergeWords($words) { $value = ''; foreach ($words as $word) { $value .= $word['text']; } return trim($value); }
php
{ "resource": "" }
q263804
Tokenizer._checkSelectors
test
protected function _checkSelectors($words) { $selectors = $this->_getSelectors($words); $result = [ 'token' => '{', 'code' => $this->_mergeWords($words), 'index' => $words[0]['index'], ]; if (!count($selectors)) { return $result; } if (substr($selectors[0], 0, 1) === '@') { $split = preg_split('/\s+/', $selectors[0]); $result['atRule'] = substr($split[0], 1); $selectors[0] = trim(substr($selectors[0], 1 + strlen($result['atRule']))); $result['atValues'] = $selectors; } else { $result['selectors'] = $selectors; } return $result; }
php
{ "resource": "" }
q263805
Tokenizer._getSelectors
test
protected function _getSelectors($words) { $selectors = []; $selector = ''; foreach ($words as $word) { if ($word['type'] !== 'text') { $selector .= $word['text']; continue; } $list = explode(',', $word['text']); $selector .= array_shift($list); while (count($list) > 0) { $selectors[] = trim($selector); $selector = array_shift($list); } } $selectors[] = trim($selector); $results = []; foreach ($selectors as $row) { if (strlen($row) > 0) { $results[] = $row; } } return $results; }
php
{ "resource": "" }
q263806
Tokenizer._parseTokens
test
protected function _parseTokens($item) { $results = []; while ($item !== null) { switch ($item['token']) { case '}': return $results; case '{': $item['children'] = $this->_parseTokens(array_shift($this->_tokens)); $results[] = $item; break; default: $results[] = $item; } $item = array_shift($this->_tokens); } return $results; }
php
{ "resource": "" }
q263807
Helper.setCurrentAppKeyForRequest
test
public static function setCurrentAppKeyForRequest($key, Request $request = null) { $request = $request ?: app('request'); $request->attributes->set(static::CURRENT_APP_KEY, $key); return $request; }
php
{ "resource": "" }
q263808
Helper.getCurrentAppKey
test
public static function getCurrentAppKey(Request $request = null) { $request = $request ?: app('request'); return $request->attributes->get(static::CURRENT_APP_KEY); }
php
{ "resource": "" }
q263809
Helper.addAcceptableJsonTypeForRequest
test
public static function addAcceptableJsonTypeForRequest(Closure $determination = null, Closure $callback = null) { app()->rebinding('request', function ($app, Request $request) use ($determination, $callback) { if (is_null($determination) || $determination($request)) { $accept = $request->headers->get('Accept'); if (! Str::contains($accept, ['/json', '+json'])) { $accept = rtrim('application/json,'.$accept, ','); $request->headers->set('Accept', $accept); $request->server->set('HTTP_ACCEPT', $accept); $_SERVER['HTTP_ACCEPT'] = $accept; if ($callback) { $callback($request); } } } }); }
php
{ "resource": "" }
q263810
GetMaxDateBalance.build
test
public function build(\Magento\Framework\DB\Select $source = null) { /* this is root query builder (started from SELECT) */ $result = $this->conn->select(); /* define tables aliases for internal usage (in this method) */ $asAcc = self::AS_ACC; $asBal = self::AS_BAL; /* FROM prxgt_acc_balance */ $tbl = $this->resource->getTableName(self::E_BAL); // name with prefix $as = $asBal; // alias for 'current table' (currently processed in this block of code) $exp = $this->expMax(); $cols = [ self::A_MAX_DATE => $exp ]; $result->from([$as => $tbl], $cols); // standard names for the variables /* LEFT JOIN prxgt_acc_account */ $tbl = $this->resource->getTableName(self::E_ACC); $as = $asAcc; $cols = []; /* bind account to transaction as debit account to bind asset type below (credit acc. has the same type) */ $cond = "$as." . EAcc::A_ID . "=$asBal." . EBal::A_ACCOUNT_ID; $result->joinLeft([$as => $tbl], $cond, $cols); return $result; }
php
{ "resource": "" }
q263811
Unpublish.unpublishPost
test
public function unpublishPost($postId, $action = 'trash') { $postStatus = get_post_status($postId); if (!in_array($postStatus, array('publish', 'private', 'password', 'draft'))) { return false; } switch ($action) { case 'draft': wp_update_post(array( 'ID' => (int)$postId, 'post_status' => 'draft' )); break; default: wp_trash_post($postId); break; } return true; }
php
{ "resource": "" }
q263812
Unpublish.saveUnpublish
test
public function saveUnpublish($postId) { // Do not proceed if post is a revision if (wp_is_post_revision($postId)) { return false; } $args = array( 'post_id' => $postId ); wp_unschedule_event(wp_next_scheduled('unpublish_post', $args), 'unpublish_post', $args); if (!isset($_POST['unpublish-active']) || $_POST['unpublish-active'] != 'true') { delete_post_meta($postId, 'unpublish-date'); delete_post_meta($postId, 'unpublish-action'); return; } $offset = get_option('gmt_offset'); if ($offset > -1) { $offset = '-' . $offset; } else { $offset = '+' . (1 * abs($offset)); } $unpublishDate = $_POST['unpublish-aa'] . '-' . $_POST['unpublish-mm'] . '-' . $_POST['unpublish-jj'] . ' ' . $_POST['unpublish-hh'] . ':' . $_POST['unpublish-mn'] . ':00'; $unpublishTime = strtotime($offset . ' hours', strtotime($unpublishDate)); $unpubParts = array( 'aa' => $_POST['unpublish-aa'], 'mm' => $_POST['unpublish-mm'], 'jj' => $_POST['unpublish-jj'], 'hh' => $_POST['unpublish-hh'], 'mn' => $_POST['unpublish-mn'] ); $action = isset($_POST['unpublish-action']) && !empty($_POST['unpublish-action']) ? $_POST['unpublish-action'] : 'trash'; update_post_meta($postId, 'unpublish-date', $unpubParts); update_post_meta($postId, 'unpublish-action', $action); wp_schedule_single_event($unpublishTime, 'unpublish_post', array( 'post_id' => $postId, 'action' => $action )); }
php
{ "resource": "" }
q263813
Unpublish.initScheduler
test
public function initScheduler($postId) : bool { $active = true; $post_types = get_field('content_scheduler_posttypes', 'option'); if (is_array($post_types) && !empty($post_types)) { $current = get_post_type($postId); $active = in_array($current, $post_types); } return $active; }
php
{ "resource": "" }
q263814
Token.generate
test
public function generate($key, $secret, $time) { if ($key && $secret && $time) { return substr(md5($key.$secret.$time), 10, 20); } }
php
{ "resource": "" }
q263815
Token.generateForKey
test
public function generateForKey($key, $time) { if ($secret = $this->client->getAppSecretForKey($key)) { return $this->generate($key, $secret, $time); } }
php
{ "resource": "" }
q263816
Token.verify
test
public function verify($token, $key, $time) { return $token && $key && $time && $token === $this->generateForKey($key, $time); }
php
{ "resource": "" }
q263817
Token.generateHttpHeaders
test
public function generateHttpHeaders($appKey, $time = null) { $headers = []; foreach ($this->generateDataForKey($appKey, $time) as $key => $value) { $headers['X-API-'.strtoupper($key)] = $value; } return $headers; }
php
{ "resource": "" }
q263818
Token.generateQueryData
test
public function generateQueryData($appKey, $time = null) { $query = []; foreach ($this->generateDataForKey($appKey, $time) as $key => $value) { $query['_'.$key] = $value; } return $query; }
php
{ "resource": "" }
q263819
SysCustomer.getId
test
public function getId() { if (is_null($this->cacheId)) { $conn = $this->daoGeneric->getConnection(); $entity = Cfg::ENTITY_MAGE_CUSTOMER; $cols = [Cfg::E_CUSTOMER_A_ENTITY_ID]; $quoted = $conn->quote(Cfg::SYS_CUSTOMER_EMAIL); $where = Cfg::E_CUSTOMER_A_EMAIL . '=' . $quoted; $rs = $this->daoGeneric->getEntities($entity, $cols, $where); $found = reset($rs); $this->cacheId = $found[Cfg::E_CUSTOMER_A_ENTITY_ID]; } return $this->cacheId; }
php
{ "resource": "" }
q263820
Builder.fit
test
public function fit($gravity = null) { $this->manipulations['c'] = 'fit'; if (!is_null($gravity)) { $this->manipulations['g'] = $gravity; } return $this; }
php
{ "resource": "" }
q263821
Builder.getManipulations
test
public function getManipulations() { $manipulations = array_map(function ($key) { return $key . '_' . $this->manipulations[$key]; }, array_keys($this->manipulations ?: [])); return implode(',', $manipulations); }
php
{ "resource": "" }
q263822
Transaction.create
test
public function create($data) { $result = parent::create($data); if ($result) { /* update balances for accounts */ if (is_array($data)) { $data = new Entity($data); } $value = $data->getValue(); $creditAccId = $data->getCreditAccId(); $debitAccId = $data->getDebitAccId(); $this->repoAccount->updateBalance($creditAccId, 0 + $value); $this->repoAccount->updateBalance($debitAccId, 0 - $value); } return $result; }
php
{ "resource": "" }
q263823
TFillable.fill
test
public function fill(array $Values) { foreach ($Values as $name => $value){ if (!property_exists($this, $name)){ throw new \Exception('Undefined property "' . $name . '"!'); } $this->{$name} = $value; } }
php
{ "resource": "" }
q263824
URI.getUri
test
public function getUri($start = self::SCHEME, $end = self::FRAGMENT) { $result = ''; switch ($start) { default: case static::SCHEME: $scheme = $this->getScheme(); if ($scheme) { $result .= $scheme . static::DELIMITER_SCHEME; } if ($end === static::SCHEME) { break; } // no break case static::AUTHORITY: case static::USERNAME: $username = $this->getUserInfo(); if ($username && $this->getHost()) { $result .= static::DELIMITER_AUTHORITY . $username . static::DELIMITER_USER; } if ($end === static::USERNAME) { break; } // no break case static::HOST: $host = $this->getHost(); if ($host && ($result === '' || !$this->getUserInfo())) { $result .= static::DELIMITER_AUTHORITY; } $result .= $host; if ($end === static::HOST) { break; } // no break case static::PORT: $port = $this->getPort(); if ($port !== null && $this->getHost()) { $result .= static::DELIMITER_PORT . $port; } if ($end === static::PORT || $end === static::AUTHORITY) { break; } // no break case static::PATH: case static::DIRECTORY: $directory = $this->getDirectory(); if ($result !== '' && $directory !== '' && substr($directory, 0, 1) !== static::DELIMITER_PATH) { $result .= static::DELIMITER_PATH; } $result .= $directory; if ($end === static::DIRECTORY) { break; } // no break case static::FILE: $file = $this->getFile(); if ($result !== '' && substr($result, -1) !== static::DELIMITER_PATH && $file !== '') { $result .= static::DELIMITER_PATH; } $result .= $this->getFile(); if ($end === static::FILE || $end === static::PATH) { break; } // no break case static::QUERY: $query = $this->getQuery(); if ($query) { $result .= static::DELIMITER_QUERY . $query; } if ($end === static::QUERY) { break; } // no break case static::FRAGMENT: $fragment = $this->getFragment(); if ($fragment) { $result .= static::DELIMITER_FRAGMENT . $fragment; } // no break } return $result; }
php
{ "resource": "" }
q263825
URI.setUserInfo
test
private function setUserInfo($username, $password = null) { $this->username = $username; $this->password = $password; return $this; }
php
{ "resource": "" }
q263826
URI.setPort
test
private function setPort($port = null) { if ($port !== null && (1 > $port || 0xffff < $port)) { throw new \InvalidArgumentException('Invalid port'); } $this->port = $port; return $this; }
php
{ "resource": "" }
q263827
URI.setPath
test
private function setPath($path) { $directory = dirname($path); $file = basename($path); // If dirname is '.'. Then remove it. if ($directory === '.') { $directory = ''; } // If the path ends with '/'. Then there is no file. if (substr($path, -1) === static::DELIMITER_PATH) { $directory = $path; $file = ''; } // If the dirname and basename are both set. Then add the missing '/'. if (substr($directory, -1) !== static::DELIMITER_PATH && $directory !== '' && $file !== '') { $directory .= static::DELIMITER_PATH; } $this->setDirectory($directory); $this->setFile($file); return $this; }
php
{ "resource": "" }
q263828
URI.getSegment
test
public function getSegment($index) { $result = $this->getSegments(); return isset($result[$index]) ? $result[$index] : null; }
php
{ "resource": "" }
q263829
URI.getQueryValue
test
public function getQueryValue($key) { return isset($this->query[$key]) ? $this->query[$key] : null; }
php
{ "resource": "" }
q263830
Builder._build
test
protected function _build($tokens, $space) { $output = ''; $lastToken = false; $level = 0; foreach ($tokens as $token) { switch ($token['token']) { case 'code': $output .= $space . $token['code'] . $this->newline; break; case '}': $level --; $space = substr($space, strlen($this->tab)); $output .= $space . '}' . $this->newline; break; case '{': if ($lastToken === '}') { // Double new line between 2 items in same scope $output .= $this->newline; } if (isset($token['selectors'])) { $output .= $space . implode($this->selectorsSeparator, $token['selectors']); } elseif (isset($token['atRule'])) { $output .= $space . '@' . $token['atRule']; if (!empty($token['atValues'])) { $values = implode($this->selectorsSeparator, $token['atValues']); $output .= $values === '' ? '' : ' ' . $values; } } else { // Error - use code as backup $output .= $space . $token['code']; } $output .= ($this->newLineAfterSelector ? $this->newline . $space : ($this->minify ? '' : ' ') ) . '{' . $this->newline; if (isset($token['children'])) { $output .= $this->_build($token['children'], $space . $this->tab); $output .= $space . '}' . $this->newline; } else { $level ++; $space .= $this->tab; } break; case 'rule': $output .= $space . $token['key'] . $this->ruleSeparator . $token['value']; foreach ($this->ruleModifiers as $mod) { if (!empty($token[$mod])) { $output .= ' !' . $mod; } } $output .= ';' . $this->newline; break; } $lastToken = $token['token']; } return $output; }
php
{ "resource": "" }
q263831
TAggregatable.aggregate
test
protected static function aggregate(string $name) : array { return array_merge(is_callable($target = [get_parent_class(static::class), 'aggregate']) ? call_user_func($target, $name) : [], Arr::cast(Arr::get(get_class_vars(static::class), $name))); }
php
{ "resource": "" }
q263832
StrategyParser.get
test
public function get($strategy) { if (!isset($this->strategies[$strategy])) { throw new StrategyNotFoundException(sprintf('Strategy "%s" not found in the configurations set', $strategy)); } return $this->buildConfiguration($strategy, $this->strategies[$strategy]); }
php
{ "resource": "" }
q263833
StrategyParser.buildConfiguration
test
protected function buildConfiguration($strategy, $strategyConfig) { $config = array_merge($this->callParams, array( 'path' => rtrim($this->router->generate('dcs_opauth_connect'), '/').'/', 'callback_url' => $this->router->generate('dcs_opauth_response', array( 'strategy' => $strategy, )), 'security_salt' => uniqid(null, true), )); if (isset($strategyConfig['options']) && is_array($strategyConfig['options'])) { $strategyConfig = array_merge($strategyConfig, $strategyConfig['options']); unset($strategyConfig['options']); } $config['Strategy'][$strategy] = $strategyConfig; return $config; }
php
{ "resource": "" }
q263834
Get.composeResult
test
private function composeResult(EAccount $acc) { /** define local working data */ $accId = $acc->getId(); $custId = $acc->getCustomerId(); $balance = $acc->getBalance(); $typeId = $acc->getAssetTypeId(); /** compose result */ $result = new AResponse(); $result->setId($accId); $result->setCustomerId($custId); $result->setBalance($balance); $result->setAssetTypeId($typeId); return $result; }
php
{ "resource": "" }
q263835
Get.exec
test
public function exec($request) { assert($request instanceof ARequest); /** define local working data */ $typeCode = $request->getAssetTypeCode(); $typeId = $request->getAssetTypeId(); $custId = $request->getCustomerId(); $isSys = $request->getIsSystem(); /** perform processing */ if (is_null($typeId)) { /* get type ID by code if missed */ $typeId = $this->daoTypeAsset->getIdByCode($typeCode); } /* return cached data for system customer if exists */ if ( $isSys && isset($this->cachedSysAccs[$typeId]) ) { $result = $this->cachedSysAccs[$typeId]; } else { /* ... or get data from DB */ if ($isSys) { /* get system customer ID */ $custId = $this->daoAccount->getSystemCustomerId(); } $account = $this->getAccount($custId, $typeId); $result = $this->composeResult($account); /* cache data for system customer */ if ($isSys) { $this->cachedSysAccs[$typeId] = $result; } } /** compose result */ return $result; }
php
{ "resource": "" }
q263836
Create.exec
test
public function exec($request) { assert($request instanceof ARequest); $result = new AResponse(); $operationTypeId = $request->getOperationTypeId(); $operationTypeCode = $request->getOperationTypeCode(); $datePerformed = $request->getDatePerformed(); $note = $request->getOperationNote(); $transactions = $request->getTransactions(); $asRef = $request->getAsTransRef(); $customerId = $request->getCustomerId(); $adminUserId = $request->getAdminUserId(); if (empty($datePerformed)) { $datePerformed = $this->hlpDate->getUtcNowForDb(); } /* add operation itself */ if (!$operationTypeId) { $operationTypeId = $this->daoTypeOper->getIdByCode($operationTypeCode); } $bindToAdd = [ EOperation::A_TYPE_ID => $operationTypeId, EOperation::A_DATE_PREFORMED => $datePerformed ]; if (!is_null($note)) { $bindToAdd[EOperation::A_NOTE] = $note; } $validTrans = $this->validateTransactions($transactions); if ($validTrans == AResponse::ERR_NO_ERROR) { /** * Better this nested transaction will break outer transaction than we will clean up data manually. */ $def = $this->manTrans->begin(); try { $operId = $this->daoOper->create($bindToAdd); if ($operId) { $transIds = $this->ownAdd->exec($operId, $transactions, $datePerformed, $asRef); $result->setOperationId($operId); $result->setTransactionsIds($transIds); /* extract IDs from sessions if both are empty */ list($customerId, $adminUserId) = $this->prepareLogIds($customerId, $adminUserId); /* log customer link */ if ($customerId) { $log = new \Praxigento\Accounting\Repo\Data\Log\Change\Customer(); $log->setCustomerRef($customerId); $log->setOperationRef($operId); $this->daoELogChangeCust->create($log); } /* log admin link */ if ($adminUserId) { $log = new \Praxigento\Accounting\Repo\Data\Log\Change\Admin(); $log->setUserRef($adminUserId); $log->setOperationRef($operId); $this->daoELogChangeAdmin->create($log); } $this->manTrans->commit($def); $result->markSucceed(); } } finally { /* rollback transaction if not committed (on exception, for example) */ $this->manTrans->end($def); } } else { $dump = var_export($request, true); $this->logger->error("Validation error: $validTrans. Details: $dump."); $result->setErrorCode($validTrans); } return $result; }
php
{ "resource": "" }
q263837
Create.prepareLogIds
test
private function prepareLogIds($custId, $adminId) { if (!$custId && !$adminId) { /* both are empty */ $customer = $this->sessCust->getCustomer(); if ($customer) { $custId = $customer->getId(); } $user = $this->sessAdmin->getUser(); if ($user instanceof \Magento\User\Model\User) { $adminId = $user->getId(); } } return [$custId, $adminId]; }
php
{ "resource": "" }
q263838
Create.validateTransactions
test
private function validateTransactions($trans) { $result = AResponse::ERR_NO_ERROR; foreach ($trans as $one) { if (is_array($one)) { $accDbt = $one[ETrans::A_DEBIT_ACC_ID]; $accCrd = $one[ETrans::A_CREDIT_ACC_ID]; } else { $accDbt = $one->getDebitAccId(); $accCrd = $one->getCreditAccId(); } if ($accDbt == $accCrd) { $result = AResponse::ERR_ONE_ACCOUNT_FOR_DEBIT_AND_CREDIT; break; } } return $result; }
php
{ "resource": "" }
q263839
Message.setHeaders
test
private function setHeaders(array $headers) { $this->headerNames = []; $this->headers = []; foreach ($headers as $name => $value) { $this->setHeader($name, $value); } return $this; }
php
{ "resource": "" }
q263840
Message.setHeader
test
protected function setHeader($name, $value) { if (!is_array($value)) { $value = [$value]; } $this->headerNames[strtolower($name)] = $name; array_merge($this->headers[$name] = $value); return $this; }
php
{ "resource": "" }
q263841
Message.addHeader
test
private function addHeader($name, $value) { if (!$this->hasHeader($name)) { return $this->setHeader($name, $value); } if (!is_array($value)) { $value = [$value]; } foreach ($value as $element) { $this->headers[$this->headerNames[strtolower($name)]][] = $element; } return $this; }
php
{ "resource": "" }
q263842
Message.removeHeader
test
private function removeHeader($name) { if ($this->hasHeader($name)) { $normalized = strtolower($name); unset($this->headers[$this->headerNames[$normalized]], $this->headerNames[$normalized]); } return $this; }
php
{ "resource": "" }
q263843
ClassLoader.addPrefix
test
function addPrefix(string $prefix, $paths, int $type = self::PSR4): void { if ($type !== static::PSR4 && $type !== static::PSR0) { throw new \UnexpectedValueException('Invalid prefix type'); } if ($prefix === '') { foreach ((array) $paths as $path) { $this->fallbacks[$type][] = $path; } return; } $firstNsSep = strpos($prefix, '\\'); $prefixLength = strlen($prefix); // determine index if ($firstNsSep === false) { // no namespace if ($type === static::PSR4) { throw new \InvalidArgumentException(sprintf( 'PSR-4 prefixes must contain a top level namespace (got "%s")', $prefix )); } // use first character $index = $prefix[0]; } else { // has namespace if ($type === static::PSR4 && $prefix[$prefixLength - 1] !== '\\') { throw new \InvalidArgumentException(sprintf( 'PSR-4 prefixes must end with a namespace separator (got "%s")', $prefix )); } // use vendor namespace $index = substr($prefix, 0, $firstNsSep); } // register $this->prefixes[$index][] = [$type, $prefix, $prefixLength, (array) $paths]; }
php
{ "resource": "" }
q263844
ClassLoader.addPrefixes
test
function addPrefixes(array $prefixes, int $type = self::PSR4): void { foreach ($prefixes as $prefix => $paths) { $this->addPrefix($prefix, $paths, $type); } }
php
{ "resource": "" }
q263845
ClassLoader.findFile
test
function findFile(string $className): ?string { if ($className[0] === '\\') { $className = substr($className, 1); } // check class map if (isset($this->classMap[$className])) { return $this->classMap[$className]; } if ($this->usePrefixes) { // determine index $firstNsSep = strpos($className, '\\'); if ($firstNsSep === false) { $isPsr4Compatible = false; $index = $className[0]; $firstNsSep = null; } else { $isPsr4Compatible = true; $index = substr($className, 0, $firstNsSep); } // cache PSR-0 subpath $subpathPsr0 = null; // scan prefixes if ( isset($this->prefixes[$index]) || ($isPsr4Compatible && isset($this->prefixes[$index = $className[0]])) ) { foreach ($this->prefixes[$index] as $prefix) { // 0 => type, 1 => prefix, 2 => prefix_len, 3 => paths if ( ($isPsr4 = ($prefix[0] === static::PSR4)) && !$isPsr4Compatible || strncmp($prefix[1], $className, $prefix[2]) !== 0 ) { // no match or we are locating a PSR-0 class but the prefix is PSR-4 continue; } // compose subpath if ($isPsr4) { // PSR-4 subpath must be built for different prefix lengths $subpath = $this->buildPsr4Subpath($className, $prefix[2]); } else { // PSR-0 subpath contains the entire namespace so it needs to be built only once if ($subpathPsr0 === null) { $subpathPsr0 = $this->buildPsr0Subpath($className, $firstNsSep); } $subpath = $subpathPsr0; } // iterate over possible paths foreach ($prefix[3] as $path) { if (($filePath = $this->findFileWithKnownSuffix($path . $subpath)) !== null) { return $filePath; } } } } // scan fallbacks if (isset($this->fallbacks[static::PSR0])) { $subpath = $subpathPsr0 ?: $this->buildPsr0Subpath($className, $firstNsSep); foreach ($this->fallbacks[static::PSR0] as $fallback) { if (($filePath = $this->findFileWithKnownSuffix($fallback . $subpath)) !== null) { return $filePath; } } } if (isset($this->fallbacks[static::PSR4])) { $subpath = $this->buildPsr4Subpath($className, 0); foreach ($this->fallbacks[static::PSR4] as $fallback) { if (($filePath = $this->findFileWithKnownSuffix($fallback . $subpath)) !== null) { return $filePath; } } } // cache failed lookup $this->classMap[$className] = false; } return null; }
php
{ "resource": "" }
q263846
ClassLoader.findFileWithKnownSuffix
test
private function findFileWithKnownSuffix(string $pathWithoutSuffix): ?string { foreach ($this->fileSuffixes as $fileSuffix) { if (is_file($filePath = $pathWithoutSuffix . $fileSuffix)) { return $filePath; } } return null; }
php
{ "resource": "" }
q263847
ApiResponse.convertObjectToArray
test
protected function convertObjectToArray($object) { if (method_exists($object, 'toArray')) { return $object->toArray(); } return json_decode(json_encode($object, true), true); }
php
{ "resource": "" }
q263848
ApiResponse.cleanArray
test
protected function cleanArray($array, $keys = null) { $keys = $keys ?: array_keys($array); foreach ($keys as $key) { if (is_array($value = Arr::get($array, $key))) { Arr::set($array, $key, array_filter($value)); } } return $array; }
php
{ "resource": "" }
q263849
ApiResponse.setCode
test
public function setCode($code) { $this->code = (int) $code; return $this->mergeData([static::codeKey() => $this->code]); }
php
{ "resource": "" }
q263850
ServerRequest.initUri
test
private function initUri($uri) { if ($uri !== null) { return $uri; } $scheme = isset($this->getServerParams()['HTTPS']) ? 'https://' : 'http://'; $host = isset($this->getServerParams()['HTTP_HOST']) ? $scheme . $this->getServerParams()['HTTP_HOST'] : ''; $path = isset($this->getServerParams()['REQUEST_URI']) ? $this->getServerParams()['REQUEST_URI'] : ''; return new URI($host . $path); }
php
{ "resource": "" }
q263851
ServerRequest.initQueryParams
test
private function initQueryParams($serverParams) { $result = []; if (isset($serverParams['REQUEST_URI']) && ($query = parse_url($serverParams['REQUEST_URI'], \PHP_URL_QUERY))) { parse_str($query, $result); } return $result ?? []; }
php
{ "resource": "" }
q263852
ServerRequest.initUploadedFiles
test
private function initUploadedFiles(array $files) { $result = []; foreach ($files as $key => $value) { $result[$key] = $this->parseUploadedFiles($value); } return $result; }
php
{ "resource": "" }
q263853
ServerRequest.parseUploadedFiles
test
private function parseUploadedFiles($files) { // Empty $first = reset($files); // Single if (!is_array($first)) { return $this->parseSingleUploadedFiles($files); } // Multiple if (count(array_filter(array_keys($first), 'is_string')) === 0) { return $this->parseMultipleUploadedFiles($files); } // Namespace return $this->initUploadedFiles($files); }
php
{ "resource": "" }
q263854
ServerRequest.parseMultipleUploadedFiles
test
private function parseMultipleUploadedFiles(array $files) { $count = count($files['name']); $result = []; for ($i = 0; $i < $count; $i++) { $result[] = new UploadedFile($files['name'][$i], $files['type'][$i], $files['tmp_name'][$i], $files['error'][$i], $files['size'][$i]); } return $result; }
php
{ "resource": "" }
q263855
ServerRequest.hasContentType
test
private function hasContentType($contentType) { foreach ($this->getHeader('Content-Type') as $key => $value) { if (substr($value, 0, strlen($contentType)) == $contentType) { return true; } } return false; }
php
{ "resource": "" }
q263856
CreateFiles.run
test
public function run() { //Create controller files foreach ($this->getControllers() as $fileName => $filePath) { $this->makeDirectory($filePath); $this->filesystem->put($filePath, $this->compileStub($fileName)); } //Create blades foreach ($this->getBlades() as $fileName => $filePath) { $this->makeDirectory($filePath); $this->filesystem->put($filePath, $this->compileStub($fileName)); } //Create migration files foreach ($this->getMigrations() as $fileName => $filePath) { $this->filesystem->put($filePath, $this->compileStub($fileName)); } //Create activation mail, if the --queue flag is passed, then it implements the ShouldQueue interface. foreach ($this->getEmails() as $fileName => $filePath) { $this->makeDirectory($filePath); $stub = $this->filesystem->get(__DIR__ . '/../../stubs/' . $fileName . '.stub'); $this->filesystem->put($filePath, $this->replaceShouldQueue($stub)); } //Create language files foreach ($this->getLanguages() as $fileName => $filePath) { $this->filesystem->put($filePath, $this->compileStub($fileName)); } }
php
{ "resource": "" }
q263857
AbstractCommandController.dispatch
test
public function dispatch() { $arguments = $this->rawArguments; $this->scriptPath = array_shift($arguments); $this->command = array_shift($arguments); $this->arguments = $this->parseArguments($arguments); if (!$this->command) { $this->outputError('No command given'); $this->command = 'help'; } $commandName = $this->command . 'Command'; if (is_callable([$this, $commandName])) { $exitCode = call_user_func_array([$this, $commandName], $this->arguments); } else { $this->outputError('Command ' . $this->command . ' could not be found'); $exitCode = 1; } die($exitCode); }
php
{ "resource": "" }
q263858
AbstractCommandController.outputTable
test
public function outputTable($data, $delimiter = '|') { $output = ''; $firstRow = reset($data); $columnWidths = []; $columnCount = count($firstRow); $headerRow = array_keys($firstRow); if (!(is_integer(reset($headerRow)) && is_integer(end($headerRow)))) { // Add the header row to the data to detect the longest string array_unshift($data, $headerRow); } else { $headerRow = []; } // Collect the column widths for ($columnIndex = 0; $columnIndex < $columnCount; $columnIndex++) { $columnWidths[$columnIndex] = max( array_map( function ($row) use ($columnIndex) { $row = array_values($row); return (isset($row[$columnIndex]) ? strlen($row[$columnIndex]) : 0); }, $data ) ); } /* * Print the header if it is defined */ if ($headerRow) { // Remove the header row to the data after detecting the longest string array_shift($data); // Add the header $output .= $delimiter . ' '; foreach ($headerRow as $columnIndex => $cell) { $output .= '' . str_pad($cell, $columnWidths[$columnIndex]) . ' ' . $delimiter . ' '; } $output .= PHP_EOL; // Add the line below the header $output .= $delimiter . ' '; foreach ($headerRow as $columnIndex => $cell) { $output .= '' . str_repeat('-', $columnWidths[$columnIndex]) . ' ' . $delimiter . ' '; } $output .= PHP_EOL; } /* * Print the table */ foreach ($data as $row) { $row = array_values($row); $output .= $delimiter . ' '; foreach ($row as $columnIndex => $cell) { if (is_bool($cell)) { $cell = $cell ? 'TRUE' : 'FALSE'; } $output .= '' . str_pad($cell, $columnWidths[$columnIndex]) . ' ' . $delimiter . ' '; } $output .= PHP_EOL; } $this->output($output); }
php
{ "resource": "" }
q263859
AbstractCommandController.outputError
test
public function outputError($error) { $message = self::ESCAPE . self::RED; if (is_scalar($error)) { $message .= $error; } else { if (is_object($error) && $error instanceof \Exception) { $message .= '#' . $error->getCode() . ': ' . $error->getMessage(); } } $message .= PHP_EOL; $message .= self::ESCAPE . self::NORMAL; fwrite(STDERR, $message); }
php
{ "resource": "" }
q263860
AbstractCommandController.helpCommand
test
public function helpCommand() { $availableCommands = $this->getAvailableCommands(); $longestCommandNameLength = max( array_map( function ($item) { return strlen($item); }, array_keys($availableCommands) ) ); $longestCommandNameLength += 4; foreach ($availableCommands as $command => $help) { $line = '' . self::ESCAPE . self::GREEN . str_pad($command, $longestCommandNameLength) . self::ESCAPE . self::NORMAL . $help; $this->outputLine($line); } }
php
{ "resource": "" }
q263861
AbstractCommandController.getAvailableCommands
test
public function getAvailableCommands() { $commands = []; $classReflection = new \ReflectionClass(get_class($this)); $methods = $classReflection->getMethods(\ReflectionMethod::IS_PUBLIC); /** @var \ReflectionMethod $method */ foreach ($methods as $method) { $methodDescription = []; $methodName = $method->name; $docComment = $method->getDocComment(); $docCommentLines = explode(PHP_EOL, $docComment); if (substr($methodName, -7) !== 'Command') { continue; } foreach ($docCommentLines as $currentLine) { $currentLine = trim($currentLine); if (substr($currentLine, 0, 2) === '/*') { continue; } if (substr($currentLine, 0, 1) === '*') { $currentLine = substr($currentLine, 1); } $currentLine = trim($currentLine); if (!$currentLine) { continue; } if ($currentLine[0] === '@') { continue; } if ($currentLine === '/') { continue; } $methodDescription[] = trim($currentLine); } $commands[substr($methodName, 0, -7)] = implode(' ', $methodDescription); } return $commands; }
php
{ "resource": "" }
q263862
FilesInteractions.makeDirectory
test
protected function makeDirectory($path) { if (!$this->filesystem->isDirectory(dirname($path))) { $this->filesystem->makeDirectory(dirname($path), 0777, true, true); } }
php
{ "resource": "" }
q263863
FilesInteractions.AppendTo
test
protected function AppendTo($file, $stub) { return $this->filesystem->append(base_path() . '/routes/' . $file . '.php', $this->compileStub($stub)); }
php
{ "resource": "" }
q263864
FilesInteractions.replaceAndSave
test
public function replaceAndSave($oldFile, $search, $replace, $newFile = null) { if (!isset($newFile) || $newFile == null) { $newFile = $oldFile; } $file = $this->filesystem->get($oldFile); $replacing = str_replace($search, $replace, $file); $this->filesystem->put($newFile, $replacing); }
php
{ "resource": "" }
q263865
Dispatcher.dispatch
test
public function dispatch($uri, $method = 'GET', $arguments = []) { $this->originalUri = $uri; $this->uri = $this->prepareUri($uri); $methods = [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'OPTIONS', 'CONNECT', 'PATCH', ]; $method = strtoupper($method); $this->method = in_array($method, $methods) ? $method : 'GET'; try { // Get the response $response = $this->getResponse(); if (!$this->raw) { $response = $this->createTemplateResponse($response); } // Output the response echo $response; return $response; } catch (\Exception $exception) { $fileHandle = fopen('php://stderr', 'w'); fwrite($fileHandle, (string)$exception); if (ConfigurationManager::getConfiguration()->isDevelopmentMode()) { echo new Response('An error occurred: ' . $exception, 500); } else { echo new Response('An error occurred', 500); } } return ''; }
php
{ "resource": "" }
q263866
Dispatcher.createTemplateResponse
test
public function createTemplateResponse($response) { $page = $this->getPage(); $view = new View(); $view->setContext($this); $view->setTemplatePath($this->getTemplatePath()); $configuration = ConfigurationManager::getConfiguration(); $view->assignMultiple( [ 'page' => $page, 'meta' => $page ? $page->getMeta() : [], 'content' => $response->getBody(), 'response' => $response, 'resourcePath' => $configuration->getResourceDirectoryUri(), 'configuration' => $configuration, ] ); return new Response( $view->render(), $response->getStatusCode(), $response->getStatusText() ); }
php
{ "resource": "" }
q263867
Dispatcher.getPage
test
public function getPage() { if (!$this->page) { $this->page = $this->getPageForUri($this->uri); } return $this->page; }
php
{ "resource": "" }
q263868
Dispatcher.getResponse
test
public function getResponse() { $statusCode = 200; $page = $this->getPage(); if (!$page) { $statusCode = 404; $page = $this->getNotFoundPage(); } return new Response( $page ? $page->getContent() : 'Not found', $statusCode ); }
php
{ "resource": "" }
q263869
Dispatcher.buildResponseForUri
test
public function buildResponseForUri($uri) { $page = $this->getPageForUri($uri); if (!$page) { return null; } return new Response($page->getContent()); }
php
{ "resource": "" }
q263870
Dispatcher.getPageForUri
test
public function getPageForUri($uri) { $pageIdentifier = trim(urldecode($uri), '/'); $pageRepository = new PageRepository(); return $pageRepository->findByIdentifier($pageIdentifier); }
php
{ "resource": "" }
q263871
Dispatcher.getAliasForUri
test
public function getAliasForUri($uri) { $routingConfiguration = ConfigurationManager::getConfiguration()->get('routing'); $aliasConfiguration = isset($routingConfiguration['alias']) ? $routingConfiguration['alias'] : []; return isset($aliasConfiguration[$uri]) ? $aliasConfiguration[$uri] : $uri; }
php
{ "resource": "" }
q263872
I18nMessageController.actionView
test
public function actionView($id) { if(Yii::$app->request->isAjax) return $this->renderAjax('view', [ 'model' => $this->findModel($id), ]); else return $this->render('view', [ 'model' => $this->findModel($id), ]); }
php
{ "resource": "" }
q263873
I18nMessageController.actionCreate
test
public function actionCreate() { $model = new I18nMessage(); if ($model->load(Yii::$app->request->post()) && $model->save()) { if(Yii::$app->request->isAjax) return $this->redirect(['index']); else return $this->redirect(['view', 'id' => $model->message_id]); } else { if(Yii::$app->request->isAjax) return $this->renderAjax('create', [ 'model' => $model, ]); else return $this->render('create', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q263874
AnchorTrait.addHeadlineIds
test
public function addHeadlineIds($content) { $regex = '/\<h([0-6]{1})\>(.+)\<\/h[0-6]{1}\>/'; return preg_replace_callback( $regex, function ($matches) { $headlineLevel = $matches[1]; $headlineText = $matches[2]; return sprintf( '<h%d id="%s">%s</h%d>', (int)$headlineLevel, $this->buildElementId($headlineText), $headlineText, (int)$headlineLevel ); }, (string)$content ); }
php
{ "resource": "" }
q263875
Bootstrap.run
test
public function run() { Dispatcher::getSharedDispatcher()->dispatch($this->getUri(), $this->getMethod(), $this->getArguments()); }
php
{ "resource": "" }
q263876
Bootstrap.runCli
test
public function runCli($arguments) { $commandController = new \Cundd\Noshi\Command\NoshiCommandController($arguments); $commandController->dispatch(); }
php
{ "resource": "" }
q263877
AuthEmailServiceProvider.register
test
public function register() { /* * Bind interfaces to concrete implementations */ $this->app->bind( ActivationInterface::class, Activation::class ); $this->app->bind( Email::class, EmailAdapter::class ); /** * Register singleton, ShouldQueue class * should be resolved out of the * container only one time. */ $this->app->singleton('Ntavelis\AuthEmail\Commands\actions\ShouldQueue'); }
php
{ "resource": "" }
q263878
MarkdownFactory.getMarkdownRenderer
test
static public function getMarkdownRenderer() { if (!self::$markdownRendererInstance) { if (class_exists('\\Michelf\\Markdown')) { self::$markdownRendererInstance = new MichelfRenderer(); } else { self::$markdownRendererInstance = new ParsedownRenderer(); } } return self::$markdownRendererInstance; }
php
{ "resource": "" }
q263879
Files.getBlades
test
protected function getBlades() { $path = base_path() . '/resources/views/'; $loginStub = $this->laravelVersion >= 5.6 ? 'login.blade.b4' : 'login.blade'; $files = [ $loginStub => $path . 'auth/login.blade.php', 'auth.email' => $path . 'emails/auth.blade.php', ]; return $files; }
php
{ "resource": "" }
q263880
Files.getMigrations
test
protected function getMigrations() { $formatted_date = date('Y_m_d_His'); $path = base_path() . '/database/migrations/'; $files = [ 'MigrationActivations' => $path . $formatted_date . '_create_user_activations_table.php', 'MigrationUsers' => $path . $formatted_date . '_add_boolean_column_to_users_table.php' ]; return $files; }
php
{ "resource": "" }
q263881
PageRepository.findByIdentifier
test
public function findByIdentifier($identifier) { if (isset($this->allPages[$identifier])) { return $this->allPages[$identifier]; } $rawPageData = null; $configuration = ConfigurationManager::getConfiguration(); $dataPath = $configuration->get('basePath') . $configuration->get('dataPath'); $pageName = $this->getPageNameForPageIdentifier($identifier); $pageDataPath = $dataPath . $pageName . '.' . $configuration->get('dataSuffix'); $directoryDataPath = $dataPath . $pageName; $metaDataPath = $dataPath . $pageName . '.json'; $lastSlashPosition = strrpos($pageName, '/'); $hiddenPageDataPath = $dataPath . substr($pageName, 0, $lastSlashPosition) . '_' . substr($pageName, $lastSlashPosition) . '.' . $configuration->get('dataSuffix'); $whiteSpacePageDataPath = $dataPath . str_replace(Page::URI_WHITESPACE_REPLACE, ' ', $pageName) . '.' . $configuration->get('dataSuffix'); // Check if the node exists if (file_exists($pageDataPath)) { $rawPageData = file_get_contents($pageDataPath); } else { if (file_exists($whiteSpacePageDataPath)) { $pageDataPath = $whiteSpacePageDataPath; $rawPageData = file_get_contents($pageDataPath); } else { if (file_exists($hiddenPageDataPath)) { $pageDataPath = $hiddenPageDataPath; $rawPageData = file_get_contents($pageDataPath); } else { if (!(file_exists($directoryDataPath) || file_exists($metaDataPath))) { return null; } } } } $page = new Page($identifier, $rawPageData, $this->buildMetaDataForPageIdentifier($identifier, $pageDataPath)); $this->allPages[$identifier] = $page; return $page; }
php
{ "resource": "" }
q263882
PageRepository.getPageNameForPageIdentifier
test
public function getPageNameForPageIdentifier($identifier) { $pageName = urldecode($identifier); if (!$pageName || $pageName[0] === '.' || strpos($pageName, '/.') !== false) { throw new InvalidPageIdentifierException('Invalid page identifier'); } if ($pageName[0] === '/') { $pageName = substr($pageName, 1); } if (substr($pageName, -1) === '/') { $pageName = substr($pageName, 0, -1); } return $pageName; }
php
{ "resource": "" }
q263883
PageRepository.buildMetaDataForPageIdentifier
test
public function buildMetaDataForPageIdentifier($identifier, $pageDataPath = null) { $configuration = ConfigurationManager::getConfiguration(); $dataPath = $configuration->get('basePath') . $configuration->get('dataPath'); $pageName = $this->getPageNameForPageIdentifier($identifier); $metaDataPath = $dataPath . $pageName . '.json'; // Read the global configuration $metaData = ObjectUtility::valueForKeyPathOfObject("pages.$identifier.meta", $configuration, []); // Check if the node exists if (file_exists($metaDataPath)) { $rawMetaData = file_get_contents($metaDataPath); $metaData = array_merge($metaData, (array)json_decode($rawMetaData, true)); } if ($pageDataPath && file_exists($pageDataPath)) { $metaData['date'] = date('c', filemtime($pageDataPath)); } return $metaData; }
php
{ "resource": "" }
q263884
PageRepository.getPageTree
test
public function getPageTree() { if (!$this->pageTree) { $configuration = ConfigurationManager::getConfiguration(); $dataPath = $configuration->get('basePath') . $configuration->get('dataPath'); $this->pageTree = $this->getPagesForPath($dataPath); } return $this->pageTree; }
php
{ "resource": "" }
q263885
PageRepository.getPagesForPath
test
public function getPagesForPath($path, $uriBase = '') { $pages = []; $pagesSortingMap = []; $pagesIdentifierMap = []; if (!file_exists($path)) { throw new \InvalidArgumentException("Page path '$path' does not exist"); } if (!is_readable($path)) { throw new \InvalidArgumentException("Page path '$path' is not readable"); } if ($handle = opendir($path)) { $dataSuffix = '.' . ConfigurationManager::getConfiguration()->get('dataSuffix'); $dataSuffixLength = strlen($dataSuffix); while (false !== ($file = readdir($handle))) { // Skip the current file if the first character is a dot if ($file[0] === '.') { continue; } // Skip hidden pages if ($file[0] === '_') { continue; } $isFolder = strpos($file, '.') === false; $isPage = substr($file, -$dataSuffixLength) === $dataSuffix; $isConfig = substr($file, -5) === '.json'; if (!($isFolder || $isPage || $isConfig)) { continue; } $relativePageIdentifier = str_replace( ' ', Page::URI_WHITESPACE_REPLACE, substr($file, 0, strrpos($file, '.')) ); $pageIdentifier = ($uriBase ? $uriBase . '/' : '') . ($relativePageIdentifier ? $relativePageIdentifier : $file); /** @var Page $page */ $page = $this->findByIdentifier($pageIdentifier); $page->setIsDirectory($isFolder); $sorting = $page->getSorting(); $sortingDescriptor = sprintf('%05d-%s', $sorting, $pageIdentifier); /* * Build the page data merged with previous definitions * Page definition is more important than the Directory definition */ $pageData = array_merge( (isset($pagesIdentifierMap[$pageIdentifier]) ? $pagesIdentifierMap[$pageIdentifier] : []), [ 'id' => $pageIdentifier, 'page' => $page, 'sorting' => $sorting, 'sorting_descriptor' => $sortingDescriptor, ] ); /* * If the current page is a folder get the children */ if ($isFolder) { $pageData['children'] = $this->getPagesForPath( $path . $file . DIRECTORY_SEPARATOR, $pageIdentifier ); } $pagesSortingMap[$sortingDescriptor] = $pageData; $pagesIdentifierMap[$pageIdentifier] = $pageData; } closedir($handle); } // Add the page to the list pages ksort($pagesSortingMap, SORT_NUMERIC); $tempPages = []; foreach ($pagesSortingMap as $pageWithSorting) { $tempPages[$pageWithSorting['id']] = $pageWithSorting['page']; } $this->allPages = array_merge($this->allPages, $tempPages); ksort($pages, SORT_NUMERIC); return $pagesSortingMap; }
php
{ "resource": "" }
q263886
AuthEmail.Success
test
private function Success() { $migrated = ''; if ($this->option('migrate')) { $migrated = ' and migrated database'; } $this->info('Email authentication generated successfully' . $migrated . '.'); $this->composer->dumpAutoloads(); }
php
{ "resource": "" }
q263887
I18nMessage.loadMessagesFromDb
test
public static function loadMessagesFromDb($category, $language) { $mainQuery = new Query(); $mainQuery->select(['t1.message', 't2.translation']) ->from([I18nMessage::tableName().' t1', I18nTranslation::tableName().' t2']) ->where('t1.message_id = t2.message_id AND t1.category = :category AND t2.language = :language') ->params([':category' => $category, ':language' => $language]); $messages = $mainQuery->createCommand()->queryAll(); return ArrayHelper::map($messages, 'message', 'translation'); }
php
{ "resource": "" }
q263888
EmailService.sendActivationMail
test
public function sendActivationMail($user) { if ($user->activated || !$this->shouldSend($user)) { return; } $token = $this->activationRepo->createActivation($user); $link = route('user.activate', $token); $this->mailer->sendTo($user, $link); }
php
{ "resource": "" }
q263889
Fuzzy.search
test
public function search(array $rows, $query, $threshold = 3) { $matched = []; foreach($rows as $row) { $distance = $this->calculateDistance($query, $row); if ($threshold >= $distance) { $matched[] = [$distance, $row]; } } return $this->transformResult($this->sortMatchedStrings($matched)); }
php
{ "resource": "" }
q263890
Template.render
test
public function render() { $template = $this->getTemplate(); // Find the expressions $matches = []; if (!preg_match_all('!\{([\w\.\\\ \/]*)\}!', $template, $matches)) { return $template; } $expressions = $matches[1]; $expressions = array_unique($expressions); foreach ($expressions as $expression) { $renderedExpression = $this->renderExpression($expression); if (is_object($renderedExpression) && !method_exists($renderedExpression, '__toString')) { throw new InvalidExpressionException( 'Could not convert object of class ' . get_class( $renderedExpression ) . ' for expression ' . $expression . ' to string', 1401543101 ); } $template = str_replace('{' . $expression . '}', $renderedExpression, $template); } return $template; }
php
{ "resource": "" }
q263891
Template.renderExpression
test
public function renderExpression($expression) { if (strpos($expression, '\\') !== false) { $expressionParts = explode(' ', $expression); $viewClass = '\\' . array_shift($expressionParts); /** @var UiInterface $newView */ if (!class_exists($viewClass)) { return '<!-- view class ' . $viewClass . ' not found -->'; } $newView = new $viewClass(); if ($newView instanceof UiInterface) { $newView->setContext($this); if ($expressionParts) { return call_user_func_array([$newView, 'render'], $expressionParts); } return $newView->render(); } try { return (string)$newView; } catch (\Exception $exception) { } } else { if (substr($expression, 0, 2) === '//') { // Handle expressions like "{//please.output.me}" } } return $this->resolveExpressionKeyPath($expression); }
php
{ "resource": "" }
q263892
Template.resolveExpressionKeyPath
test
public function resolveExpressionKeyPath($keyPath) { if (isset($this->data[$keyPath])) { return $this->data[$keyPath]; } return ObjectUtility::valueForKeyPathOfObject($keyPath, $this->data); }
php
{ "resource": "" }
q263893
BundleClassFinder.findClasses
test
public function findClasses($subDir = null, $suffix = null, $parent = null, $reflection = false) { $classes = []; foreach ($this->bundles as $bundle) { $this->setRootDirectory($bundle->getPath()); $this->setRootNamespace($bundle->getNamespace()); $classes = array_merge($classes, parent::findClasses($subDir, $suffix, $parent, $reflection)); } return $classes; }
php
{ "resource": "" }
q263894
Configuration.prepareConfigurationArray
test
private function prepareConfigurationArray(array $configuration) { $pathConfiguration = [ 'dataPath', 'templatePath', 'resourcePath', ]; foreach ($pathConfiguration as $key) { if (isset($configuration[$key])) { $configuration[$key] = rtrim($configuration[$key], '/') . '/'; } } return $configuration; }
php
{ "resource": "" }
q263895
Configuration.getHost
test
public function getHost() { $host = ''; if (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] !== '0.0.0.0') { $host = $_SERVER['SERVER_NAME']; if (!$this->_validateHost($host)) { $host = ''; } // Add the port if ($host && isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']) { $port = $_SERVER['SERVER_PORT']; if (ctype_digit($port)) { $host .= ':' . $port; } } } if (!$host && isset($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; if (!$this->_validateHost($host)) { $host = ''; } } if (!$host) { throw new SecurityException('Host could not be detected', 1394796366); } return $host; }
php
{ "resource": "" }
q263896
Configuration.get
test
public function get($key) { $accessorMethod = 'get' . ucfirst($key); if (method_exists($this, $accessorMethod)) { return $this->$accessorMethod(); } return $this->_get($key); }
php
{ "resource": "" }
q263897
I18nTranslationController.actionView
test
public function actionView($message_id, $language) { if(Yii::$app->request->isAjax) return $this->renderAjax('view', [ 'model' => $this->findModel($message_id, $language), ]); else return $this->render('view', [ 'model' => $this->findModel($message_id, $language), ]); }
php
{ "resource": "" }
q263898
I18nTranslationController.actionUpdate
test
public function actionUpdate($message_id, $language) { $model = $this->findModel($message_id, $language); if ($model->load(Yii::$app->request->post()) && $model->save()) { if(Yii::$app->request->isAjax) return $this->redirect(['index']); else return $this->redirect(['view', 'message_id' => $model->message_id, 'language' => $model->language]); } else { if(Yii::$app->request->isAjax) return $this->renderAjax('update', [ 'model' => $model, ]); else return $this->render('update', [ 'model' => $model, ]); } }
php
{ "resource": "" }
q263899
I18nTranslationController.actionDelete
test
public function actionDelete($message_id, $language) { $this->findModel($message_id, $language)->delete(); return $this->redirect(['index']); }
php
{ "resource": "" }