_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 33
8k
| 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
|
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 '(':
|
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;
|
php
|
{
"resource": ""
}
|
q263803
|
Tokenizer._mergeWords
|
test
|
protected function _mergeWords($words) {
$value = '';
foreach ($words as $word) {
$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);
|
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);
|
php
|
{
"resource": ""
}
|
q263806
|
Tokenizer._parseTokens
|
test
|
protected function _parseTokens($item) {
$results = [];
while ($item !== null) {
switch ($item['token']) {
case '}':
return $results;
case '{':
|
php
|
{
"resource": ""
}
|
q263807
|
Helper.setCurrentAppKeyForRequest
|
test
|
public static function setCurrentAppKeyForRequest($key, Request $request = null)
{
|
php
|
{
"resource": ""
}
|
q263808
|
Helper.getCurrentAppKey
|
test
|
public static function getCurrentAppKey(Request $request = null)
{
|
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);
|
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);
|
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,
|
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'],
|
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)) {
|
php
|
{
"resource": ""
}
|
q263814
|
Token.generate
|
test
|
public function generate($key, $secret, $time)
{
if ($key && $secret && $time) {
return
|
php
|
{
"resource": ""
}
|
q263815
|
Token.generateForKey
|
test
|
public function generateForKey($key, $time)
{
if ($secret = $this->client->getAppSecretForKey($key)) {
|
php
|
{
"resource": ""
}
|
q263816
|
Token.verify
|
test
|
public function verify($token, $key, $time)
{
|
php
|
{
"resource": ""
}
|
q263817
|
Token.generateHttpHeaders
|
test
|
public function generateHttpHeaders($appKey, $time = null)
{
$headers = [];
foreach ($this->generateDataForKey($appKey, $time) as $key => $value) {
|
php
|
{
"resource": ""
}
|
q263818
|
Token.generateQueryData
|
test
|
public function generateQueryData($appKey, $time = null)
{
$query = [];
foreach ($this->generateDataForKey($appKey, $time) as $key => $value) {
|
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;
|
php
|
{
"resource": ""
}
|
q263820
|
Builder.fit
|
test
|
public function fit($gravity = null)
{
$this->manipulations['c'] = 'fit';
if (!is_null($gravity)) {
|
php
|
{
"resource": ""
}
|
q263821
|
Builder.getManipulations
|
test
|
public function getManipulations()
{
$manipulations = array_map(function ($key) {
return $key . '_' . $this->manipulations[$key];
},
|
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);
|
php
|
{
"resource": ""
}
|
q263823
|
TFillable.fill
|
test
|
public function fill(array $Values) {
foreach ($Values as $name => $value){
if (!property_exists($this,
|
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) {
|
php
|
{
"resource": ""
}
|
q263825
|
URI.setUserInfo
|
test
|
private function setUserInfo($username, $password = null)
{
$this->username = $username;
|
php
|
{
"resource": ""
}
|
q263826
|
URI.setPort
|
test
|
private function setPort($port = null)
{
if ($port !== null && (1 > $port || 0xffff
|
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 '/'.
|
php
|
{
"resource": ""
}
|
q263828
|
URI.getSegment
|
test
|
public function getSegment($index)
{
$result = $this->getSegments();
return
|
php
|
{
"resource": ""
}
|
q263829
|
URI.getQueryValue
|
test
|
public function getQueryValue($key)
{
return
|
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 :
|
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'])
|
php
|
{
"resource": ""
}
|
q263832
|
StrategyParser.get
|
test
|
public function get($strategy)
{
if (!isset($this->strategies[$strategy])) {
throw new StrategyNotFoundException(sprintf('Strategy "%s"
|
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'])) {
|
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();
|
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 */
|
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();
|
php
|
{
"resource": ""
}
|
q263837
|
Create.prepareLogIds
|
test
|
private function prepareLogIds($custId, $adminId)
{
if (!$custId && !$adminId) {
/* both are empty */
$customer = $this->sessCust->getCustomer();
if ($customer) {
|
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();
|
php
|
{
"resource": ""
}
|
q263839
|
Message.setHeaders
|
test
|
private function setHeaders(array $headers)
{
$this->headerNames = [];
$this->headers = [];
foreach ($headers as $name
|
php
|
{
"resource": ""
}
|
q263840
|
Message.setHeader
|
test
|
protected function setHeader($name, $value)
{
if (!is_array($value)) {
$value = [$value];
}
$this->headerNames[strtolower($name)] = $name;
|
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];
}
|
php
|
{
"resource": ""
}
|
q263842
|
Message.removeHeader
|
test
|
private function removeHeader($name)
{
if ($this->hasHeader($name)) {
$normalized = strtolower($name);
|
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
|
php
|
{
"resource": ""
}
|
q263844
|
ClassLoader.addPrefixes
|
test
|
function addPrefixes(array $prefixes, int $type = self::PSR4): void
{
foreach ($prefixes as $prefix => $paths) {
|
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);
|
php
|
{
"resource": ""
}
|
q263846
|
ClassLoader.findFileWithKnownSuffix
|
test
|
private function findFileWithKnownSuffix(string $pathWithoutSuffix): ?string
{
foreach ($this->fileSuffixes as $fileSuffix) {
if (is_file($filePath =
|
php
|
{
"resource": ""
}
|
q263847
|
ApiResponse.convertObjectToArray
|
test
|
protected function convertObjectToArray($object)
{
if (method_exists($object, 'toArray')) {
return $object->toArray();
|
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))) {
|
php
|
{
"resource": ""
}
|
q263849
|
ApiResponse.setCode
|
test
|
public function setCode($code)
{
$this->code = (int) $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'] : '';
|
php
|
{
"resource": ""
}
|
q263851
|
ServerRequest.initQueryParams
|
test
|
private function initQueryParams($serverParams)
{
$result = [];
if (isset($serverParams['REQUEST_URI']) && ($query = parse_url($serverParams['REQUEST_URI'],
|
php
|
{
"resource": ""
}
|
q263852
|
ServerRequest.initUploadedFiles
|
test
|
private function initUploadedFiles(array $files)
{
$result = [];
foreach ($files as $key => $value) {
|
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) {
|
php
|
{
"resource": ""
}
|
q263854
|
ServerRequest.parseMultipleUploadedFiles
|
test
|
private function parseMultipleUploadedFiles(array $files)
{
$count = count($files['name']);
$result = [];
for ($i = 0; $i < $count; $i++) {
$result[]
|
php
|
{
"resource": ""
}
|
q263855
|
ServerRequest.hasContentType
|
test
|
private function hasContentType($contentType)
{
foreach ($this->getHeader('Content-Type') as $key => $value) {
if
|
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()
|
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');
|
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 . ' ';
|
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
|
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 = ''
|
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 =
|
php
|
{
"resource": ""
}
|
q263862
|
FilesInteractions.makeDirectory
|
test
|
protected function makeDirectory($path)
{
if (!$this->filesystem->isDirectory(dirname($path))) {
|
php
|
{
"resource": ""
}
|
q263863
|
FilesInteractions.AppendTo
|
test
|
protected function AppendTo($file, $stub)
{
return $this->filesystem->append(base_path()
|
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);
|
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) {
|
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(),
|
php
|
{
"resource": ""
}
|
q263867
|
Dispatcher.getPage
|
test
|
public function getPage()
{
if (!$this->page) {
|
php
|
{
"resource": ""
}
|
q263868
|
Dispatcher.getResponse
|
test
|
public function getResponse()
{
$statusCode = 200;
$page = $this->getPage();
if (!$page) {
$statusCode = 404;
$page = $this->getNotFoundPage();
}
return
|
php
|
{
"resource": ""
}
|
q263869
|
Dispatcher.buildResponseForUri
|
test
|
public function buildResponseForUri($uri)
{
$page = $this->getPageForUri($uri);
if (!$page) {
|
php
|
{
"resource": ""
}
|
q263870
|
Dispatcher.getPageForUri
|
test
|
public function getPageForUri($uri)
{
$pageIdentifier = trim(urldecode($uri), '/');
$pageRepository = new PageRepository();
|
php
|
{
"resource": ""
}
|
q263871
|
Dispatcher.getAliasForUri
|
test
|
public function getAliasForUri($uri)
{
$routingConfiguration = ConfigurationManager::getConfiguration()->get('routing');
$aliasConfiguration
|
php
|
{
"resource": ""
}
|
q263872
|
I18nMessageController.actionView
|
test
|
public function actionView($id)
{
if(Yii::$app->request->isAjax)
return $this->renderAjax('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
|
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>',
|
php
|
{
"resource": ""
}
|
q263875
|
Bootstrap.run
|
test
|
public function run()
{
Dispatcher::getSharedDispatcher()->dispatch($this->getUri(),
|
php
|
{
"resource": ""
}
|
q263876
|
Bootstrap.runCli
|
test
|
public function runCli($arguments)
{
$commandController = new
|
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
|
php
|
{
"resource": ""
}
|
q263878
|
MarkdownFactory.getMarkdownRenderer
|
test
|
static public function getMarkdownRenderer()
{
if (!self::$markdownRendererInstance) {
if (class_exists('\\Michelf\\Markdown')) {
self::$markdownRendererInstance = new MichelfRenderer();
} else {
|
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 = [
|
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',
|
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 =
|
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] === '/') {
|
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';
|
php
|
{
"resource": ""
}
|
q263884
|
PageRepository.getPageTree
|
test
|
public function getPageTree()
{
if (!$this->pageTree) {
$configuration = ConfigurationManager::getConfiguration();
$dataPath = $configuration->get('basePath') . $configuration->get('dataPath');
|
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] : []),
|
php
|
{
"resource": ""
}
|
q263886
|
AuthEmail.Success
|
test
|
private function Success()
{
$migrated = '';
if ($this->option('migrate')) {
$migrated = ' and migrated database';
}
|
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')
|
php
|
{
"resource": ""
}
|
q263888
|
EmailService.sendActivationMail
|
test
|
public function sendActivationMail($user)
{
if ($user->activated || !$this->shouldSend($user)) {
return;
}
|
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)
{
|
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(
|
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();
|
php
|
{
"resource": ""
}
|
q263892
|
Template.resolveExpressionKeyPath
|
test
|
public function resolveExpressionKeyPath($keyPath)
{
if (isset($this->data[$keyPath])) {
|
php
|
{
"resource": ""
}
|
q263893
|
BundleClassFinder.findClasses
|
test
|
public function findClasses($subDir = null, $suffix = null, $parent = null, $reflection = false)
{
$classes = [];
foreach ($this->bundles as $bundle) {
|
php
|
{
"resource": ""
}
|
q263894
|
Configuration.prepareConfigurationArray
|
test
|
private function prepareConfigurationArray(array $configuration)
{
$pathConfiguration = [
'dataPath',
'templatePath',
'resourcePath',
];
foreach ($pathConfiguration as $key) {
if (isset($configuration[$key]))
|
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']) {
|
php
|
{
"resource": ""
}
|
q263896
|
Configuration.get
|
test
|
public function get($key)
{
$accessorMethod = 'get' . ucfirst($key);
if (method_exists($this,
|
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
|
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']);
|
php
|
{
"resource": ""
}
|
q263899
|
I18nTranslationController.actionDelete
|
test
|
public function actionDelete($message_id, $language)
{
$this->findModel($message_id,
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.