_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q259900 | AccessTokenBuilder.build | test | public function build(array $data)
{
$this->validateArrayKeys(
array('scope', 'access_token', 'token_type', 'app_id', 'expires_in'),
$data
);
if (empty($data['access_token'])) {
throw new BuilderException('access_token is mandatory and should not be empty');
}
$accessToken = new AccessToken(
$data['access_token'],
$data['token_type'],
$data['app_id'],
$data['expires_in'],
$data['scope']
);
$accessToken->setPaypalData($data);
return $accessToken;
} | php | {
"resource": ""
} |
q259901 | TransactionsBuilder.build | test | public function build(array $transactions)
{
$results = array();
foreach ($transactions as $transaction) {
$results[] = $this->buildTransaction($transaction);
}
return $results;
} | php | {
"resource": ""
} |
q259902 | TransactionsBuilder.buildArray | test | public function buildArray($transactions)
{
$this->assertTransactions($transactions);
$transactionsData = array();
foreach ($transactions as $transaction) {
if ($transaction instanceof TransactionInterface) {
$data = array(
'amount' => array(
'total' => $transaction->getAmount()->getTotal(),
'currency' => $transaction->getAmount()->getCurrency(),
),
'description' => $transaction->getDescription()
);
if ($itemList = $transaction->getItemList())
{
$data['item_list'] = $itemList;
}
$transactionsData[] = $data;
}
else {
$data = array(
'amount' => array(
'total' => $transaction['amount']['total'],
'currency' => $transaction['amount']['currency'],
),
'description' => $transaction['description']
);
if (isset($transaction['item_list']) && ! empty($transaction['item_list']))
{
$data['item_list'] = $transaction['item_list'];
}
$transactionsData[] = $data;
}
}
return $transactionsData;
} | php | {
"resource": ""
} |
q259903 | RequestSender.send | test | public function send($request, $acceptedStatusCode = 200, $errorLabel = 'Error sending Request:')
{
try {
$response = $this->getClient()->send($request);
}
catch (ClientErrorResponseException $e) {
$response = $e->getResponse();
$details = json_decode($response->getBody(), true);
$reason = implode(
', ',
array_map(
function ($vvalue, $key) {
return $key . ': ' . $vvalue;
},
$details,
array_keys($details)
)
);
throw new CallException(
$errorLabel.
" response status ".$response->getStatusCode()." ".$response->getReasonPhrase().", ".
" reason: ".$reason
);
}
if ($acceptedStatusCode != $response->getStatusCode()) {
throw new CallException(
$errorLabel.
"response status ".$response->getStatusCode()." ".$response->getReasonPhrase()
);
}
return $response;
} | php | {
"resource": ""
} |
q259904 | PaymentBuilder.build | test | public function build(array $data)
{
$this->validateArrayKeys(
array('id', 'create_time', 'state', 'intent', 'payer', 'transactions', 'links'),
$data
);
if (empty($data['id'])) {
throw new BuilderException('id is mandatory and should not be empty');
}
$links = array();
foreach ($data['links'] as $link) {
$links[] = $this->linkBuilder->build($link);
}
$payment = new Payment(
$data['id'],
$data['create_time'],
$data['state'],
$data['intent'],
$this->payerBuilder->build($data['payer']),
$this->transactionsBuilder->build($data['transactions']),
$links,
isset($data['update_time']) ? $data['update_time'] : null
);
$payment->setPaypalData($data);
return $payment;
} | php | {
"resource": ""
} |
q259905 | PaymentAuthorizationBuilder.build | test | public function build(array $data)
{
$this->validateArrayKeys(
array('id', 'create_time', 'update_time', 'state', 'intent', 'payer', 'transactions', 'links'),
$data
);
if (empty($data['id'])) {
throw new BuilderException('id is mandatory and should not be empty');
}
$payer = $this->payerBuilder->build($data['payer']);
$transactions = $this->transactionsBuilder->build($data['transactions']);
$links = array();
foreach ($data['links'] as $link) {
$links[] = $this->linkBuilder->build($link);
}
if ($data['payer']['payment_method'] === 'paypal') {
$authorization = new PaypalPaymentAuthorization(
$data['id'],
$data['create_time'],
$data['state'],
$data['intent'],
$payer,
$transactions,
$links,
$data['update_time']
);
$authorization->setPaypalData($data);
return $authorization;
}
$authorization = new CreditCardPaymentAuthorization(
$data['id'],
$data['create_time'],
$data['state'],
$data['intent'],
$payer,
$transactions,
$links,
$data['update_time']
);
$authorization->setPaypalData($data);
return $authorization;
} | php | {
"resource": ""
} |
q259906 | PayerBuilder.build | test | public function build(array $data)
{
$this->validateArrayKeys(
array('payment_method'),
$data
);
if ( ! in_array($data['payment_method'], array('credit_card', 'paypal'))) {
throw new BuilderException('Parameter payment_method not valid. Allowed values: "credit_card" and "paypal"');
}
$fundingInstruments = array();
if (isset($data['funding_instruments'])) {
$fundingInstruments = $data['funding_instruments'];
}
$info = array();
if (isset($data['payer_info'])) {
$info = $data['payer_info'];
}
return new Payer($data['payment_method'], $fundingInstruments, $info);
} | php | {
"resource": ""
} |
q259907 | PayerBuilder.buildArray | test | public function buildArray($payer)
{
$payerData = array();
if ($payer instanceof PayerInterface) {
$payerData['payment_method'] = $payer->getPaymentMethod();
if ($fundingInstruments = $payer->getFundingInstruments())
{
$payerData['funding_instruments'] = $fundingInstruments;
}
if ($info = $payer->getInfo())
{
$payerData['payer_info'] = $info;
}
return $payerData;
}
if (
($payer instanceof \ArrayAccess || is_array($payer)) &&
isset($payer['payment_method'])
) {
$payerData['payment_method'] = $payer['payment_method'];
if (isset($payer['funding_instruments']))
{
$payerData['funding_instruments'] = $payer['funding_instruments'];
}
if (isset($payer['payer_info']))
{
$payerData['payer_info'] = $payer['payer_info'];
}
return $payerData;
}
throw new BuilderException('Payer is not valid');
} | php | {
"resource": ""
} |
q259908 | AuthorizationBuilder.build | test | public function build(array $data)
{
$this->validateArrayKeys(
array('amount', 'create_time', 'update_time', 'state', 'parent_payment', 'id', 'valid_until', 'links'),
$data
);
$links = array();
foreach ($data['links'] as $link) {
$links[] = $this->linkBuilder->build($link);
}
$authorization = new Authorization(
$data['id'],
$data['create_time'],
$data['update_time'],
$this->amountBuilder->build($data['amount']),
$data['state'],
$data['parent_payment'],
$data['valid_until'],
$links
);
return $authorization;
} | php | {
"resource": ""
} |
q259909 | Obfuscater.make | test | public static function make($value)
{
$safe = '';
foreach (str_split($value) as $letter) {
if (ord($letter) > 128)
return $letter;
self::makeSafer($safe, $letter);
}
return $safe;
} | php | {
"resource": ""
} |
q259910 | Obfuscater.makeSafer | test | private static function makeSafer(&$safe, $letter)
{
// To properly obfuscate the value, we will randomly convert each letter to
// its entity or hexadecimal representation, keeping a bot from sniffing
// the randomly obfuscated letters out of the string on the responses.
switch (rand(1, 3)) {
case 1:
$safe .= '&#' . ord($letter).';';
break;
case 2:
$safe .= '&#x' . dechex(ord($letter)).';';
break;
case 3:
$safe .= $letter;
// no break
}
} | php | {
"resource": ""
} |
q259911 | FormAccessible.getFormValue | test | public function getFormValue($key)
{
$value = $this->getAttributeFromArray($key);
if (in_array($key, $this->getDates()) && ! is_null($value))
$value = $this->asDateTime($value);
return $this->hasFormMutator($key)
? $this->mutateFormAttribute($key, $value)
: data_get($this, $key); // No form mutator, let the model resolve this
} | php | {
"resource": ""
} |
q259912 | FormAccessible.hasFormMutator | test | protected function hasFormMutator($key)
{
$methods = $this->getReflection()->getMethods(ReflectionMethod::IS_PUBLIC);
return collect($methods)->filter(function (ReflectionMethod $method) use ($key) {
return $method->name === $this->getMutateFromMethodName($key);
})->isNotEmpty();
} | php | {
"resource": ""
} |
q259913 | FormAccessible.getReflection | test | protected function getReflection()
{
if (is_null($this->reflection)) {
$this->reflection = new ReflectionClass($this);
}
return $this->reflection;
} | php | {
"resource": ""
} |
q259914 | HtmlBuilder.favicon | test | public function favicon($url, array $attributes = [], $secure = null)
{
$attributes = array_merge([
'rel' => 'shortcut icon',
'type' => 'image/x-icon',
], $attributes);
return Elements\Element::withTag('link')
->attribute('href', $this->url->asset($url, $secure))
->attributes($attributes)
->render();
} | php | {
"resource": ""
} |
q259915 | HtmlBuilder.link | test | public function link($url, $title = null, array $attributes = [], $secure = null, $escaped = true)
{
$url = $this->url->to($url, [], $secure);
if (is_null($title) || $title === false)
$title = $url;
return Elements\A::make()
->href($this->entities($url))
->attributes($attributes)
->html($escaped ? $this->entities($title) : $title)
->render();
} | php | {
"resource": ""
} |
q259916 | HtmlBuilder.ol | test | public function ol(array $items, array $attributes = [])
{
return Elements\Ol::make()
->items($items)
->attributes($attributes)
->render();
} | php | {
"resource": ""
} |
q259917 | HtmlBuilder.ul | test | public function ul(array $items, array $attributes = [])
{
return Elements\Ul::make()
->items($items)
->attributes($attributes)
->render();
} | php | {
"resource": ""
} |
q259918 | FormBuilder.getModelValueAttribute | test | private function getModelValueAttribute($name, $model = null)
{
$model = $model ?: $this->getModel();
$key = self::transformKey($name);
if (strpos($key, '.') !== false) {
$keys = explode('.', $key, 2);
return $this->getModelValueAttribute(
$keys[1],
$this->getModelValueAttribute($keys[0], $model)
);
}
return method_exists($model, 'getFormValue')
? $model->getFormValue($key)
: data_get($model, $key);
} | php | {
"resource": ""
} |
q259919 | FormBuilder.text | test | public function text($name, $value = null, array $attributes = [])
{
return $this->input('text', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259920 | FormBuilder.email | test | public function email($name, $value = null, array $attributes = [])
{
return $this->input('email', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259921 | FormBuilder.tel | test | public function tel($name, $value = null, array $attributes = [])
{
return $this->input('tel', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259922 | FormBuilder.number | test | public function number($name, $value = null, array $attributes = [])
{
return $this->input('number', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259923 | FormBuilder.url | test | public function url($name, $value = null, array $attributes = [])
{
return $this->input('url', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259924 | FormBuilder.color | test | public function color($name, $value = null, array $attributes = [])
{
return $this->input('color', $name, $value, $attributes);
} | php | {
"resource": ""
} |
q259925 | FormBuilder.getCheckboxCheckedState | test | private function getCheckboxCheckedState($name, $value, $checked)
{
if (
isset($this->session) &&
! $this->oldInputIsEmpty() &&
is_null($this->old($name))
)
return false;
if ($this->missingOldAndModel($name))
return $checked;
$posted = $this->getValueAttribute($name, $checked);
if (is_array($posted))
return in_array($value, $posted);
if ($posted instanceof Collection)
return $posted->contains('id', $value);
return (bool) $posted;
} | php | {
"resource": ""
} |
q259926 | FormBuilder.getUrlAction | test | private function getUrlAction($attribute)
{
return is_array($attribute)
? $this->url->to($attribute[0], array_slice($attribute, 1))
: $this->url->to($attribute);
} | php | {
"resource": ""
} |
q259927 | FormBuilder.getRouteAction | test | private function getRouteAction($attribute)
{
return is_array($attribute)
? $this->url->route($attribute[0], array_slice($attribute, 1))
: $this->url->route($attribute);
} | php | {
"resource": ""
} |
q259928 | FormBuilder.getControllerAction | test | private function getControllerAction($attribute)
{
return is_array($attribute)
? $this->url->action($attribute[0], array_slice($attribute, 1))
: $this->url->action($attribute);
} | php | {
"resource": ""
} |
q259929 | Buffer.insert | test | public function insert(string $string, int $position)
{
$this->data = substr_replace($this->data, $string, $position, 0);
} | php | {
"resource": ""
} |
q259930 | Buffer.search | test | public function search($string, $reverse = false)
{
if ($reverse) {
return strrpos($this->data, $string);
}
return strpos($this->data, $string);
} | php | {
"resource": ""
} |
q259931 | Buffer.offsetSet | test | public function offsetSet($index, $data)
{
$this->data = substr_replace($this->data, $data, $index, 1);
} | php | {
"resource": ""
} |
q259932 | Buffer.offsetUnset | test | public function offsetUnset($index)
{
if (isset($this->data[$index])) {
$this->data = substr_replace($this->data, null, $index, 1);
}
} | php | {
"resource": ""
} |
q259933 | ReadablePipe.fetch | test | private function fetch($resource, int $length = self::CHUNK_SIZE, string $byte = null): string
{
$remaining = $length;
if (('' === $this->buffer || 0 < ($remaining -= strlen($this->buffer))) && is_resource($resource)) {
// Error reporting suppressed since fread() produces a warning if the stream unexpectedly closes.
$this->buffer .= @fread($resource, $remaining);
}
if (null === $byte || false === ($position = strpos($this->buffer, $byte))) {
if (strlen($this->buffer) <= $length) {
$data = $this->buffer;
$this->buffer = '';
return $data;
}
$position = $length;
} else {
++$position; // Include byte in result.
}
$data = (string) substr($this->buffer, 0, $position);
$this->buffer = (string) substr($this->buffer, $position);
return $data;
} | php | {
"resource": ""
} |
q259934 | CommandTrait.parseFile | test | protected function parseFile($name, Closure $callback)
{
$url = $this->files[$name]['url'];
$basename = basename($url);
$storagePath = config('geonames.storagePath');
// Final file path
$path = $storagePath . '/' . $this->files[$name]['filename'] . '.txt';
// Check if file exists (should be since we just downloaded them)
$downloadedFilePath = $storagePath . '/' . $basename;
if (!file_exists($downloadedFilePath)) {
throw new RuntimeException('File does not exist: ' . $downloadedFilePath);
}
// If it is a zip file we must unzip it
if (substr($basename, -4) === '.zip') {
$this->unZip($name);
}
$steps = $this->getLineCount($path);
/* @var $output OutputStyle */
$output = $this->getOutput();
$bar = $output->createProgressBar($steps);
$bar->setFormat('<info>Seeding File:</info> ' . basename($path) . ' %current%/%max% %bar% %percent%% <info>Remaining Time:</info> %remaining%');
$steps = 0;
$fh = fopen($path, 'r');
if (!$fh) {
throw new RuntimeException("Can not open file: $path");
}
while (!feof($fh)) {
$line = fgets($fh);
// ignore empty lines and comments
if (!$line or $line === '' or strpos($line, '#') === 0) continue;
// Geonames format is tab seperated
$line = explode("\t", $line);
// Insert using closure
$callback($line);
$steps++;
if (isset($bar) && $steps % ($this->bufferSize * 10) === 0)
$bar->advance($this->bufferSize * 10);
}
fclose($fh);
if (isset($bar)) {
$bar->finish();
$output->newLine();
}
// If we wont keep txt version delete file
if (substr($basename, -4) === '.zip' && !config('geonames.keepTxt')) {
$this->line('<info>Removing File:</info> ' . basename($path));
unlink($path);
}
} | php | {
"resource": ""
} |
q259935 | CommandTrait.getLineCount | test | protected function getLineCount($path)
{
$fh = fopen($path, 'r');
if (!$fh) {
throw new RuntimeException("Can not open file: $path");
}
$fileSize = @filesize($path);
/* @var $output OutputStyle */
$output = $this->getOutput();
$bar = $output->createProgressBar($fileSize);
$bar->setFormat('<info>Reading File:</info> ' . basename($path) . ' %bar% %percent%% <info>Remaining Time:</info> %remaining%');
$steps = 0;
$currentSize = 0;
while (!feof($fh)) {
$line = fgets($fh);
$currentSize += strlen($line);
// ignore empty lines and comments
if (!$line or $line === '' or strpos($line, '#') === 0) continue;
$steps++;
// Reading is so much faster, must slow down advances
if (isset($bar) && $steps % ($this->bufferSize * 100) === 0) {
$bar->advance($currentSize);
$currentSize = 0;
}
}
fclose($fh);
if (isset($bar)) {
$bar->finish();
$output->newLine();
}
return $steps;
} | php | {
"resource": ""
} |
q259936 | CommandTrait.unZip | test | protected function unZip($name)
{
$zipFileName = basename($this->files[$name]['url']);
if (!substr($zipFileName, -4) === '.zip')
throw new RuntimeException($zipFileName . ' does not have .zip extension');
// Final file path
$storagePath = config('geonames.storagePath');
$extractedFile = $this->files[$name]['filename'] . '.txt';
$path = $storagePath . '/' . $extractedFile;
// Open zip archive because we need the size of extracted file
$zipArchive = new ZipArchive;
$zipArchive->open($storagePath . '/' . $zipFileName);
if (file_exists($path)) {
$uncompressedSize = $zipArchive->statName($extractedFile)['size'];
$fileSize = filesize($path);
if ($uncompressedSize !== $fileSize) {
$this->line('<info>Existing File:</info> ' . basename($path) . ' size does not match the one in ' . $zipFileName);
} else {
// Do not extract again
$this->line('<info>Existing File:</info> ' . 'Found ' . basename($path) . ' file extracted from ' . $zipFileName);
$zipArchive->close();
return;
}
}
// File does not exist or size does not match
$this->line('<info>Extracting File:</info> ' . $extractedFile . ' from ' . $zipFileName . ' ...!!!Please Wait!!!...');
// Extract file
$zipArchive->extractTo($storagePath . '/', $extractedFile);
$zipArchive->close();
} | php | {
"resource": ""
} |
q259937 | CommandTrait.getUrlSize | test | protected function getUrlSize($url)
{
$data = get_headers($url, true);
if (isset($data['Content-Length']))
return (int)$data['Content-Length'];
return false;
} | php | {
"resource": ""
} |
q259938 | CommandTrait.getFilesArray | test | protected function getFilesArray()
{
static $firstRun = true;
if ($firstRun) {
$this->updateFilesList();
$firstRun = false;
}
$data = $this->files;
foreach ($data as $key => $value) {
if (in_array($value['table'], config('geonames.ignoreTables'))) {
unset($data[$key]);
}
}
return $data;
} | php | {
"resource": ""
} |
q259939 | MemoryStream.free | test | protected function free(\Throwable $exception = null)
{
$this->readable = false;
$this->writable = false;
if (null !== $this->delayed) {
$this->delayed->resolve('');
}
if (0 !== $this->hwm) {
while (!$this->queue->isEmpty()) {
/** @var \Icicle\Awaitable\Delayed $delayed */
$delayed = $this->queue->shift();
$delayed->reject(
$exception = $exception ?: new ClosedException('The stream was unexpectedly closed.')
);
}
}
} | php | {
"resource": ""
} |
q259940 | MemoryStream.remove | test | private function remove(): string
{
if (null !== $this->byte && false !== ($position = $this->buffer->search($this->byte))) {
if (0 === $this->length || $position < $this->length) {
return $this->buffer->shift($position + 1);
}
return $this->buffer->shift($this->length);
}
if (0 === $this->length) {
return $this->buffer->drain();
}
return $this->buffer->shift($this->length);
} | php | {
"resource": ""
} |
q259941 | BufferIterator.seek | test | public function seek($position)
{
$position = (int) $position;
if (0 > $position) {
$position = 0;
}
$this->current = $position;
} | php | {
"resource": ""
} |
q259942 | BufferIterator.insert | test | public function insert(string $data)
{
if (!$this->valid()) {
throw new OutOfBoundsException('The iterator is not valid!');
}
$this->buffer[$this->current] = $data . $this->buffer[$this->current];
} | php | {
"resource": ""
} |
q259943 | BufferIterator.replace | test | public function replace(string $data): string
{
if (!$this->valid()) {
throw new OutOfBoundsException('The iterator is not valid!');
}
$temp = $this->buffer[$this->current];
$this->buffer[$this->current] = $data;
return $temp;
} | php | {
"resource": ""
} |
q259944 | BufferIterator.remove | test | public function remove(): string
{
if (!$this->valid()) {
throw new OutOfBoundsException('The iterator is not valid!');
}
$temp = $this->buffer[$this->current];
unset($this->buffer[$this->current]);
--$this->current;
return $temp;
} | php | {
"resource": ""
} |
q259945 | Install.publishDirectory | test | protected function publishDirectory($from, $to)
{
$toContents = $this->files->files($to);
$fromContents = $this->files->files($from);
foreach ($fromContents as $file) {
$newFile = $to . DIRECTORY_SEPARATOR . $this->files->name($file) . '.' . $this->files->extension($file);
if ($this->files->isFile($file) && (!in_array($newFile, $toContents) || $this->option('force'))) {
$this->files->copy($file, $newFile);
}
}
$this->status($from, $to, 'Directory');
} | php | {
"resource": ""
} |
q259946 | StreamResource.close | test | public function close()
{
if (is_resource($this->resource)) {
fclose($this->resource);
}
$this->resource = null;
$this->autoClose = false;
} | php | {
"resource": ""
} |
q259947 | GeonamesGeoname.scopeAdmin1 | test | public function scopeAdmin1($query)
{
$table = 'geonames_geonames';
if (!isset($query->getQuery()->columns))
$query = $query->addSelect($this->usefulScopeColumns);
$query = $query
->leftJoin('geonames_admin1_codes as admin1', 'admin1.code', '=',
DB::raw('CONCAT_WS(\'.\',' .
$table . '.country_code,' .
$table . '.admin1_code)')
)
->addSelect(
'admin1.geoname_id as admin1_geoname_id',
'admin1.name as admin1_name'
);
return $query;
} | php | {
"resource": ""
} |
q259948 | GeonamesGeoname.scopeAddCountryInfo | test | public function scopeAddCountryInfo($query)
{
$table = 'geonames_geonames';
if (!isset($query->getQuery()->columns))
$query = $query->addSelect($this->usefulScopeColumns);
$query = $query
->leftJoin('geonames_country_infos as country_info', $table . '.country_code', '=',
'country_info.iso'
)
->addSelect(
'country_info.geoname_id as country_info_geoname_id',
'country_info.country as country_info_country'
);
return $query;
} | php | {
"resource": ""
} |
q259949 | GeonamesGeoname.scopeCity | test | public function scopeCity($query, $name = null, $featureCodes = ['PPLC', 'PPLA', 'PPLA2', 'PPLA3'])
{
return $this->scopeSearchByFeature($query,$name,'P',$featureCodes);
} | php | {
"resource": ""
} |
q259950 | GeonamesGeoname.scopeCountry | test | public function scopeCountry($query, $name = null, $featureCodes = ['PCLI'])
{
return $this->scopeSearchByFeature($query,$name,'A',$featureCodes);
} | php | {
"resource": ""
} |
q259951 | GeonamesGeoname.scopeSearchByFeature | test | public function scopeSearchByFeature($query, $name = null, $feature_class=null, $featureCodes = null)
{
$table = 'geonames_geonames';
if (!isset($query->getQuery()->columns))
$query = $query->addSelect($this->usefulScopeColumns);
if ($name !== null)
$query = $query->where($table . '.name', 'LIKE', $name);
$query = $query
->where($table . '.feature_class', $feature_class)
->whereIn($table . '.feature_code', $featureCodes);
return $query;
} | php | {
"resource": ""
} |
q259952 | NodeRedirectService.createPendingRedirects | test | public function createPendingRedirects()
{
$this->nodeFactory->reset();
foreach ($this->pendingRedirects as $nodeIdentifierAndWorkspace => $oldUriPerDimensionCombination) {
list($nodeIdentifier, $workspaceName) = explode('@', $nodeIdentifierAndWorkspace);
$this->buildRedirects($nodeIdentifier, $workspaceName, $oldUriPerDimensionCombination);
}
$this->persistenceManager->persistAll();
} | php | {
"resource": ""
} |
q259953 | NodeRedirectService.hasNodeUriChanged | test | protected function hasNodeUriChanged(NodeInterface $node, Workspace $targetWorkspace): bool
{
$newUriPath = $this->buildUriPathForNode($node);
$newUriPath = $this->removeContextInformationFromRelativeNodeUri($newUriPath);
$nodeInTargetWorkspace = $this->getNodeInWorkspace($node, $targetWorkspace);
if (!$nodeInTargetWorkspace) {
return false;
}
$oldUriPath = $this->buildUriPathForNode($nodeInTargetWorkspace);
$oldUriPath = $this->removeContextInformationFromRelativeNodeUri($oldUriPath);
return ($newUriPath !== $oldUriPath);
} | php | {
"resource": ""
} |
q259954 | NodeRedirectService.buildRedirects | test | protected function buildRedirects(string $nodeIdentifier, string $workspaceName, array $oldUriPerDimensionCombination)
{
foreach ($oldUriPerDimensionCombination as list($oldRelativeUri, $dimensionCombination)) {
$this->createRedirectFrom($oldRelativeUri, $nodeIdentifier, $workspaceName, $dimensionCombination);
}
} | php | {
"resource": ""
} |
q259955 | NodeRedirectService.createRedirectFrom | test | protected function createRedirectFrom(string $oldUri, string $nodeIdentifer, string $workspaceName, array $dimensionCombination): bool
{
$node = $this->getNodeInWorkspaceAndDimensions($nodeIdentifer, $workspaceName, $dimensionCombination);
if ($node === null) {
return false;
}
if ($this->isRestrictedByNodeType($node) || $this->isRestrictedByPath($node)) {
return false;
}
$newUri = $this->buildUriPathForNode($node);
if ($node->isRemoved()) {
return $this->removeNodeRedirectIfNeeded($node, $newUri);
}
if ($oldUri === $newUri) {
return false;
}
$hosts = $this->getHostnames($node->getContext());
$this->flushRoutingCacheForNode($node);
$statusCode = (integer)$this->defaultStatusCode['redirect'];
$this->redirectStorage->addRedirect($oldUri, $newUri, $statusCode, $hosts);
return true;
} | php | {
"resource": ""
} |
q259956 | NodeRedirectService.removeNodeRedirectIfNeeded | test | protected function removeNodeRedirectIfNeeded(NodeInterface $node, string $newUri): bool
{
// By default the redirect handling for removed nodes is activated.
// If it is deactivated in your settings you will be able to handle the redirects on your own.
// For example redirect to dedicated landing pages for deleted campaign NodeTypes
if ($this->enableRemovedNodeRedirect) {
$hosts = $this->getHostnames($node->getContext());
$this->flushRoutingCacheForNode($node);
$statusCode = (integer)$this->defaultStatusCode['gone'];
$this->redirectStorage->addRedirect($newUri, '', $statusCode, $hosts);
return true;
}
return false;
} | php | {
"resource": ""
} |
q259957 | NodeRedirectService.isRestrictedByNodeType | test | protected function isRestrictedByNodeType(NodeInterface $node): bool
{
if (!isset($this->restrictByNodeType)) {
return false;
}
foreach ($this->restrictByNodeType as $disabledNodeType => $status) {
if ($status !== true) {
continue;
}
if ($node->getNodeType()->isOfType($disabledNodeType)) {
$this->systemLogger->log(vsprintf('Redirect skipped based on the current node type (%s) for node %s because is of type %s', [
$node->getNodeType()->getName(),
$node->getContextPath(),
$disabledNodeType
]), LOG_DEBUG, null, 'RedirectHandler');
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q259958 | NodeRedirectService.isRestrictedByPath | test | protected function isRestrictedByPath(NodeInterface $node): bool
{
if (!isset($this->restrictByPathPrefix)) {
return false;
}
foreach ($this->restrictByPathPrefix as $pathPrefix => $status) {
if ($status !== true) {
continue;
}
$pathPrefix = rtrim($pathPrefix, '/') . '/';
if (mb_strpos($node->getPath(), $pathPrefix) === 0) {
$this->systemLogger->log(vsprintf('Redirect skipped based on the current node path (%s) for node %s because prefix matches %s', [
$node->getPath(),
$node->getContextPath(),
$pathPrefix
]), LOG_DEBUG, null, 'RedirectHandler');
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q259959 | NodeRedirectService.getHostnames | test | protected function getHostnames(ContentContext $contentContext): array
{
$domains = [];
$site = $contentContext->getCurrentSite();
if ($site === null) {
return $domains;
}
foreach ($site->getActiveDomains() as $domain) {
/** @var Domain $domain */
$domains[] = $domain->getHostname();
}
return $domains;
} | php | {
"resource": ""
} |
q259960 | NodeRedirectService.getUriBuilder | test | protected function getUriBuilder(): UriBuilder
{
if ($this->uriBuilder !== null) {
return $this->uriBuilder;
}
$httpRequest = Request::createFromEnvironment();
$actionRequest = new ActionRequest($httpRequest);
$this->uriBuilder = new UriBuilder();
$this->uriBuilder
->setRequest($actionRequest);
$this->uriBuilder
->setFormat('html')
->setCreateAbsoluteUri(false);
return $this->uriBuilder;
} | php | {
"resource": ""
} |
q259961 | tl_short_urls.loadName | test | public function loadName($varValue, DataContainer $dc)
{
// check for query parameters
if (strpos($varValue, '?') !== false)
{
$pos = strpos($varValue, '?');
$url = substr($varValue, 0, $pos);
$par = substr($varValue, $pos + 1);
if ($par)
{
parse_str($par, $arrParameters);
return rawurldecode($url) . '?' . http_build_query($arrParameters);
}
}
return rawurldecode($varValue);
} | php | {
"resource": ""
} |
q259962 | tl_short_urls.validate | test | private function validate($name, $domain)
{
// check if a page exists
if( !\Config::get('urlSuffix') && ( $objPages = \PageModel::findByAlias( $name ) ) !== null )
{
// check if short url has a domain
if( $domain > 0 )
{
$valid = true;
while( $objPages->next() )
{
// load page details
$objPages->current()->loadDetails();
// if one of the found pages is within the same domain, do not allow it
if( $objPages->rootId == $domain )
{
$valid = false;
break;
}
}
if( $valid )
return;
}
// otherwise throw exception
throw new Exception(sprintf($GLOBALS['TL_LANG']['tl_short_urls']['pageExists'], $name));
}
} | php | {
"resource": ""
} |
q259963 | tl_short_urls.pagePicker | test | public function pagePicker(DataContainer $dc)
{
return ' <a href="contao/page.php?do=' . Input::get('do') . '&table=' . $dc->table . '&field=' . $dc->field . '&value=' . str_replace(array('{{link_url::', '}}'), '', $dc->value) . '&switch=1' . '" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['pagepicker']) . '" onclick="Backend.getScrollOffset();Backend.openModalSelector({\'width\':768,\'title\':\'' . specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MOD']['page'][0])) . '\',\'url\':this.href,\'id\':\'' . $dc->field . '\',\'tag\':\'ctrl_'. $dc->field . ((Input::get('act') == 'editAll') ? '_' . $dc->id : '') . '\',\'self\':this});return false">' . Image::getHtml('pickpage.gif', $GLOBALS['TL_LANG']['MSC']['pagepicker'], 'style="vertical-align:top;cursor:pointer"') . '</a>';
} | php | {
"resource": ""
} |
q259964 | tl_short_urls.labelCallback | test | public function labelCallback($arrRow)
{
// get the target URL
$targetURL = \ShortURLs::processTarget( $arrRow['target'] );
// remove current host
$targetURL = str_replace( \Environment::get('base'), '', $targetURL );
// check for domain restriction
$domain = '';
if( $arrRow['domain'] && ( $objPage = \PageModel::findById( $arrRow['domain'] ) ) !== null )
$domain = $objPage->dns . '/';
// generate list record
return '<div class="tl_content_right"><span style="color:rgb(200,200,200)">[' . ( $arrRow['redirect'] == 'permanent' ? 301 : 302 ) . ']</span></div><div class="tl_content_left">' . $domain . rawurldecode($arrRow['name']) . ' » ' . rawurldecode($targetURL) . ' </div>';
} | php | {
"resource": ""
} |
q259965 | admin.init | test | public static function init() {
$class = get_called_class();
// Admin menu entry for upload debugging.
add_action('admin_menu', array($class, 'menu_debug'));
// Override upload file validation (general).
add_filter('wp_check_filetype_and_ext', array($class, 'check_filetype_and_ext'), 10, 4);
// Override upload file validation (SVG).
add_filter('wp_check_filetype_and_ext', array($class, 'check_filetype_and_ext_svg'), 15, 4);
// Set up translations.
add_action('plugins_loaded', array($class, 'localize'));
// Update check on debug page.
add_action('admin_notices', array($class, 'debug_notice'));
// AJAX hook for disabling contributor lookups.
add_action('wp_ajax_bm_ajax_disable_contributor_notice', array($class, 'disable_contributor_notice'));
// And the corresponding warnings.
add_filter('admin_notices', array($class, 'contributors_changed_notice'));
// Pull remote contributor information.
$next = wp_next_scheduled('cron_get_remote_contributors');
if ('disabled' === get_option('bm_contributor_notice', false)) {
// Make sure the CRON job is disabled.
if ($next) {
wp_unschedule_event($next, 'cron_get_remote_contributors');
}
}
else {
add_action('cron_get_remote_contributors', array($class, 'cron_get_remote_contributors'));
if (!$next) {
wp_schedule_event(time(), 'hourly', 'cron_get_remote_contributors');
}
}
// Register plugins page quick links if we aren't running in
// Must-Use mode.
if (!BLOBMIMES_MUST_USE) {
add_filter('plugin_action_links_' . plugin_basename(BLOBMIMES_INDEX), array($class, 'plugin_action_links'));
}
} | php | {
"resource": ""
} |
q259966 | admin.plugin_action_links | test | public static function plugin_action_links($links) {
if (current_user_can('manage_options')) {
$links[] = '<a href="' . esc_url(admin_url('tools.php?page=blob-mimes-admin')) . '">' . __('Debug File Validation', 'blob-mimes') . '</a>';
}
$links[] = '<a href="https://github.com/Blobfolio/blob-mimes/tree/master/wp" target="_blank" rel="noopener">' . esc_html__('Documentation', 'blob-mimes') . '</a>';
return $links;
} | php | {
"resource": ""
} |
q259967 | admin.get_version | test | public static function get_version() {
if (is_null(static::$version)) {
$plugin_data = get_plugin_data(BLOBMIMES_INDEX, false, false);
if (isset($plugin_data['Version'])) {
static::$version = $plugin_data['Version'];
}
else {
static::$version = '0.0';
}
}
return static::$version;
} | php | {
"resource": ""
} |
q259968 | admin.get_remote_version | test | public static function get_remote_version() {
if (is_null(static::$remote_version)) {
$response = plugins_api(
'plugin_information',
array('slug'=>'blob-mimes')
);
if (
!is_wp_error($response) &&
is_a($response, 'stdClass') &&
isset($response->version)
) {
static::$remote_version = $response->version;
static::$remote_home = $response->homepage;
}
else {
static::$remote_version = '0.0';
}
}
return static::$remote_version;
} | php | {
"resource": ""
} |
q259969 | admin.check_filetype_and_ext | test | public static function check_filetype_and_ext($checked, $file, $filename, $mimes) {
// We don't care what WP has already done.
$proper_filename = false;
// Do basic extension validation and MIME mapping.
$wp_filetype = mime::check_real_filetype($file, $filename, $mimes);
$ext = $wp_filetype['ext'];
$type = $wp_filetype['type'];
// We can't do any further validation without a file to work with.
if (!@file_exists($file)) {
return compact('ext', 'type', 'proper_filename');
}
// If the type is valid, should we be renaming the file?
if (false !== $ext && false !== $type) {
$new_filename = mime::update_filename_extension($filename, $ext);
if ($filename !== $new_filename) {
$proper_filename = $new_filename;
}
}
return compact('ext', 'type', 'proper_filename');
} | php | {
"resource": ""
} |
q259970 | admin.check_filetype_and_ext_svg | test | public static function check_filetype_and_ext_svg($checked, $file, $filename, $mimes) {
// Only need to do something if the type is SVG.
if ('image/svg+xml' === $checked['type']) {
try {
$contents = @file_get_contents($file);
$contents = svg::sanitize($contents);
// Overwrite the contents if we're good.
if (is_string($contents) && $contents) {
@file_put_contents($file, $contents);
// In case it got renamed somewhere along the way.
if ($checked['proper_filename']) {
$checked['proper_filename'] = mime::update_filename_extension($checked['proper_filename'], '.svg');
}
}
// Otherwise just fail the download.
else {
$checked['type'] = $checked['ext'] = false;
}
} catch (\Throwable $e) {
error_log($e->getMessage());
$checked['type'] = $checked['ext'] = false;
} catch (\Exception $e) {
$checked['type'] = $checked['ext'] = false;
}
}
return $checked;
} | php | {
"resource": ""
} |
q259971 | admin.parse_readme_contributors | test | protected static function parse_readme_contributors($file) {
if (!$file || !@is_file($file)) {
return false;
}
require_once (ABSPATH . 'wp-admin/includes/file.php');
// This can actually be parsed the same way plugin index files
// are. Neat!
$headers = get_file_data($file, array('Contributors'=>'Contributors'));
if (isset($headers['Contributors'])) {
// These are comma-separated, so let's array-ize them and
// clean it up a bit.
$headers['Contributors'] = explode(',', $headers['Contributors']);
foreach ($headers['Contributors'] as $k=>$v) {
$headers['contributors'][$k] = trim($v);
if (!$v) {
unset($headers['contributors'][$k]);
}
}
// We should have at least one!
if (count($headers['contributors'])) {
$headers['contributors'] = array_unique($headers['contributors']);
sort($headers['contributors']);
return $headers['contributors'];
}
}
// No go.
return false;
} | php | {
"resource": ""
} |
q259972 | admin.get_plugin_slug_by_path | test | public static function get_plugin_slug_by_path($path) {
if (is_string($path) && $path) {
$slug = $path;
while (false !== strpos($slug, '/')) {
$slug = dirname($slug);
}
$slug = preg_replace('/\.php$/i', '', $slug);
return $slug ? $slug : false;
}
return false;
} | php | {
"resource": ""
} |
q259973 | admin.cron_get_remote_contributors | test | public static function cron_get_remote_contributors() {
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugins = get_plugins();
$out = array();
// We'll also keep track of plugins that aren't hosted on
// WP.org. This might change, so we'll periodically rebuild the
// list.
$save_invalid = false;
if (false === ($invalid = get_transient('bm_external_plugins'))) {
$save_invalid = true;
$invalid = array();
}
foreach ($plugins as $k=>$v) {
// Can't check it.
if (
false === ($slug = static::get_plugin_slug_by_path($k)) ||
isset($invalid[$slug])
) {
continue;
}
// The plugins_api() function does not fully support the
// API spec, so we have to do this manually.
$url = sprintf(static::PLUGIN_API, $slug);
$response = wp_remote_get(
$url,
array(
'timeout'=>3,
)
);
if (200 === wp_remote_retrieve_response_code($response)) {
$body = wp_remote_retrieve_body($response);
$body = json_decode($body, true);
if ($body) {
// If WP returned an error, note the slug so we can
// avoid checking it in the future.
if (isset($body['error'])) {
$invalid[$slug] = true;
$save_invalid = true;
continue;
}
if (
isset($body['contributors']) &&
is_array($body['contributors']) &&
count($body['contributors'])
) {
ksort($body['contributors']);
$out[$slug] = array_keys($body['contributors']);
}
}
}
}
// Save the contributors.
update_option('bm_remote_contributors', $out);
// Save the invalid plugins.
if ($save_invalid) {
set_transient('bm_external_plugins', $invalid, DAY_IN_SECONDS);
}
} | php | {
"resource": ""
} |
q259974 | FileTrait.validate | test | private function validate()
{
$file = $this->file;
if (!is_file($file)) {
throw new \RuntimeException(sprintf("'%s' is not a file", $file));
}
if (!is_readable($file)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException(sprintf("'%s' is not a readable file", $file));
// @codeCoverageIgnoreEnd
}
} | php | {
"resource": ""
} |
q259975 | FileTrait.getSupportedLoader | test | private function getSupportedLoader($data)
{
$loaders = $this->vars->loader->getLoaders();
foreach ($loaders as $loader) {
$class_loader = new \ReflectionClass($loader);
$class_loader = $class_loader->newInstanceArgs(array($data));
if ($class_loader->supports()) {
return $class_loader;
}
}
return false;
} | php | {
"resource": ""
} |
q259976 | FileTrait.loadContent | test | private function loadContent($data)
{
$loader = $this->getSupportedLoader($data);
if (!$loader) {
throw new \InvalidArgumentException(sprintf("'%s' is not supported by the current loaders", $this->file));
}
$loader->load();
return $loader->getContent();
} | php | {
"resource": ""
} |
q259977 | VarsServiceProvider.createOptions | test | private function createOptions($app)
{
$options = array();
if (isset($app['vars.path'])) {
$options['path'] = $app['vars.path'];
}
if (isset($app['vars.options'])) {
$options = $this->createKeyedOptions($options, $app['vars.options']);
}
if (!isset($options['merge_globals']) || is_null($options['merge_globals'])) {
$options['merge_globals'] = false;
}
if (isset($app['debug']) && $app['debug']) {
$options['cache'] = false;
}
return $options;
} | php | {
"resource": ""
} |
q259978 | svg_base.get_allowed_tags | test | public static function get_allowed_tags() {
$tags = array(
'a',
'altGlyph',
'altGlyphDef',
'altGlyphItem',
'animate',
'animateColor',
'animateMotion',
'animateTransform',
'audio',
'canvas',
'circle',
'clipPath',
'color-profile',
'cursor',
'defs',
'desc',
'discard',
'ellipse',
'feBlend',
'feColorMatrix',
'feComponentTransfer',
'feComposite',
'feConvolveMatrix',
'feDiffuseLighting',
'feDisplacementMap',
'feDistantLight',
'feDropShadow',
'feFlood',
'feFuncA',
'feFuncB',
'feFuncG',
'feFuncR',
'feGaussianBlur',
'feImage',
'feMerge',
'feMergeNode',
'feMorphology',
'feOffset',
'fePointLight',
'feSpecularLighting',
'feSpotLight',
'feTile',
'feTurbulence',
'filter',
'font',
'font-face',
'font-face-format',
'font-face-name',
'font-face-src',
'font-face-uri',
'g',
'glyph',
'glyphRef',
'hatch',
'hatchpath',
'hkern',
'image',
'line',
'linearGradient',
'marker',
'mask',
'mesh',
'meshgradient',
'meshpatch',
'meshrow',
'metadata',
'missing-glyph',
'mpath',
'path',
'pattern',
'polygon',
'polyline',
'radialGradient',
'rect',
'set',
'solidcolor',
'stop',
'style',
'svg',
'switch',
'symbol',
'text',
'textPath',
'title',
'tref',
'tspan',
'unknown',
'use',
'video',
'view',
'vkern',
);
$tags = apply_filters('blobmimes_svg_allowed_tags', $tags);
if (!is_array($tags) || !count($tags)) {
return array();
}
// Convert to lowercase for easier comparison.
foreach ($tags as $k=>$v) {
$tags[$k] = mb::strtolower(trim($v));
if (!strlen($tags[$k])) {
unset($tags[$k]);
}
}
// Pre-sorting will speed up looped checks.
$tags = array_unique($tags);
sort($tags);
return $tags;
} | php | {
"resource": ""
} |
q259979 | svg_base.get_allowed_protocols | test | public static function get_allowed_protocols() {
$protocols = array(
'http',
'https',
);
$protocols = apply_filters('blobmimes_svg_allowed_protocols', $protocols);
if (!is_array($protocols) || !count($protocols)) {
return array();
}
// Convert to lowercase for easier comparison.
foreach ($protocols as $k=>$v) {
$protocols[$k] = mb::strtolower(trim($v));
if (!strlen($protocols[$k])) {
unset($protocols[$k]);
}
}
// Pre-sorting will speed up looped checks.
$protocols = array_unique($protocols);
sort($protocols);
return $protocols;
} | php | {
"resource": ""
} |
q259980 | svg_base.get_allowed_domains | test | public static function get_allowed_domains() {
$domains = array(
site_url(),
'creativecommons.org',
'inkscape.org',
'sodipodi.sourceforge.net',
'w3.org',
);
$domains = apply_filters('blobmimes_svg_allowed_domains', $domains);
if (!is_array($domains) || !count($domains)) {
return array();
}
// Sanitize the list before moving on.
foreach ($domains as $k=>$domain) {
if (false === ($domains[$k] = static::sanitize_domain($domain))) {
unset($domains[$k]);
}
}
// Pre-sorting will speed up looped checks.
$domains = array_unique($domains);
sort($domains);
return $domains;
} | php | {
"resource": ""
} |
q259981 | svg_base.sanitize_domain | test | public static function sanitize_domain($domain = '') {
if (!is_string($domain)) {
return false;
}
$domain = mb::strtolower(trim($domain));
// Try to parse a full URL.
$host = wp_parse_url($domain, PHP_URL_HOST);
if (!$host) {
// Strip path?
if (false !== ($start = mb::strpos($domain, '/'))) {
$domain = mb::substr($domain, 0, $start);
}
// Strip query?
if (false !== ($start = mb::strpos($domain, '?'))) {
$domain = mb::substr($domain, 0, $start);
}
// Strip port?
if (
!filter_var($domain, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) &&
false !== ($start = mb::strpos($domain, ':'))
) {
$domain = mb::substr($domain, 0, $start);
}
// Bail if invalid characters at this point.
if (filter_var($domain, FILTER_SANITIZE_URL) !== $domain) {
return false;
}
} else {
$domain = $host;
}
if (is_string($domain)) {
$domain = preg_replace('/^www\./u', '', $domain);
}
return $domain ? $domain : false;
} | php | {
"resource": ""
} |
q259982 | svg_base.sanitize_attribute_value | test | protected static function sanitize_attribute_value($str = '') {
$str = wp_kses_no_null($str);
// Decode all entities.
$old_value = '';
while ($old_value !== $str) {
$old_value = $str;
$str = wp_kses_decode_entities($str);
$str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
// And (full) trim while we're here.
$str = preg_replace('/^\s+/u', '', $str);
$str = preg_replace('/\s+$/u', '', $str);
}
return $str;
} | php | {
"resource": ""
} |
q259983 | svg_base.sanitize_iri_value | test | protected static function sanitize_iri_value($str = '') {
$allowed_protocols = static::get_allowed_protocols();
$allowed_domains = static::get_allowed_domains();
if (wp_kses_bad_protocol($str, $allowed_protocols) !== $str) {
return '';
}
// Assign a protocol.
$str = preg_replace('/^\/\//', 'https://', $str);
// Is this a URLish thing?
if (filter_var($str, FILTER_SANITIZE_URL) !== $str) {
return '';
}
// Check the domain, if applicable.
if (preg_match('/^[\w\d]+:\/\//i', $str)) {
if (false !== ($domain = static::sanitize_domain($str))) {
if (!in_array($domain, $allowed_domains, true)) {
return '';
}
} else {
return '';
}
}
return $str;
} | php | {
"resource": ""
} |
q259984 | svg_base.callback_sanitize_css_iri | test | protected static function callback_sanitize_css_iri($match) {
$str = static::sanitize_attribute_value($match[1]);
// Strip quotes.
$str = ltrim($str, "'\"");
$str = rtrim($str, "'\"");
$str = static::sanitize_iri_value($str);
if (strlen($str)) {
return "url('$str')";
}
return 'none';
} | php | {
"resource": ""
} |
q259985 | svg_base.load_svg | test | protected static function load_svg($svg = '') {
// Early bail.
if (!is_string($svg) || !strlen($svg)) {
return false;
}
// Maybe a path?
if (
false === mb::strpos(mb::strtolower($svg), '<svg') ||
false === mb::strrpos(mb::strtolower($svg), '</svg>')
) {
try {
// @codingStandardsIgnoreStart
$svg = @file_get_contents($svg);
// @codingStandardsIgnoreEnd
if (!is_string($svg) || !strlen($svg)) {
return false;
}
} catch (\Throwable $e) {
return false;
} catch (\Exception $e) {
return false;
}
}
// Lowercase the tags.
$svg = preg_replace('/<svg/ui', '<svg', $svg);
$svg = preg_replace('/<\/svg>/ui', '</svg>', $svg);
if (
false === ($start = mb::strpos($svg, '<svg')) ||
false === ($end = mb::strrpos($svg, '</svg>'))
) {
return false;
}
$svg = mb::substr($svg, $start, ($end - $start + 6));
// Remove comments.
$svg = static::strip_comments($svg);
return $svg;
} | php | {
"resource": ""
} |
q259986 | svg_base.strip_comments | test | protected static function strip_comments($svg = '') {
if (!is_string($svg)) {
return false;
}
// Remove XML, PHP, ASP, etc.
$svg = preg_replace('/<\?(.*)\?>/Us', '', $svg);
$svg = preg_replace('/<\%(.*)\%>/Us', '', $svg);
if (
false !== mb::strpos($svg, '<?') ||
false !== mb::strpos($svg, '<%')
) {
return false;
}
// Remove comments.
$svg = preg_replace('/<!--(.*)-->/Us', '', $svg);
$svg = preg_replace('/\/\*(.*)\*\//Us', '', $svg);
if (
false !== mb::strpos($svg, '<!--') ||
false !== mb::strpos($svg, '/*')
) {
return false;
}
return $svg;
} | php | {
"resource": ""
} |
q259987 | ResourceFlagsTrait.replicateFlags | test | protected function replicateFlags($resource, $original_resource)
{
return sprintf(
'%s%s%s',
($this->checkSuppression($original_resource)) ? '@' : null,
$resource,
($this->checkRecursive($original_resource)) ? '*' : null
);
} | php | {
"resource": ""
} |
q259988 | LoaderProvider.makeLoaders | test | private function makeLoaders($options, $default_loaders)
{
$loaders = $this->preParseLoaders($options, $default_loaders);
$parsed_loaders = array();
foreach ($loaders as $loader) {
if ($loader === 'default') {
$parsed_loaders = array_merge($parsed_loaders, $default_loaders);
} else {
$parsed_loaders[] = $loader;
}
}
$parsed_loaders = array_unique($parsed_loaders);
$this->loaders = $this->makeNameSpaceLoaders($parsed_loaders, $default_loaders);
$this->extensions = $this->makeExtensions($this->loaders);
} | php | {
"resource": ""
} |
q259989 | LoaderProvider.preParseLoaders | test | private function preParseLoaders($options, $default_loaders)
{
$loaders = array();
if (is_array($options['loaders']) && !empty($options['loaders'])) {
$loaders = $options['loaders'];
} elseif (is_string($options['loaders'])) {
$loaders[] = $options['loaders'];
} else {
$loaders = $default_loaders;
}
return $loaders;
} | php | {
"resource": ""
} |
q259990 | LoaderProvider.makeNameSpaceLoaders | test | private function makeNameSpaceLoaders($loaders, $default_loaders)
{
$parsed_loaders = array();
foreach ($loaders as $loader) {
if (in_array($loader, $default_loaders)) {
$loader = sprintf('%s\%sLoader', __NAMESPACE__, ucfirst(strtolower($loader)));
}
if (!class_exists($loader)) {
throw new \InvalidArgumentException(sprintf("'%s' loader class does not exist", $loader));
}
$parsed_loaders[] = $loader;
}
return $parsed_loaders;
} | php | {
"resource": ""
} |
q259991 | Vars.parseOptions | test | private function parseOptions(array $options)
{
$parsed_options = array_merge($this->default_options, $options);
$parsed_options['loaders'] = (isset($options['loaders'])) ?
$options['loaders'] : $this->default_options['loaders'];
return $parsed_options;
} | php | {
"resource": ""
} |
q259992 | Vars.makeCache | test | private function makeCache($options, $resource)
{
$cache = new CacheProvider($resource, $options);
$this->cache = $cache;
} | php | {
"resource": ""
} |
q259993 | Vars.makePaths | test | private function makePaths($options)
{
$this->setPath($options['path']);
if (is_null($options['cache_path']) && !is_null($options['path'])) {
$this->cache->setPath($options['path']);
$this->paths_loaded = true;
}
} | php | {
"resource": ""
} |
q259994 | Vars.makeLoader | test | private function makeLoader($options)
{
$loader = new LoaderProvider($options, $this->default_options['loaders']);
$this->loader = $loader;
} | php | {
"resource": ""
} |
q259995 | Vars.makeVariables | test | private function makeVariables($options)
{
$this->variables = new VariableProvider($this);
if (isset($options['replacements'])) {
$this->variables->rstore->load($options['replacements']);
}
} | php | {
"resource": ""
} |
q259996 | Vars.loadFromCache | test | private function loadFromCache()
{
$this->cache->load();
$passed_keys = array(
'path',
'content',
'extensions',
'loaders',
'resources',
'replacements',
'globals',
);
$loaded_vars = get_object_vars($this->cache->getLoadedVars());
foreach ($loaded_vars as $key => $value) {
if (in_array($key, $passed_keys)) {
$this->$key = $value;
}
}
$this->cache->setTime($loaded_vars['cache']->getTime());
} | php | {
"resource": ""
} |
q259997 | Vars.mergeGlobals | test | private function mergeGlobals($content, $options)
{
if (array_key_exists('_globals', $content)) {
$this->globals = $content['_globals'];
if ($options['merge_globals']) {
$content = array_replace_recursive($content, $content['_globals']);
}
unset($content['_globals']);
}
return $content;
} | php | {
"resource": ""
} |
q259998 | Vars.getResource | test | public function getResource($resource)
{
foreach ($this->getResources() as $r) {
if ($resource === $r->getFilename()) {
return $r;
}
}
return false;
} | php | {
"resource": ""
} |
q259999 | VariableStore.createPrefix | test | public function createPrefix($relative)
{
if ($relative) {
$this->prefix = (empty($this->current_prefix)) ? '' : $this->current_prefix;
return;
}
$this->prefix = '';
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.