sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getPlaceholder($imagestyle_id = null, $absolute = false)
{
$placeholder = $this->getPlaceholderPath();
return $this->getUrl($placeholder, $imagestyle_id, $absolute);
} | Returns a string containing image placeholder URL
@param integer|null $imagestyle_id
@param boolean $absolute
@return string | entailment |
public function getUrl($path, $imagestyle_id = null, $absolute = false)
{
if (empty($path)) {
return $this->getPlaceholder($imagestyle_id, $absolute);
}
if (isset($imagestyle_id)) {
$suffix = preg_replace('/^image\//', '', gplcart_path_normalize($path));
$path = GC_DIR_IMAGE_CACHE . "/$imagestyle_id/$suffix";
}
return $this->url->image($path);
} | Returns a string containing the image cache URL
@param string $path
@param null|string|int $imagestyle_id
@param bool $absolute
@return string | entailment |
public function up()
{
Schema::create('cms_postmeta', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('post_id', false, true);
$table->string('meta_key');
$table->longText('meta_value')->nullable();
$table->longText('custom')->nullable();
$table->string('group')->nullable();
$table->timestamps();
$table->index(['post_id']);
$table->foreign('post_id')->references('id')->on('cms_posts')->onDelete('cascade');
});
} | Run the migrations.
@return void | entailment |
public function registeredToAdmin(array $user)
{
$store = $this->store->get($user['store_id']);
$vars = array(
'@name' => $user['name'],
'@store' => $store['name'],
'@email' => $user['email'],
'@user_id' => $user['user_id'],
'@status' => empty($user['status']) ? $this->translation->text('Inactive') : $this->translation->text('Active')
);
$subject = $this->translation->text('New account on @store', $vars);
$message = $this->translation->text("A new account has been created on @store\r\n\r\nE-mail: @email\r\nName: @name\r\nUser ID: @user_id\r\nStatus: @status", $vars);
$options = array('from' => $this->store->getConfig('email.0', $store));
return array($options['from'], $subject, $message, $options);
} | Sent to an admin when a user has been registered
@param array $user
@return array | entailment |
public function registeredToCustomer(array $user)
{
$store = $this->store->get($user['store_id']);
$options = $this->store->getConfig(null, $store);
$store_name = $this->store->getTranslation('title', $this->translation->getLangcode(), $store);
$base = $this->store->getUrl($store);
$vars = array(
'@store' => $store_name,
'@name' => $user['name'],
'@order' => "$base/account/{$user['user_id']}",
'@edit' => "$base/account/{$user['user_id']}/edit",
'@status' => empty($user['status']) ? $this->translation->text('Inactive') : $this->translation->text('Active')
);
$subject = $this->translation->text('Account details for @name on @store', $vars);
$message = $this->translation->text("Thank you for registering on @store\r\n\r\nAccount status: @status\r\n\r\nEdit account: @edit\r\nView orders: @order", $vars);
$message .= $this->getSignature($options);
$options['from'] = $this->store->getConfig('email.0', $store);
return array($user['email'], $subject, $message, $options);
} | Sent to the user when his account has been created
@param array $user
@return array | entailment |
public function resetPassword(array $user)
{
$store = $this->store->get($user['store_id']);
$options = $this->store->getConfig(null, $store);
$store_name = $this->store->getTranslation('title', $this->translation->getLangcode(), $store);
$base = $this->store->getUrl($store);
$date_format = $this->config->get('date_full_format', 'd.m.Y H:i');
$vars = array(
'@name' => $user['name'],
'@store' => $store_name,
'@expires' => date($date_format, $user['data']['reset_password']['expires']),
'@link' => "$base/forgot?" . http_build_query(array('key' => $user['data']['reset_password']['token'], 'user_id' => $user['user_id'])),
);
$subject = $this->translation->text('Password recovery for @name on @store', $vars);
$message = $this->translation->text("You or someone else requested a new password on @store\r\n\r\nTo get the password please click on the following link:\r\n@link\r\n\r\nThis link expires on @expires and nothing will happen if it's not used", $vars);
$message .= $this->getSignature($options);
$options['from'] = $this->store->getConfig('email.0', $store);
return array($user['email'], $subject, $message, $options);
} | Sent when a user wants to reset his password
@param array $user
@return array | entailment |
public function changedPassword(array $user)
{
$store = $this->store->get($user['store_id']);
$options = $this->store->getConfig(null, $store);
$store_name = $this->store->getTranslation('title', $this->translation->getLangcode(), $store);
$vars = array('@store' => $store_name, '@name' => $user['name']);
$subject = $this->translation->text('Password has been changed for @name on @store', $vars);
$message = $this->translation->text('Your password on @store has been changed', $vars);
$message .= $this->getSignature($options);
$options['from'] = $this->store->getConfig('email.0', $store);
return array($user['email'], $subject, $message, $options);
} | Sent to the user whose password has been changed
@param array $user
@return array | entailment |
public function onWidgetDetailGenerate(WidgetDetailEvent $event)
{
// Share cache directories between users if appropriate.
if ($this->settingsHelper->getShareCaches()) {
$cacheDir = $this->coreParametersHelper->getParameter(
'cached_data_dir',
$this->pathsHelper->getSystemPath('cache', true)
);
$event->setCacheDir($cacheDir, 'shared_dashboard');
}
// Override the default cache timeout for the widget if appropriate.
if ($this->settingsHelper->getCacheTTL()) {
/** @var Widget $widget */
$widget = $event->getWidget();
if ($widget) {
$defaultCacheTTL = $widget->getCacheTimeout();
if ($defaultCacheTTL < $this->settingsHelper->getCacheTTL()) {
$event->setCacheTimeout($this->settingsHelper->getCacheTTL());
}
// add date Params as clone params to keep date as unique key for cache
// since Core removes date params before generating keys
$params = $widget->getParams();
$cloneFrom = isset($params['dateFrom']) ? clone $params['dateFrom'] : new \DateTime('today midnight');
$cloneTo = isset($params['dateTo']) ? clone $params['dateTo'] : new \DateTime('tomorrow midnight - 1 second');
$params['uniqueDateKey'] = [
'fromKey' => $cloneFrom,
'toKey' => $cloneTo,
];
$widget->setParams($params);
}
}
} | Set a widget detail when needed.
@param WidgetDetailEvent $event | entailment |
public static function deserializeObject(array $arr)
{
/** @var Filter $result */
$result = parent::deserializeObject($arr);
$result->maxResults = $arr['maxResults'];
return $result;
} | @param array $arr
@return Filter | entailment |
public function getList(array $options = array())
{
$options += array('index' => 'product_bundle_id');
$result = &gplcart_static(gplcart_array_hash(array('product.bundle.list' => $options)));
if (isset($result)) {
return $result;
}
$this->hook->attach('product.bundle.list.before', $options, $result, $this);
if (isset($result)) {
return $result;
}
$conditions = array();
$sql = 'SELECT pb.*, p.store_id
FROM product_bundle pb
LEFT JOIN product p ON(pb.product_id = p.product_id)
LEFT JOIN product p2 ON(pb.item_product_id = p2.product_id)';
if (isset($options['product_bundle_id'])) {
$sql .= ' WHERE pb.product_bundle_id = ?';
$conditions[] = $options['product_bundle_id'];
} else {
$sql .= ' WHERE pb.product_bundle_id IS NOT NULL';
}
if (isset($options['store_id'])) {
$sql .= ' AND p.store_id = ? AND p2.store_id = ?';
$conditions[] = $options['store_id'];
$conditions[] = $options['store_id'];
}
if (isset($options['status'])) {
$sql .= ' AND p.status = ? AND p2.status = ?';
$conditions[] = (int) $options['status'];
$conditions[] = (int) $options['status'];
}
if (isset($options['product_id'])) {
$sql .= ' AND pb.product_id = ?';
$conditions[] = $options['product_id'];
}
if (!empty($options['limit'])) {
$sql .= ' LIMIT ' . implode(',', array_map('intval', $options['limit']));
}
$result = $this->db->fetchAll($sql, $conditions, array('index' => $options['index']));
$this->hook->attach('product.bundle.list.after', $options, $result, $this);
return $result;
} | Returns an array of bundled products
@param array $options
@return array | entailment |
public function set($product_id, array $products)
{
$this->delete(array('product_id' => $product_id));
$added = $count = 0;
foreach ($products as $product) {
$count++;
$data = array(
'product_id' => $product_id,
'item_product_id' => $product['product_id']
);
if ($this->add($data)) {
$added++;
}
}
return $count && $added == $count;
} | Delete old and add new bundled items for the product
@param int $product_id
@param array $products
@return bool | entailment |
public function getItems($product_id)
{
$product_ids = array();
foreach ($this->getList(array('product_id' => $product_id)) as $item) {
$product_ids[] = $item['item_product_id'];
}
return $product_ids;
} | Returns an array of bundled product IDs for the product
@param int $product_id
@return array | entailment |
public function outputCacheImage()
{
try {
$this->setUrlPathImage();
$this->setFileImage();
$this->setDirectoryImage();
$this->tryOutputImage();
$this->checkCacheDirectoryImage();
$this->applyActionsImage();
$this->tryOutputImage();
} catch (Exception $ex) {
$this->response->outputError404(false);
}
} | Outputs processed images | entailment |
protected function setUrlPathImage()
{
$parts = explode('files/image/cache/', urldecode(strtok($this->server->requestUri(), '?')));
if (empty($parts[1])) {
throw new OutOfRangeException('Second segment is empty in the image cache path');
}
$parts = explode('/', $parts[1]);
if (empty($parts[1])) {
throw new OutOfRangeException('Second segment is empty in the image cache path');
}
$this->data_imagestyle_id = array_shift($parts);
if ($parts[0] == 'image') {
unset($parts[0]);
}
$this->data_path = implode('/', $parts);
} | Parse the current URL path
@throws OutOfRangeException | entailment |
protected function setDirectoryImage()
{
$imagestyle_directory = GC_DIR_IMAGE_CACHE . "/$this->data_imagestyle_id";
$image_directory = pathinfo($this->data_path, PATHINFO_DIRNAME);
if (!empty($image_directory)) {
$imagestyle_directory = GC_DIR_IMAGE_CACHE . "/$this->data_imagestyle_id/$image_directory";
}
$this->data_imagestyle_directory = $imagestyle_directory;
$this->data_cached_file = "$imagestyle_directory/" . basename($this->data_path);
} | Set the current image style directory | entailment |
protected function tryOutputImage()
{
if (is_file($this->data_cached_file)) {
$this->response->addHeader('Last-Modified', gmdate('D, d M Y H:i:s T', filemtime($this->data_cached_file)))
->addHeader('Content-Length', filesize($this->data_cached_file))
->addHeader('Content-type', mime_content_type($this->data_cached_file))
->sendHeaders();
readfile($this->data_cached_file);
exit;
}
} | Try to output existing image | entailment |
protected function applyActionsImage()
{
$actions = $this->image_style->getActions($this->data_imagestyle_id);
if (empty($actions)) {
throw new RuntimeException('No image style actions to apply');
}
$this->image_style->applyActions($actions, $this->data_source_file, $this->data_cached_file);
} | Apply all defined actions to the source image
@throws RuntimeException | entailment |
public function priceRule(array &$submitted, array $options = array())
{
$this->options = $options;
$this->submitted = &$submitted;
$this->validatePriceRule();
$this->validateName();
$this->validateWeight();
$this->validateBool('status');
$this->validateUsedPriceRule();
$this->validateTriggerPriceRule();
$this->validateCurrencyPriceRule();
$this->validateValueTypePriceRule();
$this->validateCodePriceRule();
$this->validateValuePriceRule();
$this->unsetSubmitted('update');
return $this->getResult();
} | Performs full price rule validation
@param array $submitted
@param array $options
@return array|boolean | entailment |
protected function validatePriceRule()
{
$id = $this->getUpdatingId();
if ($id === false) {
return null;
}
$data = $this->price_rule->get($id);
if (empty($data)) {
$this->setErrorUnavailable('update', $this->translation->text('Price rule'));
return false;
}
$this->setUpdating($data);
return true;
} | Validates a price rule to be updated
@return boolean|null | entailment |
protected function validateValueTypePriceRule()
{
$field = 'value_type';
if ($this->isExcluded($field)) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
$types = $this->price_rule->getTypes();
if (empty($types[$value])) {
$this->setErrorInvalid($field, $this->translation->text('Value type'));
return false;
}
return true;
} | Validates a price rule value type
@return boolean|null | entailment |
protected function validateCodePriceRule()
{
$field = 'code';
$value = $this->getSubmitted($field);
if (empty($value)) {
return null;
}
$updating = $this->getUpdating();
if (isset($updating['code']) && $updating['code'] === $value) {
return true;
}
$label = $this->translation->text('Code');
if (mb_strlen($value) > 255) {
$this->setErrorLengthRange($field, $label, 0, 255);
return false;
}
$rules = $this->price_rule->getList(array('code' => $value));
if (empty($rules)) {
return true;
}
foreach ((array) $rules as $rule) {
if ($rule['code'] === $value) {
$this->setErrorExists($field, $label);
return false;
}
}
return true;
} | Validates a price rule code
@return boolean|null | entailment |
protected function validateValuePriceRule()
{
$field = 'value';
if ($this->isExcluded($field) || $this->isError('value_type')) {
return null;
}
$value = $this->getSubmitted($field);
if ($this->isUpdating() && !isset($value)) {
$this->unsetSubmitted($field);
return null;
}
if (!isset($value)) {
$this->setErrorRequired($field, $this->translation->text('Value'));
return false;
}
$updating = $this->getUpdating();
$submitted_value_type = $this->getSubmitted('value_type');
if (isset($submitted_value_type)) {
$value_type = $submitted_value_type;
} else if (isset($updating['value_type'])) {
$value_type = $updating['value_type'];
} else {
$this->setErrorUnavailable('value_type', $this->translation->text('Value type'));
return false;
}
try {
$handlers = $this->price_rule->getTypes();
return static::call($handlers, $value_type, 'validate', array($value, $this));
} catch (Exception $ex) {
$this->setError($field, $ex->getMessage());
return false;
}
} | Validates a price rule value
@return boolean|null | entailment |
public function validateValuePercentPriceRule($value)
{
$field = 'value';
$label = $this->translation->text('Value');
if (!is_numeric($value)) {
$this->setErrorNumeric($field, $label);
return false;
}
if ($value == 0 || abs($value) > 100) {
$this->setErrorInvalid($field, $label);
return false;
}
return true;
} | Validates the value of percent type
@param string $value
@return boolean | entailment |
public function validateValueFixedPriceRule($value)
{
$field = 'value';
$label = $this->translation->text('Value');
if (!is_numeric($value)) {
$this->setErrorNumeric($field, $label);
return false;
}
if (strlen($value) > 8) {
$this->setErrorInvalid($field, $label);
return false;
}
return true;
} | Validates the value of fixed type
@param string $value
@return boolean | entailment |
private function _filter()
{
$html = '';
$search = false;
foreach($this->setting['column'] as $column){
if(isset($column['filter'])){
$search = true;
$html .= '<span style="display: inline-block; margin: 2px 12px 2px 0;">'; // 不换行
$value = isset($column['filter']['value']) ? $column['filter']['value'] : '';
switch($column['filter']['type']){
case 'hidden': // 可用来做默认过滤值,替代设置里面的default
$html .= "<input type='hidden' name='_filter[{$column['name']}]' class='data-tables-submit' value='{$value}'/>";
break;
case 'input': // input值过滤,可设置默认过滤值value 及 filter的title为placeholder,默认读column的title 及 width
$width = isset($column['filter']['width']) ? 'style="width: ' . $column['filter']['width'] . 'px;"' : 'style="width: 110px;"';
$title = isset($column['filter']['title']) ? $column['filter']['title'] : $column['title'];
$html .= "{$column['title']}: <input type='text' name='_filter[{$column['name']}]' class='form-control input-sm data-tables-submit' value='{$value}' placeholder='{$title}' {$width}>";
if(isset($column['filter']['like']) && $column['filter']['like'])
$html .= " <input type='checkbox' class='data-tables-submit pointer' name='_like[{$column['name']}]' value='true' title='Whether to use fuzzy queries'/>";
break;
case 'select': // select单选值过滤,可设置value, option
// html
$class = str_replace('.', '', 'select-single-' . $column['name']); // 过滤join
$html .= "{$column['title']}: <select name='_filter[{$column['name']}]' class='data-tables-submit select-single {$class}'>";
$html .= '<option value="">- Select -</option>';
if($column['filter']['option']):
foreach ($column['filter']['option'] as $k => $v) {
if($value === $k)
$selected = 'selected';
else
$selected = '';
$html .= "<option value='{$k}' {$selected}>{$v}</option>";
}
endif;
$html .= '</select>';
// js
$filter = isset($column['filter']['filter']) && $column['filter']['filter'] ? 'true' : 'false';
$height = isset($column['filter']['height']) ? $column['filter']['height'] : '400';
$this->js .= "$('#{$this->id} .{$class}').multiselect({checkboxName: '',enableFiltering: {$filter},maxHeight: {$height}});";
break;
case 'range':
$width = isset($column['filter']['width']) ? 'style="width: ' . $column['filter']['width'] . 'px;"' : 'style="width: 70px;"';
if($value)
$range = explode('~', $value);
else
$range['0'] = $range['1'] = '';
$html .= "{$column['title']}: <input type='text' name='_filter[{$column['name']}][0]' class='form-control input-sm data-tables-submit' value='{$range['0']}' placeholder='From' {$width}>~
<input type='text' name='_filter[{$column['name']}][1]' class='form-control input-sm data-tables-submit' value='{$range['1']}' placeholder='To' {$width}>";
break;
case 'date_range':
if(isset($column['filter']['format'])){
$class = str_replace('.', '', 'date-range-' . $column['name']); // 过滤join
$this->js .= $this->_makeDateRangeJs($class, $column['filter']['format']);
}else{
$class = 'date-range-picker';
$this->js .= $this->_makeDateRangeJs($class, 'YYYY-MM-DD HH:mm');
}
$width = isset($column['filter']['width']) ? 'style="width: ' . $column['filter']['width'] . 'px;"' : 'style="width: 230px;"';
$title = isset($column['filter']['title']) ? $column['filter']['title'] : $column['title'];
$html .= "{$column['title']}: <input type='text' name='_filter[{$column['name']}]' class='form-control input-sm {$class} data-tables-submit' value='{$value}' placeholder='{$title}' {$width}>";
break;
case 'date':
if(isset($column['filter']['format'])){
$class = str_replace('.', '', 'date-time-' . $column['name']);
$this->js .= $this->_makeDateTimeJs($class, $column['filter']['format']);
}else{
$class = 'date-time-picker';
$this->js .= $this->_makeDateTimeJs($class, 'YYYY-MM-DD HH:mm');
}
$width = isset($column['filter']['width']) ? 'style="width: ' . $column['filter']['width'] . 'px;"' : 'style="width: 140px;"';
$title = isset($column['filter']['title']) ? $column['filter']['title'] : $column['title'];
$html .= "{$column['title']}: <input type='text' name='_filter[{$column['name']}]' class='form-control input-sm {$class} data-tables-submit' value='{$value}' placeholder='{$title}' {$width}>";
break;
}
$html .= '</span>';
}
}
// 其他html
if(isset($this->setting['title']) && is_string($this->setting['title']))
$html .= $this->setting['title'];
// 搜索与导出按钮
if($search)
$html .= '<button type="button" class="btn btn-primary btn-sm" style="margin-left: 12px;" onclick="dataTablesSubmit();">Search</button>';
if(isset($this->setting['export']) && $this->setting['export'])
$html .= '<button type="button" class="btn btn-info btn-sm" style="margin-left: 12px;" onclick="dataTablesSubmit(true);">Export</button>';
return $html;
} | 过滤panel的header内容 | entailment |
private function _table()
{
$columnNum = 0; // 列数
$head = '<thead><tr>';
$foot = '<tfoot><tr>';
foreach($this->setting['column'] as $column){
if(!$this->_displayColumn($column)) continue;
$columnNum++;
// 排序
if(isset($column['sort'])){
if(isset($this->sortHtml[$column['sort']]))
$sort = str_replace('%field%', $column['name'], $this->sortHtml[$column['sort']]);
else
$sort = str_replace('%field%', $column['name'], $this->sortHtml['default']);
}else
$sort = '';
// tips
$tips = isset($column['tips']) ? '<i class="glyphicon glyphicon-question-sign" data-toggle="tooltip" data-placement="top" data-original-title="'. $column['tips'] .'"></i>' : '';
$head .= '<th>' . $column['title'] . $tips . $sort . '</th>';
$foot .= '<th>' . $column['title'] . '</th>';
}
$head .= '</tr></thead>';
$foot .= '</tr></tfoot>';
$body = '<tbody id="' . $this->id . '-body" data-column="' . $columnNum . '">
<tr>
<td colspan="' . $columnNum . '">
<div class="progress progress-striped active" style=" margin:15px 50px;">
<div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%;">
</div>
</div>
</td>
</tr>
</tbody>';
// 附加html
$before = (isset($this->setting['before']) && is_string($this->setting['before'])) ? $this->setting['before'] : '';
$after = (isset($this->setting['after']) && is_string($this->setting['after'])) ? $this->setting['after'] : '';
return $before . '<div class="table-responsive"><table class="table table-striped table-hover">' . $head . $body . $foot . '</table></div>' . $after;
} | 表格头部和底部 | entailment |
public function listCart()
{
$this->actionListCart();
$this->setTitleListCart();
$this->setBreadcrumbListCart();
$this->setFilterListCart();
$this->setPagerlListCart();
$this->setData('carts', $this->getListCart());
$this->outputListCart();
} | Displays the shopping cart overview page | entailment |
protected function actionListCart()
{
list($selected, $action) = $this->getPostedAction();
$deleted = 0;
foreach ($selected as $id) {
if ($action === 'delete' && $this->access('cart_delete')) {
$deleted += (int) $this->cart->delete($id);
}
}
if ($deleted > 0) {
$message = $this->text('Deleted %num item(s)', array('%num' => $deleted));
$this->setMessage($message, 'success');
}
} | Applies an action to the selected shopping cart items | entailment |
protected function setPagerlListCart()
{
$options = $this->query_filter;
$options['count'] = true;
$total = (int) $this->cart->getList($options);
$pager = array(
'total' => $total,
'query' => $this->query_filter
);
return $this->data_limit = $this->setPager($pager);
} | Sets pager
@return array | entailment |
protected function getListCart()
{
$conditions = $this->query_filter;
$conditions['limit'] = $this->data_limit;
$list = (array) $this->cart->getList($conditions);
$this->prepareListCart($list);
return $list;
} | Returns an array of shopping cart items
@return array | entailment |
protected function prepareListCart(array &$items)
{
foreach ($items as &$item) {
$this->setItemUrlEntity($item, $this->store, 'product');
}
} | Prepare an array of cart items
@param array $items | entailment |
public function setJob($job_model)
{
if ($this->isCanceledJob($job_model)) {
return null;
}
$job_id = $this->getQuery('job_id');
if (empty($job_id)) {
return null;
}
$job = $job_model->get($job_id);
if (empty($job['status'])) {
return null;
}
$this->setJsSettings('job', $job);
if ($this->getQuery('process_job') === $job['id'] && $this->isAjax()) {
$this->outputJson($job_model->process($job));
}
return null;
} | Processes the current job
@param \gplcart\core\models\Job $job_model
@return null | entailment |
public function getWidgetJob($job_model, $job = null)
{
if (!isset($job)) {
$job = $job_model->get($this->getQuery('job_id', ''));
}
$rendered = '';
if (!empty($job['status'])) {
$job += array('widget' => 'common/job');
$rendered = $this->render($job['widget'], array('job' => $job));
}
return $rendered;
} | Returns the rendered job widget
@param \gplcart\core\models\Job $job_model
@param null|array $job
@return string | entailment |
public function isCanceledJob($job_model)
{
$cancel_job_id = $this->getQuery('cancel_job');
if (empty($cancel_job_id)) {
return false;
}
$job_model->delete($cancel_job_id);
return true;
} | Whether the current job is canceled
@param \gplcart\core\models\Job $job_model
@return boolean | entailment |
public function getChallenge()
{
if (empty($this->_challenge))
{
$output = $this->postRequest(
'identification/securitytoken/challenge',
[
'useEasyLogin' => false,
'generateEasyLoginId' => false,
'userId' => $this->_username,
]
);
if (!isset($output->links->next->uri))
throw new Exception('Cannot fetch control number. Check if the username is correct.', 10);
$this->_challenge = $output->challenge;
$this->_useOneTimePassword = (bool)$output->useOneTimePassword;
}
return $this->_challenge;
} | Fetch control number
For security token with control number and response code.
@return string|null Control number. Null if the security token only requires a generated one time code.
@throws Exception | entailment |
public function login($challengeResponse = '')
{
if (!empty($challengeResponse))
$this->setChallengeResponse($challengeResponse);
if (is_null($this->_challenge))
$this->getChallenge();
if (empty($this->_challengeResponse))
throw new UserException('One time code or response code from security token is missing.', 11);
$output = $this->postRequest('identification/securitytoken', ['response' => (string)$this->_challengeResponse,]);
if (!isset($output->links->next->uri))
{
$code = ($this->isUseOneTimePassword()) ? 'one time code' : 'response code';
$errorCode = ($this->isUseOneTimePassword()) ? 12 : 13;
throw new Exception(sprintf('Cannot sign in. Probably due to invalid or too old %s.', $code), $errorCode);
}
return true;
} | Sign in
It is a good idea to check security token type before sign in with getChallenge() and isUseOneTimePassword().
@param string $challengeResponse One time code or response code from security token
@return bool True on successful sign in
@throws Exception | entailment |
public function set($path, $create = false)
{
$zip = $this->zip;
$flag = $create ? $zip::CREATE : null;
if ($this->zip->open($path, $flag) !== true) {
throw new RuntimeException("Failed to open ZIP file $path");
}
return $this;
} | Sets a file path
@param string $path
@param bool $create
@throws RuntimeException
@return $this | entailment |
public function directory($source, $destination, $wrapper = '')
{
$files = gplcart_file_scan_recursive($source);
if (empty($files)) {
return false;
}
$this->set($destination, true);
$added = 0;
foreach ($files as $file) {
if (is_dir($file)) {
$added++;
continue;
}
$prefix = $wrapper === '' ? '' : $wrapper . DIRECTORY_SEPARATOR;
$relative = $prefix . substr($file, strlen($source) + 1);
$added += (int) $this->zip->addFile($file, $relative);
}
$result = count($files) == $added;
$this->zip->close();
return $result;
} | Zip a whole folder
@param string $source
@param string $destination
@param string $wrapper Wrapping local directory in the archive
@return boolean | entailment |
public function file($source, $destination)
{
settype($source, 'array');
$this->set($destination, true);
$added = 0;
foreach ($source as $file) {
$added += (int) $this->zip->addFile($file, basename($file));
}
$this->zip->close();
return count($source) == $added;
} | Create a ZIP archive
@param array|string $source
@param string $destination
@return bool | entailment |
public function extract($path, $files = array())
{
if (empty($files)) {
return $this->zip->extractTo($path);
}
return $this->zip->extractTo($path, $files);
} | Extract the complete archive or the given files to the specified destination
@param string $path
@param array $files
@return boolean | entailment |
public function getList()
{
$items = array();
for ($i = 0; $i < $this->zip->numFiles; $i++) {
$items[] = $this->zip->getNameIndex($i);
}
return $items;
} | Returns an array of files in the archive
@return array | entailment |
public function getMeta($file)
{
$content = file_get_contents($file);
$matches = array();
preg_match('~<!--(.*?)-->~msi', $content, $matches);
if (empty($matches[1])) {
return array();
}
$meta = json_decode(trim($matches[1]), true);
if (!is_array($meta)) {
return array();
}
$meta += array(
'title' => '',
'teaser' => '',
'weight' => 0
);
return $meta;
} | Extracts meta data from a help file
@param string $file
@return array | entailment |
public function get($file)
{
$result = null;
$this->hook->attach('help.get.before', $file, $result, $this);
if (isset($result)) {
return (array) $result;
}
$result = $this->getMeta($file);
if (empty($result)) {
return array();
}
$hash = gplcart_string_encode(gplcart_path_relative($file));
$result += array(
'file' => $file,
'path' => "admin/help/$hash"
);
$this->hook->attach('help.get.after', $file, $result, $this);
return (array) $result;
} | Returns an array of help data from the file
@param string $file
@return array | entailment |
public function getList($langcode = '')
{
if (empty($langcode)) {
$langcode = 'en';
}
$result = &gplcart_static("help.list.$langcode");
if (isset($result)) {
return $result;
}
$this->hook->attach('help.list.before', $langcode, $result, $this);
if (isset($result)) {
return $result;
}
$dir = $this->getDirectory($langcode);
if (!is_dir($dir)) {
return $result = array();
}
$result = $titles = $weights = array();
foreach (gplcart_file_scan($dir, array('md')) as $file) {
$data = $this->get($file);
if (!empty($data['title'])) {
$result[] = $data;
$titles[] = $data['title'];
$weights[] = $data['weight'];
}
}
array_multisort($weights, SORT_ASC, $titles, SORT_ASC, $result);
$this->hook->attach('help.list.after', $langcode, $result, $this);
return $result;
} | Returns an array of help items
@param string
@return array | entailment |
public function getByPattern($pattern, $langcode)
{
$prepared = strtr($pattern, array('/' => '-', '*' => '_', '/*' => '_'));
foreach (array($langcode, 'en') as $code) {
$dir = $this->getDirectory($code);
if (is_file("$dir/$prepared.php")) {
return $this->get("$dir/$prepared.php");
}
}
return array();
} | Returns a help data using a simple path pattern, e.g admin/*
@param string $pattern
@param string $langcode
@return array | entailment |
public function parse($file)
{
$result = null;
$this->hook->attach('help.render.before', $file, $result, $this);
if (isset($result)) {
return (string) $result;
}
$result = $this->markdown->render(file_get_contents($file));
$this->hook->attach('help.render.after', $file, $result, $this);
return (string) $result;
} | Render a help file
@param string $file
@return string | entailment |
public function getElements()
{
if (self::$elements === null) {
self::$elements = $this->loadJson($this->resource('OptionalElements.json'))->elements;
}
return self::$elements;
} | Get the optional html elments.
@throws \ArjanSchouten\HtmlMinifier\Exception\FileNotFoundException
@return mixed | entailment |
public static function calculateHashSecure($jumpUrl, $locationData, $mimeType)
{
$data = [(string)$jumpUrl, (string)$locationData, (string)$mimeType];
return GeneralUtility::hmac(serialize($data));
} | Calculates the hash for the given jump URL secure data.
@param string $jumpUrl The URL to the file
@param string $locationData Information about the record that rendered the jump URL, format is [pid]:[table]:[uid]
@param string $mimeType Mime type of the file or an empty string
@return string The calculated hash | entailment |
public function process(MinifyContext $context)
{
$context->setContents($this->trailingWhitespaces($context->getContents()));
$context->setContents($this->runMinificationRules($context->getContents()));
$context->setContents($this->removeSpacesAroundPlaceholders($context->getContents()));
return $context->setContents($this->maxHtmlLineLength($context->getContents(), $this->maxHtmlLineLength));
} | Minify redundant whitespaces.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
public function runMinificationRules($contents)
{
do {
$originalContents = $contents;
$contents = preg_replace(array_keys($this->minifyRules), array_values($this->minifyRules), $contents);
} while ($originalContents != $contents);
return $contents;
} | Loop over the minification rules as long as changes in output occur.
@param string $contents
@return string | entailment |
public function maxHtmlLineLength($contents, $maxHtmlLineLength)
{
if (strlen($contents) <= $maxHtmlLineLength) {
return $contents;
}
$result = '';
$splits = str_split($contents, $maxHtmlLineLength);
foreach ($splits as $split) {
$pos = strrpos($split, '><');
if ($pos === false) {
$result .= $split;
} else {
$result .= substr_replace($split, PHP_EOL, $pos + 1, 0);
}
}
return $result;
} | Old browsers, firewalls and more can't handle to long lines.
Therefore add a linebreak after specified character length.
@param int $maxHtmlLineLength
@param string $contents
@return string | entailment |
public function process($context, $url, array $configuration, ContentObjectRenderer $contentObjectRenderer, &$keepProcessing)
{
if (!$this->isEnabled($context, $configuration)) {
return $url;
}
$this->contentObjectRenderer = $contentObjectRenderer;
// Strip the absRefPrefix from the URLs.
$urlPrefix = (string)$this->getTypoScriptFrontendController()->absRefPrefix;
if ($urlPrefix !== '' && StringUtility::beginsWith($url, $urlPrefix)) {
$url = substr($url, strlen($urlPrefix));
}
// Make sure the slashes in the file URL are not encoded.
if ($context === UrlProcessorInterface::CONTEXT_FILE) {
$url = str_replace('%2F', '/', rawurlencode(rawurldecode($url)));
}
$url = $this->build($url, isset($configuration['jumpurl.']) ? $configuration['jumpurl.'] : []);
// Now add the prefix again if it was not added by a typolink call already.
if ($urlPrefix !== '' && !StringUtility::beginsWith($url, $urlPrefix)) {
$url = $urlPrefix . $url;
}
return $url;
} | Generates the JumpURL for the given parameters.
@see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::processUrlModifiers()
@param string $context The context in which the URL is generated (e.g. "typolink").
@param string $url The URL that should be processed.
@param array $configuration The link configuration.
@param \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer $contentObjectRenderer The calling content object renderer.
@param bool $keepProcessing If this is set to FALSE no further hooks will be processed after the current one.
@return string | entailment |
protected function isEnabled($context, array $configuration = [])
{
if (!empty($configuration['jumpurl.']['forceDisable'])) {
return false;
}
$enabled = !empty($configuration['jumpurl']);
// if jumpurl is explicitly set to 0 we override the global configuration
if (!$enabled && $this->getTypoScriptFrontendController()->config['config']['jumpurl_enable']) {
$enabled = !isset($configuration['jumpurl']) || $configuration['jumpurl'];
}
// If we have a mailto link and jumpurl is not explicitly enabled
// but globally disabled for mailto links we disable it
if (
empty($configuration['jumpurl']) && $context === UrlProcessorInterface::CONTEXT_MAIL
&& $this->getTypoScriptFrontendController()->config['config']['jumpurl_mailto_disable']
) {
$enabled = false;
}
return $enabled;
} | Returns TRUE if jumpurl was enabled in the global configuration
or in the given configuration
@param string $context separate check for the MAIL context needed
@param array $configuration Optional jump URL configuration
@return bool TRUE if enabled, FALSE if disabled | entailment |
protected function build($url, array $configuration)
{
$urlParameters = ['jumpurl' => $url];
// see if a secure File URL should be built
if (!empty($configuration['secure'])) {
$secureParameters = $this->getParametersForSecureFile(
$url,
isset($configuration['secure.']) ? $configuration['secure.'] : []
);
$urlParameters = array_merge($urlParameters, $secureParameters);
} else {
$urlParameters['juHash'] = JumpUrlUtility::calculateHash($url);
}
$typoLinkConfiguration = [
'parameter' => $this->getTypoLinkParameter($configuration),
'additionalParams' => GeneralUtility::implodeArrayForUrl('', $urlParameters),
// make sure jump URL is not called again
'jumpurl.' => ['forceDisable' => '1']
];
return $this->getContentObjectRenderer()->typoLink_URL($typoLinkConfiguration);
} | Builds a jump URL for the given URL
@param string $url The URL to which will be jumped
@param array $configuration Optional TypoLink configuration
@return string The generated URL | entailment |
protected function getParametersForSecureFile($jumpUrl, array $configuration)
{
$parameters = [
'juSecure' => 1,
'locationData' => $this->getTypoScriptFrontendController()->id . ':' . $this->getContentObjectRenderer()->currentRecord
];
$pathInfo = pathinfo($jumpUrl);
if (!empty($pathInfo['extension'])) {
$mimeTypes = GeneralUtility::trimExplode(',', $configuration['mimeTypes'], true);
foreach ($mimeTypes as $mimeType) {
list($fileExtension, $mimeType) = GeneralUtility::trimExplode('=', $mimeType, false, 2);
if (strtolower($pathInfo['extension']) === strtolower($fileExtension)) {
$parameters['mimeType'] = $mimeType;
break;
}
}
}
$parameters['juHash'] = JumpUrlUtility::calculateHashSecure($jumpUrl, $parameters['locationData'], $parameters['mimeType']);
return $parameters;
} | Returns a URL parameter array containing parameters for secure downloads by "jumpurl".
Helper function for filelink()
The array returned has the following structure:
juSecure => is always 1,
locationData => information about the record that created the jumpUrl,
juHash => the hash that will be checked before the file is downloadable
[mimeType => the mime type of the file]
@param string $jumpUrl The URL to jump to, basically the filepath
@param array $configuration TypoScript properties for the "jumpurl.secure" property of "filelink"
@return array URL parameters required for jumpUrl secure | entailment |
protected function getTypoLinkParameter(array $configuration)
{
$linkParameter = $this->getContentObjectRenderer()->stdWrapValue('parameter', $configuration);
if (empty($linkParameter)) {
$frontendController = $this->getTypoScriptFrontendController();
$linkParameter = $frontendController->id . ',' . $frontendController->type;
}
return $linkParameter;
} | Checks if an alternative link parameter was configured and if not
a default parameter will be generated based on the current page
ID and type.
When linking to a file this method is needed
@param array $configuration Data from the TypoLink jumpurl configuration
@return string The parameter for the jump URL TypoLink | entailment |
public function run(MinifyContext $context, $options = [])
{
$context->addMinificationStep($context->getContents(), 'Initial step');
$context = $this->placeholders($context);
$context = $this->minifiers($context, $options);
return $this->restore($context);
} | @param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@param array $options
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function placeholders(MinifyContext $context)
{
foreach ($this->placeholders as $placeholder) {
$placeholder = new $placeholder();
$context = $placeholder->process($context);
}
return $context;
} | @param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function minifiers(MinifyContext $context, $options = [])
{
foreach ($this->minifiers as $minifier) {
$minifier = new $minifier();
$provides = $minifier->provides();
if ($this->runAll($options) || $this->isOptionSet($provides, $options)) {
$context = $minifier->process($context);
$context->addMinificationStep($context->getContents(), $this->getClassName($minifier).'|'.$minifier->provides());
}
}
return $context;
} | @param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@param array $options
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function isOptionSet($provides, $options = [])
{
if (isset($options[$provides]) && $options[$provides] === true) {
return true;
} elseif (!isset($options[$provides]) && Options::options()[$provides]->isDefault()) {
return true;
}
return false;
} | Check whether an option is set in the options aray.
@param string $provides
@param array $options
@return bool | entailment |
protected function restore(MinifyContext $context)
{
$withoutPlaceholders = $context->getPlaceholderContainer()->restorePlaceholders($context->getContents());
return $context->setContents($withoutPlaceholders);
} | Restore placeholders with their original content.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
public function addPlaceholder($placeholder)
{
if (!isset(class_implements($placeholder)[PlaceholderInterface::class])) {
throw new InvalidArgumentException('The class ['.$placeholder.'] should be a member of the ['.PlaceholderInterface::class.']');
} elseif (in_array($placeholder, $this->placeholders)) {
throw new InvalidArgumentException('The placeholder ['.$placeholder.'] is already added to the minifier!');
}
$this->placeholders[] = $placeholder;
return $this->placeholders;
} | Add a placeholder strategy to the registered placeholders.
@param string $placeholder
@return \ArjanSchouten\HtmlMinifier\Placeholders\PlaceholderInterface[] | entailment |
public function addMinifier($minifier)
{
if (!isset(class_implements($minifier)[MinifierInterface::class])) {
throw new InvalidArgumentException('The class ['.$minifier.'] should be a member of the ['.MinifierInterface::class.']');
} elseif (in_array($minifier, $this->minifiers)) {
throw new InvalidArgumentException('The minifier ['.$minifier.'] is already added to the minifier!');
}
$this->minifiers[] = $minifier;
return $this->minifiers;
} | Add a placeholder strategy to the registered placeholders.
@param string $minifier
@return \ArjanSchouten\HtmlMinifier\Minifiers\MinifierInterface[] | entailment |
private function getClassName($object)
{
$class = get_class($object);
if (($index = strrpos($class, '\\'))) {
$fixForTrailingBackslash = 1;
return substr($class, $index + $fixForTrailingBackslash);
}
return $class;
} | Get the classname without the namespace.
@param $object
@return string | entailment |
public function toJson()
{
$contents = array();
foreach ($this->data as $key => $value) {
$outputKey = $this->outputKeys[$key];
$contents[] = sprintf('"%s":%s', $outputKey, $value->toJson());
}
return sprintf("{%s}", implode(",", $contents));
} | /*
========== IDataType ========== | entailment |
public function process(MinifyContext $context)
{
return $context->setContents(preg_replace_callback(
'/
<! # search for the start of a comment
[^>]* # search for everything without a ">"
> # match the end of the comment
/xs', function ($match) {
if (Str::contains(strtolower($match[0]), 'doctype')) {
return $match[0];
}
return '';
}, $context->getContents()));
} | Replace remaining comments.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
public function offsetExists($offset)
{
$offset = $this->convertOffset($offset);
$this->checkOffset($offset);
return isset($this->data[$offset]);
} | /*
========== ArrayAccess ========== | entailment |
public function process($context)
{
$contents = $context->getContents();
$contents = preg_replace_callback('/<\?=((?!\?>).)*\?>/s', function ($match) use ($context) {
return $context->getPlaceholderContainer()->createPlaceholder($match[0]);
}, $contents);
$contents = preg_replace_callback('/<\?php((?!\?>).)*(\?>)?/s', function ($match) use ($context) {
return $context->getPlaceholderContainer()->createPlaceholder($match[0]);
}, $contents);
return $context->setContents($contents);
} | Replace PHP tags with a temporary placeholder.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$this->currentFile = $phpcsFile;
$tokens = $phpcsFile->getTokens();
$type = strtolower($tokens[$stackPtr]['content']);
$errorData = array($type);
$find = PHP_CodeSniffer_Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true);
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT
) {
$phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing');
$phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'no');
return;
} else {
$phpcsFile->recordMetric($stackPtr, 'Class has doc comment', 'yes');
}
// Try and determine if this is a file comment instead of a class comment.
// We assume that if this is the first comment after the open PHP tag, then
// it is most likely a file comment instead of a class comment.
if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
$start = ($tokens[$commentEnd]['comment_opener'] - 1);
} else {
$start = $phpcsFile->findPrevious(T_COMMENT, ($commentEnd - 1), null, true);
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle');
return;
}
// Check each tag.
$this->processTags($phpcsFile, $stackPtr, $tokens[$commentEnd]['comment_opener']);
} | Processes this test, when one of its tokens is encountered.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@return void | entailment |
public function call($callback, array $parameters = [])
{
$this->_events[] = $event = new CallbackEvent($callback, $parameters);
return $event;
} | Add a new callback event to the schedule.
@param string $callback
@param array $parameters
@return Event | entailment |
public function process($context)
{
$context->setContents($this->setCDataPlaceholder($context->getContents(), $context->getPlaceholderContainer()));
return $context->setContents($this->setConditionalCommentsPlaceholder($context->getContents(), $context->getPlaceholderContainer()));
} | Replace critical content with a temp placeholder for integrity.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function setCDataPlaceholder($contents, PlaceholderContainer $placeholderContainer)
{
return preg_replace_callback('/<!\[CDATA\[((?!\]\]>).)*\]\]>/s', function ($match) use ($placeholderContainer) {
return $placeholderContainer->createPlaceholder($match[0]);
}, $contents);
} | Replace CData with a temporary placeholder.
@param string $contents
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
protected function setConditionalCommentsPlaceholder($contents, PlaceholderContainer $placeholderContainer)
{
return preg_replace_callback(
'/
(
<! # Match the start of a comment
(-{2})? # IE can understand comments without dashes
\[ # Match the start ("[" is a metachar => escape it)
(?:(?!\]>).)* # Match everything except "]>"
\]> # Match end
)
(
(?:
(?!<!\[endif\]-{2}?>)
.)*
) # Match everything except end of conditional comment
(
<!\[endif\]
(?:\2|(?=>)) # Use a trick to ensure that when dashes are captured they are...
# matched at the end! Else make sure that the next char is a ">"!
> # Match the endif with the captured dashes
)
/xis',
function ($match) use ($placeholderContainer) {
if (!empty(preg_replace('/\s*/', '', $match[3]))) {
return $placeholderContainer->createPlaceholder($match[1]).$match[3].$placeholderContainer->createPlaceholder($match[4]);
} else {
return '';
}
}, $contents);
} | Replace conditional placeholders used by Internet Explorer.
@param string $contents
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
public function addMinificationStep($input, $keyName = null)
{
if ($this->statistics === null) {
$this->statistics = new Statistics($input, $keyName);
return;
}
$this->statistics->createReferencePoint($this->placeholderContainer->getContentSize($input), $keyName);
} | Add a minification step.
@param string $input
@param string $keyName | entailment |
public function restorePlaceholders($contents)
{
foreach ($this->all() as $placeholder => $original) {
$contents = str_replace($placeholder, $original, $contents);
}
return $contents;
} | @param string $contents
@return string | entailment |
public function addPlaceholder($value, $content)
{
$placeholder = $this->createPlaceholder($value);
return str_replace($value, $placeholder, $content);
} | Replace ```$value``` with a placeholder and store it in the container.
@param string $value
@param string $content
@return string $contents | entailment |
public function createPlaceholder($value)
{
if (($key = array_search($value, $this->all()))) {
$placeholder = $key;
} else {
$placeholder = $this->createUniquePlaceholder();
}
$value = $this->removeNestedPlaceholders($value);
$this->items[$placeholder] = $value;
return $placeholder;
} | Create a unique placeholder for the given contents.
@param string $value
@return string $placeholder | entailment |
public function getContentSize($contentsWithPlaceholders)
{
$placeholderSize = $this->map(function ($value, $key) use (&$contentsWithPlaceholders){
$count = substr_count($contentsWithPlaceholders, $key);
return strlen($key) * $count - strlen($value) * $count;
})->sum();
return strlen($contentsWithPlaceholders) - $placeholderSize;
} | Calculate the byte size of the placeholders.
@param string $contentsWithPlaceholders
@return int | entailment |
protected function removeNestedPlaceholders($originalContent)
{
return preg_replace_callback('/'.Constants::PLACEHOLDER_PATTERN.'/', function ($match) {
return $this->pull($match[0]);
}, $originalContent);
} | Remove nested placeholders so no nested placholders remain in the original contents.
@param string $originalContent
@return string | entailment |
public static function newResources($credentials)
{
if ((!isset($credentials[self::USERNAME])) || (!isset($credentials[self::PASSWORD]))) {
throw new Exception('Invalid credentials');
}
$restClient = new Client($credentials[self::USERNAME], $credentials[self::PASSWORD]);
return new Resources($restClient);
} | Creates a new Resources object
Creates a new Rest Client based on the credentials
and returns a new Resources instance based on that Rest Client instance.
@param array $credentials
@return IResources
@throws Exception | entailment |
public static function options()
{
if (self::$options === null) {
self::$options = [
self::WHITESPACES => new Option(self::WHITESPACES, 'Remove redundant whitespaces', true),
self::COMMENTS => new Option(self::COMMENTS, 'Remove comments', true),
self::BOOLEAN_ATTRIBUTES => new Option(self::BOOLEAN_ATTRIBUTES, 'Collapse boolean attributes from checked="checked" to checked', true),
self::ATTRIBUTE_QUOTES => new Option(self::ATTRIBUTE_QUOTES, 'Remove quotes around html attributes', false),
self::OPTIONAL_ELEMENTS => new Option(self::OPTIONAL_ELEMENTS, 'Remove optional elements which can be implied by the browser', false),
self::REMOVE_DEFAULTS => new Option(self::REMOVE_DEFAULTS, 'Remove defaults such as from <script type=text/javascript>', false),
self::EMPTY_ATTRIBUTES => new Option(self::EMPTY_ATTRIBUTES, 'Remove empty attributes. HTML boolean attributes are skipped', false),
];
}
return self::$options;
} | Get all the options available for this minifier.
@return array | entailment |
private function createFlagDefinition($name, Reference $reference, $default)
{
return new Definition(
Flag::class,
[
(string) $name,
$reference,
(bool) $default
]
);
} | @param string $name
@param Reference $reference
@param bool $default
@return Definition | entailment |
public function process(MinifyContext $context)
{
return $context->setContents(preg_replace_callback(
'/
(\s*'.Constants::ATTRIBUTE_NAME_REGEX.'\s*) # Match the attribute name
=\s* # Match the equal sign with optional whitespaces
(["\']) # Match quotes and capture for backreferencing
\s* # Strange but possible to have a whitespace in an attribute
\2 # Backreference to the matched quote
\s*
/x',
function ($match) {
if ($this->isBooleanAttribute($match[1])) {
return Html::isLastAttribute($match[0]) ? $match[1] : $match[1].' ';
}
return Html::hasSurroundingAttributes($match[0]) ? ' ' : '';
}, $context->getContents()));
} | Execute the minification rule.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
private function isBooleanAttribute($attribute)
{
return array_search(trim($attribute), $this->repository->getAttributes()) || Html::isDataAttribute($attribute);
} | Check if an attribute is a boolean attribute.
@param string $attribute
@return bool | entailment |
public function process(MinifyContext $context)
{
return $context->setContents(preg_replace_callback(
'/
= # start matching by a equal sign
\s* # its valid to use whitespaces after the equals sign
(["\'])? # match a single or double quote and make it a capturing group for backreferencing
(
(?:(?=\1)|[^\\\\])* # normal part of "unrolling the loop". Match no quote nor escaped char
(?:\\\\\1 # match the escaped quote
(?:(?=\1)|[^\\\\])* # normal part again
)* # special part of "unrolling the loop"
) # use a the "unrolling the loop" technique to be able to skip escaped quotes like ="\""
\1? # match the same quote symbol as matched before
/x', function ($match) {
return $this->minifyAttribute($match);
}, $context->getContents()));
} | Execute the minification rule.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function minifyAttribute($match)
{
if (Str::contains($match[2], $this->prohibitedChars)) {
return $match[0];
} elseif (preg_match('/'.Constants::PLACEHOLDER_PATTERN.'/is', $match[2])) {
return $match[0];
}
return '='.$match[2];
} | Minify the attribute quotes if allowed.
@param array $match
@return string | entailment |
protected function offsetIsAllowed($offset)
{
return (is_null($offset) || (((string)(int)$offset) == $offset) || is_int($offset));
} | /*
========== MagicArray ========== | entailment |
public function toJson()
{
$contents = array();
foreach ($this->data as $value) {
$contents[] = $value->toJson();
}
return sprintf("[%s]", implode(",", $contents));
} | /*
========== IDataType ========== | entailment |
protected function processReturn(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
// Skip constructor and destructor.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
$isSpecialMethod = ($methodName === '__construct' || $methodName === '__destruct');
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error = 'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
$return = $tag;
}
}
if ($this->isInterface($phpcsFile)) {
return;
}
if ($this->isAbstractMethod($phpcsFile, $stackPtr)) {
return;
}
if ($isSpecialMethod === true) {
return;
}
if ($return !== null) {
$content = $tokens[($return + 2)]['content'];
if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) {
$error = 'Return type missing for @return tag in function comment';
$phpcsFile->addError($error, $return, 'MissingReturnType');
} elseif (!$this->functionHasReturnStatement($phpcsFile, $stackPtr)) {
$error = 'Function return type is set, but function has no return statement';
$phpcsFile->addError($error, $return, 'InvalidNoReturn');
}
} elseif ($this->functionHasReturnStatement($phpcsFile, $stackPtr)) {
$error = 'Missing @return tag in function comment.';
$phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn');
}
} | Process the return comment of this function comment.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@param int $commentStart The position in the stack where the comment started.
@return void | entailment |
protected function functionHasReturnStatement(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $continueSearch = null)
{
$tokens = $phpcsFile->getTokens();
$sFunctionToken = $tokens[$stackPtr];
$returnStatement = false;
if (isset($sFunctionToken['scope_closer']) and isset($sFunctionToken['scope_opener'])) {
$startSearch = $continueSearch !== null ? $continueSearch : $sFunctionToken['scope_opener'];
$returnStatement =
$phpcsFile->findNext(T_RETURN, $startSearch, $sFunctionToken['scope_closer'])
|| $phpcsFile->findNext(T_YIELD, $startSearch, $sFunctionToken['scope_closer']);
}
if ($returnStatement !== false) {
if ($phpcsFile->hasCondition($returnStatement, T_CLOSURE)) {
return $this->functionHasReturnStatement($phpcsFile, $stackPtr, $returnStatement+1);
} else {
return true;
}
}
return false;
} | Search if Function has a Return Statement
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@param int $continueSearch If found a return in Condition of a closure
than continue to search
@return bool | entailment |
protected function isInterface(PHP_CodeSniffer_File $phpcsFile) {
$checkFile = "". $phpcsFile->getFilename();
if (isset($this->isFileInterface[$checkFile])) {
return (bool) $this->isFileInterface[$checkFile];
}
$interface = $phpcsFile->findNext(T_INTERFACE, 0);
return $this->isFileInterface[$checkFile] = (bool)(empty($interface) == false);
} | Test if this a PHP Interface File
@param PHP_CodeSniffer_File $phpcsFile
@return bool | entailment |
public function process(MinifyContext $context)
{
$elements = (new OptionalElementsRepository())->getElements();
$contents = $context->getContents();
foreach ($elements as $element) {
$contents = $this->removeElement($element, $contents);
}
return $context->setContents($contents);
} | Execute the minification rule.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function removeElement($element, $contents)
{
$newContents = preg_replace('@'.$element->regex.'@xi', '', $contents);
if ($newContents !== $contents && isset($element->elements)) {
foreach ($element->elements as $element) {
$newContents = $this->removeElement($element, $newContents);
}
}
return $newContents;
} | Remove an optional element.
@param object $element
@param string $contents
@return string | entailment |
public function process(MinifyContext $context)
{
$contents = preg_replace_callback(
'/'.
Constants::$htmlEventNamePrefix.Constants::ATTRIBUTE_NAME_REGEX.' # Match an on{attribute}
\s*=\s* # Match equals sign with optional whitespaces around it
["\']? # Match an optional quote
\s*javascript: # Match the text "javascript:" which should be removed
/xis',
function ($match) {
return str_replace('javascript:', '', $match[0]);
}, $context->getContents());
return $context->setContents($contents);
} | Minify javascript prefixes on html event attributes.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
public function process($context)
{
$contents = $context->getContents();
$contents = $this->whitespaceBetweenInlineElements($contents, $context->getPlaceholderContainer());
$contents = $this->whitespaceInInlineElements($contents, $context->getPlaceholderContainer());
$contents = $this->replaceElementContents($contents, $context->getPlaceholderContainer());
return $context->setContents($contents);
} | Replace critical content with a temporary placeholder.
@param \ArjanSchouten\HtmlMinifier\MinifyContext $context
@return \ArjanSchouten\HtmlMinifier\MinifyContext | entailment |
protected function whitespaceBetweenInlineElements($contents, PlaceholderContainer $placeholderContainer)
{
$elementsRegex = $this->getInlineElementsRegex();
return preg_replace_callback(
'/
(
<('.$elementsRegex.') # Match the start tag and capture it
(?:(?!<\/\2>).*) # Match everything without the end tag
<\/\2> # Match the captured elements end tag
)
\s+ # Match minimal 1 whitespace between the elements
<('.$elementsRegex.') # Match the start of the next inline element
/xi',
function ($match) use ($placeholderContainer) {
// Where going to respect one space between the inline elements.
$placeholder = $placeholderContainer->createPlaceholder(' ');
return $match[1].$placeholder.'<'.$match[3];
}, $contents);
} | Whitespaces between inline html elements must be replaced with a placeholder because
a browser is showing that whitespace.
@param string $contents
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
protected function whitespaceInInlineElements($contents, PlaceholderContainer $placeholderContainer)
{
$elementsRegex = $this->getInlineElementsRegex();
return preg_replace_callback(
'/
(
<('.$elementsRegex.') # Match an inline element
(?:(?!<\/\2>).*) # Match everything except its end tag
<\/\2> # Match the end tag
\s+
)
<('.$elementsRegex.') # Match starting tag
/xis',
function ($match) use ($placeholderContainer) {
return $this->replaceWhitespacesInInlineElements($match[1], $placeholderContainer).'<'.$match[3];
}, $contents);
} | Whitespaces in an inline element have a function so we replace it.
@param string $contents
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
private function replaceWhitespacesInInlineElements($element, PlaceholderContainer $placeholderContainer)
{
return preg_replace_callback('/>\s/', function ($match) use ($placeholderContainer) {
return '>'.$placeholderContainer->createPlaceholder(' ');
}, $element);
} | Replace the whitespaces in inline elements with a placeholder.
@param string $element
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
protected function replaceElementContents($contents, PlaceholderContainer $placeholderContainer)
{
$htmlTags = implode('|', $this->htmlPlaceholderTags);
$pattern = '/
(
<(' . $htmlTags . ') # Match html start tag and capture
(?:
[^"\'>]*|"[^"]*"|\'[^\']*\'
)* # Match all attributes
> # Match end of tag
)
(
(?: # Negotiate this part
(?!<\/\2>) # Negative look ahead for the end tag
. # Match everything if not the end tag
)*+ # Possessive quantifier which will prevent backtracking
)
(<\/\2>) # Match end tag by back referencing the start tag
/xis';
return preg_replace_callback($pattern, function ($match) use ($placeholderContainer) {
return $match[1].$placeholderContainer->createPlaceholder($match[3]).$match[4];
}, $contents);
} | @param string $contents
@param \ArjanSchouten\HtmlMinifier\PlaceholderContainer $placeholderContainer
@return string | entailment |
public function getAttributes()
{
if (self::$attributes === null) {
self::$attributes = $this->loadJson($this->resource('HtmlBooleanAttributes.json'))->attributes;
}
return self::$attributes;
} | Get the html boolean attributes.
@throws \ArjanSchouten\HtmlMinifier\Exception\FileNotFoundException
@return \Illuminate\Support\Collection | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.