sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public static function toSerialize($resource) {
if (!self::isArray($resource)) {
$resource = self::toArray($resource);
}
return serialize($resource);
} | Transforms a resource into a serialized form.
@access public
@param mixed $resource
@return string
@static | entailment |
public static function toXml($resource, $root = 'root') {
if (self::isXml($resource)) {
return $resource;
}
$array = self::toArray($resource);
if (!empty($array)) {
$xml = simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><'. $root .'></'. $root .'>');
$response = self::buildXml($xml, $array);
return $response->asXML();
}
return $resource;
} | Transforms a resource into an XML document.
@access public
@param mixed $resource
@param string $root
@return string (xml)
@static | entailment |
public static function buildArray($object) {
$array = array();
foreach ($object as $key => $value) {
if (is_object($value)) {
$array[$key] = self::buildArray($value);
} else {
$array[$key] = $value;
}
}
return $array;
} | Turn an object into an array. Alternative to array_map magic.
@access public
@param object $object
@return array | entailment |
public static function buildObject($array) {
$obj = new \stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$obj->{$key} = self::buildObject($value);
} else {
$obj->{$key} = $value;
}
}
return $obj;
} | Turn an array into an object. Alternative to array_map magic.
@access public
@param array $array
@return object | entailment |
public static function buildXml(&$xml, $array) {
if (is_array($array)) {
foreach ($array as $key => $value) {
// XML_NONE
if (!is_array($value)) {
$xml->addChild($key, $value);
continue;
}
// Multiple nodes of the same name
if (isset($value[0])) {
foreach ($value as $kValue) {
if (is_array($kValue)) {
self::buildXml($xml, array($key => $kValue));
} else {
$xml->addChild($key, $kValue);
}
}
// XML_GROUP
} else if (isset($value['attributes'])) {
if (is_array($value['value'])) {
$node = $xml->addChild($key);
self::buildXml($node, $value['value']);
} else {
$node = $xml->addChild($key, $value['value']);
}
if (!empty($value['attributes'])) {
foreach ($value['attributes'] as $aKey => $aValue) {
$node->addAttribute($aKey, $aValue);
}
}
// XML_MERGE
} else if (isset($value['value'])) {
$node = $xml->addChild($key, $value['value']);
unset($value['value']);
if (!empty($value)) {
foreach ($value as $aKey => $aValue) {
if (is_array($aValue)) {
self::buildXml($node, array($aKey => $aValue));
} else {
$node->addAttribute($aKey, $aValue);
}
}
}
// XML_OVERWRITE
} else {
$node = $xml->addChild($key);
if (!empty($value)) {
foreach ($value as $aKey => $aValue) {
if (is_array($aValue)) {
self::buildXml($node, array($aKey => $aValue));
} else {
$node->addChild($aKey, $aValue);
}
}
}
}
}
}
return $xml;
} | Turn an array into an XML document. Alternative to array_map magic.
@access public
@param object $xml
@param array $array
@return object | entailment |
public static function xmlToArray($xml, $format = self::XML_GROUP) {
if (is_string($xml)) {
$xml = @simplexml_load_string($xml);
}
if (count($xml->children()) <= 0) {
return (string)$xml;
}
$array = array();
foreach ($xml->children() as $element => $node) {
$data = array();
if (!isset($array[$element])) {
$array[$element] = "";
}
if (!$node->attributes() || $format === self::XML_NONE) {
$data = self::xmlToArray($node, $format);
} else {
switch ($format) {
case self::XML_GROUP:
$data = array(
'attributes' => array(),
'value' => (string)$node
);
if (count($node->children()) > 0) {
$data['value'] = self::xmlToArray($node, $format);
}
foreach ($node->attributes() as $attr => $value) {
$data['attributes'][$attr] = (string)$value;
}
break;
case self::XML_MERGE:
case self::XML_OVERWRITE:
if ($format === self::XML_MERGE) {
if (count($node->children()) > 0) {
$data = $data + self::xmlToArray($node, $format);
} else {
$data['value'] = (string)$node;
}
}
foreach ($node->attributes() as $attr => $value) {
$data[$attr] = (string)$value;
}
break;
}
}
if (count($xml->{$element}) > 1) {
$array[$element][] = $data;
} else {
$array[$element] = $data;
}
}
return $array;
} | Convert a SimpleXML object into an array.
@access public
@param object $xml
@param int $format
@return array | entailment |
public static function utf8Encode($data) {
if (is_string($data)) {
return utf8_encode($data);
} else if (is_array($data)) {
foreach ($data as $key => $value) {
$data[utf8_encode($key)] = self::utf8Encode($value);
}
} else if (is_object($data)) {
foreach ($data as $key => $value) {
$data->{$key} = self::utf8Encode($value);
}
}
return $data;
} | Encode a resource object for UTF-8.
@access public
@param mixed $data
@return array|string
@static | entailment |
public static function utf8Decode($data) {
if (is_string($data)) {
return utf8_decode($data);
} else if (is_array($data)) {
foreach ($data as $key => $value) {
$data[utf8_decode($key)] = self::utf8Decode($value);
}
} else if (is_object($data)) {
foreach ($data as $key => $value) {
$data->{$key} = self::utf8Decode($value);
}
}
return $data;
} | Decode a resource object for UTF-8.
@access public
@param mixed $data
@return array|string
@static | entailment |
public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
/** @var \Drupal\site_commerce\SiteCommerceInterface[] $entities */
if (empty($entities)) {
return;
}
parent::buildComponents($build, $entities, $displays, $view_mode);
} | {@inheritdoc} | entailment |
protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
$defaults = parent::getBuildDefaults($entity, $view_mode);
// Don't cache site_commerces that are in 'preview' mode.
if (isset($defaults['#cache']) && isset($entity->in_preview)) {
unset($defaults['#cache']);
}
return $defaults;
} | {@inheritdoc} | entailment |
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('site_commerce.drupal7import');
$form['file'] = [
'#title' => $this->t('XLS file'),
'#type' => 'managed_file',
'#upload_location' => 'public://',
'#default_value' => $config->get('fid') ? [$config->get('fid')] : NULL,
'#upload_validators' => array(
'file_validate_extensions' => array('xls xlsx'),
),
'#required' => TRUE,
];
// Если файл был загружен.
if (!empty($config->get('fid'))) {
$file = File::load($config->get('fid'));
$created = \Drupal::service('date.formatter')->format($file->created->value, 'medium');
$form['file_information'] = [
'#markup' => $this->t('This file was uploaded at @created.', ['@created' => $created]),
];
// Кнопка импорта со своим собственным обработчиком.
$form['actions']['start_import'] = [
'#type' => 'submit',
'#value' => $this->t('Start import'),
'#submit' => ['::startImport'],
'#weight' => 100,
];
}
$form['additional_settings'] = [
'#type' => 'fieldset',
'#title' => $this->t('Additional settings'),
];
$form['additional_settings']['skip_first_line'] = [
'#type' => 'checkbox',
'#title' => $this->t('Skip first line'),
'#default_value' => $config->get('skip_first_line'),
'#description' => $this->t('If file contain titles, this checkbox help to skip first line.'),
];
$form['additional_settings']['chunk_size'] = [
'#type' => 'number',
'#title' => $this->t('Chunk size'),
'#default_value' => $config->get('chunk_size') ? $config->get('chunk_size') : 50,
'#required' => TRUE,
'#min' => 1,
];
return parent::buildForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$config = $this->config('site_commerce.drupal7import');
// Сохраняем идентификатор файла.
$fid_old = $config->get('fid');
$fid_form = $form_state->getValue('file')[0];
// Проверяет отличие текущего файла (ранее загруженного) от нового.
if (empty($fid_old) || $fid_old != $fid_form) {
// Удаляет старый файл.
if (!empty($fid_old)) {
$previous_file = File::load($fid_old);
\Drupal::service('file.usage')->delete($previous_file, 'site_commerce', 'config_form', $previous_file->id());
}
// Сохраняет новый файл.
$new_file = File::load($fid_form);
$new_file->save();
// Устанавливает принадлежность файла, чтобы предотвартить его удаление по Cron.
\Drupal::service('file.usage')->add($new_file, 'site_commerce', 'config_form', $new_file->id());
// Сохраняет информацию в конфигурацию.
$config->set('fid', $fid_form)->set('creation', time());
}
$config->set('skip_first_line', $form_state->getValue('skip_first_line'))
->set('chunk_size', $form_state->getValue('chunk_size'))
->save();
} | {@inheritdoc} | entailment |
public function startImport(array &$form, FormStateInterface $form_state) {
// Выполняет стандартную валидацию полей формы и добавляет примечания об ошибках.
ConfigFormBase::validateForm($form, $form_state);
if (!$form_state->getValue('validate_error')) {
$config = $this->config('site_commerce.drupal7import');
$fid = $config->get('fid');
$skip_first_line = $config->get('skip_first_line');
$chunk_size = $config->get('chunk_size');
if ($fid) {
$import = new SiteCommerceDrupal7BatchImport($fid, $skip_first_line, $chunk_size);
$import->setBatch();
}
}
} | {@inheritdoc}
Импорт из файла. | entailment |
public function addPaymentType($paymentType){
if(!in_array($paymentType, $this->getPaymentTypes())){
throw new SdkException('Wrong payment type');
}
$this->paymentType = $paymentType;
return $this;
} | Установить тип платежа. Из констант
@param int $paymentType
throws SdkException
@return CreateDocumentRequest | entailment |
public function addSno($sno){
if(!in_array($sno, $this->getSnoTypes())){
throw new SdkException('Wrong sno type');
}
$this->sno = $sno;
return $this;
} | Добавить SNO. Если у организации один тип - оно не обязательное. Из констант
@param string $sno
@throws SdkException
@return CreateDocumentRequest | entailment |
public function addOperationType($operationType){
if(!in_array($operationType, $this->getOperationTypes())){
throw new SdkException('Wrong operation type');
}
$this->operationType = $operationType;
$this->itemsType = (stristr($this->operationType, 'correction') !== FALSE) ? self::ITEMS_TYPE_CORRECTION : self::ITEMS_TYPE_RECEIPT;
return $this;
} | Добавить тип операции и определить наименование параметра для передачи товаров
@param string $operationType Тип операции. Из констант
@throws SdkException
@return CreateDocumentRequest | entailment |
public function form($model)
{
return $this->form->of('orchestra.settings', function (FormGrid $form) use ($model) {
$form->setup($this, 'orchestra::settings', $model);
$this->application($form);
$this->mailer($form, $model);
});
} | Form View Generator for Setting Page.
@param \Illuminate\Support\Fluent $model
@return \Orchestra\Contracts\Html\Form\Builder | entailment |
protected function application(FormGrid $form)
{
$form->fieldset(trans('orchestra/foundation::label.settings.application'), function (Fieldset $fieldset) {
$fieldset->control('input:text', 'site_name')
->label(trans('orchestra/foundation::label.name'));
$fieldset->control('textarea', 'site_description')
->label(trans('orchestra/foundation::label.description'))
->attributes(['rows' => 3]);
$fieldset->control('select', 'site_registrable')
->label(trans('orchestra/foundation::label.settings.user-registration'))
->attributes(['role' => 'agreement'])
->options([
'yes' => 'Yes',
'no' => 'No',
]);
});
} | Form view generator for application configuration.
@param \Orchestra\Contracts\Html\Form\Grid $form
@return void | entailment |
protected function mailer(FormGrid $form, $model)
{
$form->fieldset(trans('orchestra/foundation::label.settings.mail'), function (Fieldset $fieldset) use ($model) {
$fieldset->control('select', 'email_driver')
->label(trans('orchestra/foundation::label.email.driver'))
->options([
'mail' => 'Mail',
'smtp' => 'SMTP',
'sendmail' => 'Sendmail',
'ses' => 'Amazon SES',
'mailgun' => 'Mailgun',
'mandrill' => 'Mandrill',
'sparkpost' => 'SparkPost',
]);
$fieldset->control('input:text', 'email_host')
->label(trans('orchestra/foundation::label.email.host'));
$fieldset->control('input:text', 'email_port')
->label(trans('orchestra/foundation::label.email.port'));
$fieldset->control('input:text', 'email_address')
->label(trans('orchestra/foundation::label.email.from'));
$fieldset->control('input:text', 'email_username')
->label(trans('orchestra/foundation::label.email.username'));
$fieldset->control('input:password', 'email_password')
->label(trans('orchestra/foundation::label.email.password'))
->help(view('orchestra/foundation::settings._hidden', [
'value' => $model['email_password'],
'action' => 'change_password',
'field' => 'email_password',
]));
$fieldset->control('input:text', 'email_encryption')
->label(trans('orchestra/foundation::label.email.encryption'));
$fieldset->control('input:text', 'email_key')
->label(trans('orchestra/foundation::label.email.key'));
$fieldset->control('input:password', 'email_secret')
->label(trans('orchestra/foundation::label.email.secret'))
->help(view('orchestra/foundation::settings._hidden', [
'value' => $model['email_secret'],
'action' => 'change_secret',
'field' => 'email_secret',
]));
$fieldset->control('input:text', 'email_domain')
->label(trans('orchestra/foundation::label.email.domain'));
$fieldset->control('select', 'email_region')
->label(trans('orchestra/foundation::label.email.region'))
->options([
'us-east-1' => 'us-east-1',
'us-west-2' => 'us-west-2',
'eu-west-1' => 'eu-west-1',
]);
$fieldset->control('input:text', 'email_sendmail')
->label(trans('orchestra/foundation::label.email.command'));
$fieldset->control('select', 'email_queue')
->label(trans('orchestra/foundation::label.email.queue'))
->attributes(['role' => 'agreement'])
->options([
'yes' => 'Yes',
'no' => 'No',
]);
});
} | Form view generator for email configuration.
@param \Orchestra\Contracts\Html\Form\Grid $form
@param \Illuminate\Support\Fluent $model
@return void | entailment |
public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
$result = AccessResult::neutral();
return $return_as_object ? $result : $result->isAllowed();
} | {@inheritdoc} | entailment |
public function indexStatus() {
$total = $this->database->query("SELECT COUNT(*) FROM {site_kadry_steps} n WHERE n.type='education'")->fetchField();
$remaining = $this->database->query("SELECT COUNT(DISTINCT n.course_esid) FROM {site_kadry_steps} n LEFT JOIN {search_dataset} sd ON sd.sid = n.course_esid AND sd.type = :type WHERE n.type = 'education' AND sd.sid IS NULL OR sd.reindex <> 0", array(':type' => $this->getPluginId()))->fetchField();
return array('remaining' => $remaining, 'total' => $total);
} | {@inheritdoc} | entailment |
public function updateIndex() {
$limit = (int) $this->searchSettings->get('index.cron_limit');
$query = $this->database->select('site_kadry_steps', 'n');
$query->addField('n', 'course_esid');
$query->condition('n.type', 'education');
$query->leftJoin('search_dataset', 'sd', 'sd.sid = n.course_esid AND sd.type = :type', array(':type' => $this->getPluginId()));
$query->addExpression('CASE MAX(sd.reindex) WHEN NULL THEN 0 ELSE 1 END', 'ex');
$query->addExpression('MAX(sd.reindex)', 'ex2');
$query->condition(
$query->orConditionGroup()
->where('sd.sid IS NULL')
->condition('sd.reindex', 0, '<>')
);
$query->orderBy('ex', 'DESC')
->orderBy('ex2')
->orderBy('n.course_esid')
->groupBy('n.course_esid')
->range(0, $limit);
$results = $query->execute()->fetchCol();
if (!$results) {
return;
}
$databaseCourses = \Drupal::service('site_kadry_courses.database');
foreach ($results as $course_esid) {
$step = (object) $databaseCourses->loadStep($course_esid);
$this->indexStep($step);
}
} | {@inheritdoc} | entailment |
protected function indexStep($step) {
$text = '<h1>' . $step->title . '</h1> ';
$text .= $step->description . ' ';
$text = trim($text);
// Use the current default interface language.
$language = \Drupal::languageManager()->getCurrentLanguage();
// Instantiate the transliteration class.
$transliteration = \Drupal::service('transliteration');
// Use this to transliterate some text.
$text_transliterate .= $transliteration->transliterate($text, $language->getId());
$text = $text . $text_transliterate . ' ';
// Fetch extra data normally not visible.
$extra = \Drupal::moduleHandler()->invokeAll('step_update_index', [$step]);
foreach ($extra as $t) {
$text .= $t;
}
// Update index, using search index "type" equal to the plugin ID.
search_index($this->getPluginId(), $step->course_esid, $language->getId(), $text);
} | Indexes a single step.
@param $step
The step to index. | entailment |
public function table($model)
{
return $this->table->of('orchestra.users', function (TableGrid $table) use ($model) {
// attach Model and set pagination option to true
$table->with($model);
$table->sortable($this->getSortableFields());
$table->layout('orchestra/foundation::components.table');
$this->prependTableColumns($model, $table);
// Add columns
$table->column('fullname')
->label(trans('orchestra/foundation::label.users.fullname'))
->escape(false)
->value($this->getFullnameColumn());
$table->column('email')
->label(trans('orchestra/foundation::label.users.email'));
$this->appendTableColumns($model, $table);
});
} | Table View Generator for Orchestra\Model\User.
@param \Orchestra\Model\User $model
@return \Orchestra\Contracts\Html\Table\Builder | entailment |
public function actions(TableBuilder $table)
{
return $table->extend(function (TableGrid $table) {
$table->column('actions')
->label('')
->escape(false)
->headers(['class' => 'th-action'])
->attributes(function () {
return ['class' => 'th-action'];
})
->value($this->getActionsColumn());
});
} | Table actions View Generator for Orchestra\Model\User.
@param \Orchestra\Contracts\Html\Table\Builder $table
@return \Orchestra\Contracts\Html\Table\Builder | entailment |
public function form($model)
{
return $this->form->of('orchestra.users', function (FormGrid $form) use ($model) {
$form->resource($this, 'orchestra/foundation::users', $model);
$form->hidden('id');
$form->fieldset(function (Fieldset $fieldset) {
$fieldset->control('input:text', 'email')
->label(trans('orchestra/foundation::label.users.email'));
$fieldset->control('input:text', 'fullname')
->label(trans('orchestra/foundation::label.users.fullname'));
$fieldset->control('input:password', 'password')
->label(trans('orchestra/foundation::label.users.password'));
$fieldset->control('select', 'roles[]')
->label(trans('orchestra/foundation::label.users.roles'))
->attributes(['multiple' => true])
->options(function () {
$roles = app('orchestra.role');
return $roles->pluck('name', 'id');
})
->value(function ($user) {
// get all the user roles from objects
return $user->roles()->get()->pluck('id')->all();
});
});
});
} | Form View Generator for Orchestra\Model\User.
@param \Orchestra\Model\User $model
@return \Orchestra\Contracts\Html\Form\Builder | entailment |
protected function getActionsColumn()
{
return function ($row) {
$btn = [];
$btn[] = app('html')->link(
handles("orchestra::users/{$row->id}/edit"),
trans('orchestra/foundation::label.edit'),
[
'class' => 'btn btn-xs btn-label btn-warning',
'role' => 'edit',
'data-id' => $row->id,
]
);
if (! is_null($this->user) && $this->user->id !== $row->id) {
$btn[] = app('html')->link(
handles("orchestra::users/{$row->id}"),
trans('orchestra/foundation::label.delete'),
[
'class' => 'btn btn-xs btn-label btn-danger',
'role' => 'delete',
'data-id' => $row->id,
'data-method' => 'DELETE',
]
);
}
return app('html')->create(
'div',
app('html')->raw(implode('', $btn)),
['class' => 'btn-group']
);
};
} | Get actions column for table builder.
@return callable | entailment |
protected function getFullnameColumn()
{
return function ($row) {
$roles = $row->roles;
$value = [];
foreach ($roles as $role) {
$value[] = app('html')->create('span', e($role->name), [
'class' => 'label label-info',
'role' => 'role',
]);
}
return implode('', [
app('html')->create('strong', e($row->fullname)),
app('html')->create('br'),
app('html')->create('span', app('html')->raw(implode(' ', $value)), [
'class' => 'meta',
]),
]);
};
} | Get fullname column for table builder.
@return callable | entailment |
public function viewElements(FieldItemListInterface $items, $langcode) {
// Формирует идентификатор позиции из текущего пути.
$url = \Drupal\Core\Url::fromRoute('<current>');
$path = $url->getInternalPath();
$pid = (int) substr($path, 14);
$elements['data'] = array(
'#create_placeholder' => TRUE,
'#lazy_builder' => ['site_commerce.lazy_builders:parametrsBlock', [$pid]],
);
return $elements;
} | {@inheritdoc} | entailment |
public function getTags()
{
return \is_string($value = $this->getContentValue('tags', null))
? array_unique(array_filter(explode(',', $value)))
: null;
} | Возвращает массив тегов.
@return null|string[] | entailment |
public function getParameters() {
$filledvars = array();
foreach (get_object_vars($this) as $name => $value) {
if ($value) {
$filledvars[$name] = (string)$value;
}
}
return $filledvars;
} | Получить параметры, сгенерированные командой
@return array | entailment |
protected function getEntityIds() {
$query = $this->getStorage()->getQuery()
->sort($this->entityType->getKey('id'), 'DESC');
$this->limit = 1000;
if ($this->limit) {
$query->pager($this->limit);
}
return $query->execute();
} | Loads entity IDs using a pager sorted by the entity id.
@return array
An array of entity IDs. | entailment |
protected function getDefaultOperations(EntityInterface $entity) {
$operations = [];
if ($entity->access('update') && $entity->hasLinkTemplate('edit-form')) {
$operations['edit'] = [
'title' => $this->t('Edit'),
'weight' => 10,
'url' => $entity->urlInfo('edit-form'),
];
}
if ($entity->access('delete') && $entity->hasLinkTemplate('delete-form')) {
$operations['delete'] = [
'title' => $this->t('Delete'),
'weight' => 100,
'url' => $entity->urlInfo('delete-form'),
];
}
return $operations;
} | Gets this list's default operations.
@param \Drupal\Core\Entity\EntityInterface $entity
The entity the operations are for.
@return array
The array structure is identical to the return value of
self::getOperations(). | entailment |
public function store(PasswordResetLink $listener, array $input)
{
$validation = $this->validator->with($input);
if ($validation->fails()) {
return $listener->resetLinkFailedValidation($validation->getMessageBag());
}
$response = $this->password->sendResetLink(['email' => $input['email']]);
if ($response != Password::RESET_LINK_SENT) {
return $listener->resetLinkFailed($response);
}
return $listener->resetLinkSent($response);
} | Request to reset password.
@param \Orchestra\Contracts\Auth\Listener\PasswordResetLink $listener
@param array $input
@return mixed | entailment |
public function update(PasswordReset $listener, array $input)
{
$response = $this->password->reset($input, function (Eloquent $user, $password) {
// Save the new password and login the user.
$user->setAttribute('password', $password);
$user->save();
Auth::login($user);
});
$errors = [
Password::INVALID_PASSWORD,
Password::INVALID_TOKEN,
Password::INVALID_USER,
];
if (\in_array($response, $errors)) {
return $listener->passwordResetHasFailed($response);
}
return $listener->passwordHasReset($response);
} | Reset the password.
@param \Orchestra\Contracts\Auth\Listener\PasswordReset $listener
@param array $input
@return mixed | entailment |
public function routeNotificationFor($driver)
{
if (\method_exists($this, $method = 'routeNotificationFor'.Str::studly($driver))) {
return $this->{$method}();
}
switch ($driver) {
case 'database':
return $this->notifications();
case 'mail':
return $this->getRecipientEmail();
case 'nexmo':
return $this->getAttribute('phone_number');
}
} | Get the notification routing information for the given driver.
@param string $driver
@return mixed | entailment |
protected function queueToPublisher(Fluent $extension)
{
Publisher::queue($extension->get('name'));
return $this->redirect(handles('orchestra::publisher'));
} | Queue publishing asset to publisher.
@param \Illuminate\Support\Fluent $extension
@return mixed | entailment |
public function priceEditor($method, $tid, $pid, $group, $prefix = "", $from = "0.00", $value = "0.00", $unit = "", $currency = "руб.", $suffix = "") {
if ($method == 'ajax') {
// Create AJAX Response object.
$response = new AjaxResponse();
$units = array_flip(getUnitMeasurement());
$data = array(
'pid' => $pid,
'from' => $from,
'value' => $value,
'unit' => $units[$unit],
);
$this->databaseSiteCommerce->priceEditorUpdate($data);
// Изменяем цвет строки.
$selector = '#product-' . $pid;
$css = array(
'background-color' => 'rgb(184, 220, 255)',
);
$response->addCommand(new CssCommand($selector, $css));
// Очищает cache.
Cache::invalidateTags(['taxonomy_term:' . $tid]);
Cache::invalidateTags(['site_commerce::' . $pid]);
// Return ajax response.
return $response;
}
} | Регистрирует изменение стоимости позиции.
@param [type] $method
@param [type] $pid
@param [type] $cost_group
@param [type] $cost_prefix
@param [type] $cost_from
@param [type] $cost_value
@param [type] $cost_currency
@param [type] $cost_suffix
@return ajax response | entailment |
public function positionsSetWeight($method, $tid, $pids) {
if ($method == 'ajax') {
// Create AJAX Response object.
$response = new AjaxResponse();
$pids = explode("&pid=", $pids);
unset($pids[0]);
$weight = 1;
foreach ($pids as $pid) {
//$response->addCommand(new AlertCommand("Категория: " . $tid . "; Позиция: " . $pid . "; Номер: " . $weight));
$data = array(
'pid' => $pid,
'weight' => $weight,
);
$this->databaseSiteCommerce->positionSetWeight($data);
$weight++;
}
// Очищает cache.
Cache::invalidateTags(['taxonomy_term:' . $tid]);
// Return ajax response.
return $response;
}
} | Регистрирует вес позиций в категории.
@param [string] $method
@param [int] $cid
@param [string] $pids
@return ajax response
@access public | entailment |
public function handle(Application $app, Kernel $kernel)
{
if (! $app->routesAreCached()) {
return;
}
$app->terminating(function () use ($kernel) {
$kernel->call('route:cache');
});
} | Execute the job.
@param \Illuminate\Contracts\Foundation\Application $app
@param \Illuminate\Contracts\Console\Kernel $kernel
@return void | entailment |
public function apiRequest($http_method, $api_path, $data = null, $headers = null, $test_response = null)
{
$data = \is_array($data)
? $data
: [];
$headers = \is_array($headers)
? $headers
: [];
$uri = $this->getApiRequestUri($api_path);
try {
// Временная метка начала осуществления запроса
$now = microtime(true);
// Если в метод был передан объект-ответ, который надо использовать как ответ от B2B API - то используем его
if ($test_response instanceof ResponseInterface) {
$this->httpClient()->fire('before_request', $http_method, $uri, $data, $headers);
$response = clone $test_response;
$this->httpClient()->fire('after_request', $response);
} else {
$response = $this->http_client->request($http_method, $uri, $data, $headers);
}
// Считаем время исполнения запроса (в секундах с дробной частью)
$duration = \round(microtime(true) - $now, 4);
// Это условие, в основном, сделано для тестов
if ($test_response instanceof ResponseInterface && (($code = $test_response->getStatusCode()) >= 400)) {
throw new RequestException(
sprintf('Wrong response code: %d', $code),
new Request($http_method, $uri),
$test_response
);
}
$response_array = \json_decode($content = $response->getBody()->getContents(), true);
if (\json_last_error() === JSON_ERROR_NONE) {
return \array_replace($response_array, [
// Добавляем время исполнения запроса в ответ
B2BApiResponseInterface::REQUEST_DURATION_KEY_NAME => $duration,
]);
}
throw new B2BApiException(sprintf('Invalid JSON string received: "%s"', $content));
} catch (RequestException $e) {
$response = $e->getResponse();
$request = $e->getRequest();
$request_data = \json_encode($data, JSON_UNESCAPED_UNICODE);
$code = $e->getCode();
$response_content = null;
if ($response instanceof ResponseInterface) {
$body = $response->getBody();
$uri = $request->getUri();
$code = $response->getStatusCode();
$response_content = \str_replace(["\n", "\r", "\t"], '', $body->read((int) $body->getSize()));
}
throw new B2BApiException(sprintf(
'Request to the B2B API (path: \'%s\', data: \'%s\') failed with message: "%s"',
$uri,
$request_data,
$response_content
), $code, $e);
} catch (Exception $e) {
throw new B2BApiException(
"Request to the B2B API failed with message: \"{$e->getMessage()}\"", $e->getCode(), $e
);
}
} | {@inheritdoc} | entailment |
protected function getApiRequestUri($api_path)
{
static $base_uri = null;
if (empty($base_uri)) {
// Инициализируем базовый URI
$base_uri = rtrim(
$this->getConfigValue("api.versions.{$this->getConfigValue('use_api_version')}.base_uri"),
'\\/ '
);
}
return $base_uri . '/' . ltrim((string) $api_path, '\\/ ');
} | Возвращает абсолютный HTTP путь к методу API.
@param string $api_path
@return string | entailment |
private function checkType($oldType, $newType, NodePath $nodePath) : string
{
if (!is_null($oldType) && ($newType !== $oldType) && ($newType !== 'null') && ($oldType !== 'null')) {
throw new JsonParserException(
"Data in '$nodePath' contains incompatible data types '$oldType' and '$newType'."
);
}
return $newType;
} | Check that two types same or compatible.
@param $oldType
@param $newType
@param NodePath $nodePath
@return string
@throws JsonParserException | entailment |
public function executeAndRedirect(Listener $listener)
{
$this->publisher->connected() && $this->publisher->execute();
return $listener->publishingHasSucceed();
} | Run publishing if possible.
@param \Orchestra\Contracts\Foundation\Listener\AssetPublishing $listener
@return mixed | entailment |
protected function getExtension($vendor, $package = null)
{
$name = (is_null($package) ? $vendor : implode('/', [$vendor, $package]));
return new Fluent(['name' => $name, 'uid' => $name]);
} | Get extension information.
@param string $vendor
@param string|null $package
@return \Illuminate\Support\Fluent | entailment |
public function bootstrap(Application $app)
{
$app->make('orchestra.memory')->extend('user', function ($app, $name) {
return new UserProvider(
new UserRepository($name, [], $app)
);
});
} | Bootstrap the given application.
@param \Illuminate\Contracts\Foundation\Application $app
@return void | entailment |
public function login(Listener $listener, array $input, ThrottlesCommand $throttles = null)
{
$validation = $this->validator->on('login')->with($input);
// Validate user login, if any errors is found redirect it back to
// login page with the errors.
if ($validation->fails()) {
return $listener->userLoginHasFailedValidation($validation->getMessageBag());
}
if ($this->hasTooManyAttempts($throttles)) {
return $this->handleUserHasTooManyAttempts($listener, $input, $throttles);
}
if ($this->authenticate($input)) {
return $this->handleUserWasAuthenticated($listener, $input, $throttles);
}
return $this->handleUserFailedAuthentication($listener, $input, $throttles);
} | Login a user.
@param \Orchestra\Contracts\Auth\Listener\AuthenticateUser $listener
@param array $input
@param \Orchestra\Contracts\Auth\Command\ThrottlesLogins|null $throttles
@return mixed | entailment |
protected function authenticate(array $input)
{
$remember = (($input['remember'] ?? 'no') === 'yes');
$data = Arr::except($input, ['remember']);
// We should now attempt to login the user using Auth class. If this
// failed simply return false.
return $this->auth->attempt($data, $remember);
} | Authenticate the user.
@param array $input
@return bool | entailment |
protected function handleUserWasAuthenticated(Listener $listener, array $input, ThrottlesCommand $throttles = null)
{
if ($throttles) {
$throttles->clearLoginAttempts();
}
return $listener->userHasLoggedIn($this->verifyWhenFirstTimeLogin($this->getUser()));
} | Send the response after the user was authenticated.
@param \Orchestra\Contracts\Auth\Listener\AuthenticateUser $listener
@param array $input
@param \Orchestra\Contracts\Auth\Command\ThrottlesLogins|null $throttles
@return mixed | entailment |
protected function handleUserHasTooManyAttempts(Listener $listener, array $input, ThrottlesCommand $throttles = null)
{
$throttles->incrementLoginAttempts();
$throttles->fireLockoutEvent();
return $listener->sendLockoutResponse($input, $throttles->getSecondsBeforeNextAttempts());
} | Send the response after the user has too many attempts.
@param \Orchestra\Contracts\Auth\Listener\AuthenticateUser $listener
@param array $input
@param \Orchestra\Contracts\Auth\Command\ThrottlesLogins|null $throttles
@return mixed | entailment |
protected function handleUserFailedAuthentication(Listener $listener, array $input, ThrottlesCommand $throttles = null)
{
if ($throttles) {
$throttles->incrementLoginAttempts();
}
return $listener->userLoginHasFailedAuthentication($input);
} | Send the response after the user failed authentication.
@param \Orchestra\Contracts\Auth\Listener\AuthenticateUser $listener
@param array $input
@param \Orchestra\Contracts\Auth\Command\ThrottlesLogins|null $throttles
@return mixed | entailment |
protected function verifyWhenFirstTimeLogin(Eloquent $user)
{
if ((int) $user->getAttribute('status') === Eloquent::UNVERIFIED) {
$user->activate()->save();
}
return $user;
} | Verify user account if has not been verified, other this should
be ignored in most cases.
@param \Orchestra\Model\User $user
@return \Orchestra\Model\User | entailment |
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('site_commerce.import');
$form['paths'] = array(
'#type' => 'fieldset',
'#title' => $this->t('Settings of file paths'),
);
// Путь до файла импорта с категориями каталога.
$form['paths']['file_catalog_path'] = array(
'#type' => 'textfield',
'#title' => $this->t('Path of catalog file'),
'#default_value' => $config->get('file_catalog_path') ? $config->get('file_catalog_path') : "",
);
$queue = \Drupal::queue('site_commerce_catalog_import');
if ($number_of_items = $queue->numberOfItems()) {
$form['paths']['info_text_catalog_import'] = [
'#type' => 'markup',
'#markup' => new FormattableMarkup('In the queue for processing: @number.', [
'@number' => $number_of_items,
]),
];
}
// Путь до файла импорта с товарами.
$form['paths']['file_products_path'] = array(
'#type' => 'textfield',
'#title' => $this->t('Path of products file'),
'#default_value' => $config->get('file_products_path') ? $config->get('file_products_path') : "",
);
$queue = \Drupal::queue('site_commerce_products_import');
if ($number_of_items = $queue->numberOfItems()) {
$form['paths']['info_text_products_import'] = [
'#type' => 'markup',
'#markup' => new FormattableMarkup('In the queue for processing: @number.', [
'@number' => $number_of_items,
]),
];
}
return parent::buildForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function getResponse()
{
if ($this->response === null and $this->isExecuted()) {
$this->response = Response::forge($this);
}
return $this->response;
} | Get the response.
@return Response | entailment |
public function setOption($option, $value = null)
{
if (is_array($option)) { // If it's an array, loop through each option and call this method recursively.
foreach ($option as $opt => $val) {
$this->setOption($opt, $val);
}
return;
}
if (array_key_exists($option, $this->defaults)) { // If it is a default value.
throw new ProtectedOptionException(sprintf('Unable to set protected option #%u', $option));
}
if (curl_setopt($this->handle, $option, $value) === false) {
throw new CurlErrorException(sprintf('Couldn\'t set option #%u', $option));
}
} | Set an option for the request.
@param mixed $option
@param mixed $value null
@return RequestInterface | entailment |
public function execute()
{
$this->content = curl_exec($this->handle);
// If the execution wasn't successful, throw an exception.
if ($this->isSuccessful() === false) {
throw new CurlErrorException($this->getErrorMessage());
}
$this->executed = true;
} | Execute the request.
@return void | entailment |
public function register()
{
$this->app->singleton('javascript', function ($app) {
return new ScriptVariables();
});
$this->app->alias('javascript', ScriptVariables::class);
} | Register the service provider.
@return void | entailment |
public function viewElements(FieldItemListInterface $items, $langcode)
{
$elements = [];
foreach ($items as $delta => $item) {
$elements['data'] = [
'#theme' => 'site_commerce_quantity_default_formatter',
'#visible' => $item->visible,
'#unit' => $item->unit,
'#min' => $item->min,
'#stock' => $item->stock,
];
}
return $elements;
} | {@inheritdoc} | entailment |
protected function attachAccessPolicyEvents(Application $app)
{
// Orchestra Platform should be able to watch any changes to Role model
// and sync the information to "orchestra.acl".
Role::observe($app->make(RoleObserver::class));
// Orchestra Platform should be able to determine admin and member roles
// dynamically.
Role::setDefaultRoles(\config('orchestra/foundation::roles'));
} | Attach access policy events.
@param \Illuminate\Contracts\Foundation\Application $app
@return void | entailment |
public function buildForm(array $form, FormStateInterface $form_state) {
// Rebuild the form.
$form_state->setRebuild();
// The combination of having user input and rebuilding the form means
// that it will attempt to cache the form state which will fail if it is
// a GET request.
$form_state->setRequestMethod('POST');
/** @var \Drupal\site_commerce\Entity\SiteCommerceInterface $site_commerce */
$site_commerce = $this->entity;
// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = array(
'#type' => 'hidden',
'#default_value' => $site_commerce->getChangedTime(),
);
$form['advanced'] = array(
'#type' => 'vertical_tabs',
'#attributes' => array('class' => array('entity-meta')),
'#weight' => 99,
);
/* @var $entity \Drupal\site_commerce\Entity\SiteCommerce */
$form = parent::buildForm($form, $form_state);
// Node author information for administrators.
$form['author'] = array(
'#type' => 'details',
'#title' => t('Authoring information'),
'#group' => 'advanced',
'#attributes' => array(
'class' => array('node-form-author'),
),
'#attached' => array(
'library' => array('node/drupal.node'),
),
'#weight' => 90,
'#optional' => TRUE,
);
if (isset($form['uid'])) {
$form['uid']['#group'] = 'author';
}
if (isset($form['created'])) {
$form['created']['#group'] = 'author';
}
$form['#attached']['library'][] = 'node/form';
return $form;
} | {@inheritdoc} | entailment |
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = [];
$element['target_id'] = array(
'#type' => 'number',
'#title' => $this->t('ID of product'),
'#default_value' => isset($items[$delta]->target_id) ? $items[$delta]->target_id : NULL,
'#step' => '1',
'#min' => '0',
);
$element['name'] = array(
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#default_value' => isset($items[$delta]->name) ? $items[$delta]->name : NULL,
'#empty_value' => '',
'#maxlength' => 255,
);
$element['min'] = array(
'#type' => 'number',
'#title' => $this->t('Minimum order quantity'),
'#default_value' => isset($items[$delta]->min) ? $items[$delta]->min : 1,
'#empty_value' => '1',
'#step' => '1',
'#min' => '0',
'#theme_wrappers' => [],
);
$element['unit'] = array(
'#type' => 'select',
'#title' => $this->t('Unit of quantity'),
'#options' => getUnitMeasurement(),
'#default_value' => isset($items[$delta]->unit) ? $items[$delta]->unit : NULL,
'#theme_wrappers' => [],
);
$element['cost'] = array(
'#type' => 'number',
'#title' => $this->t('Price'),
'#default_value' => isset($items[$delta]->cost) ? $items[$delta]->cost : 0,
'#empty_value' => '',
'#step' => '0.01',
'#min' => '0',
'#theme_wrappers' => [],
);
$element['currency'] = array(
'#type' => 'select',
'#title' => $this->t('Currency'),
'#options' => getCurrency(),
'#default_value' => isset($items[$delta]->currency) ? $items[$delta]->currency : NULL,
'#theme_wrappers' => [],
);
$element['select'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Allow select'),
'#default_value' => isset($items[$delta]->select) ? $items[$delta]->select : NULL,
'#empty_value' => '',
'#theme_wrappers' => [],
);
$element['description'] = array(
'#type' => 'textarea',
'#title' => $this->t('Description'),
'#default_value' => isset($items[$delta]->description) ? $items[$delta]->description : NULL,
'#empty_value' => '',
);
$element['#theme'] = 'site_commerce_parametrs_default_widget';
return $element;
} | {@inheritdoc} | entailment |
public function route(string $name, string $default = '/')
{
if (\in_array($name, ['orchestra', 'orchestra/foundation'])) {
$name = 'orchestra';
}
return parent::route($name, $default);
} | Get extension route.
@param string $name
@param string $default
@return \Orchestra\Contracts\Extension\UrlGenerator | entailment |
protected function generateRouteByName(string $name, string $default)
{
// Orchestra Platform routing is managed by `orchestra/foundation::handles`
// and can be manage using configuration.
if (\in_array($name, ['orchestra'])) {
$url = Config::get('orchestra/foundation::handles', $default);
return $this->app->make('orchestra.extension.url')->handle(
\is_string($url) ? $url : 'admin'
);
}
return parent::generateRouteByName($name, $default);
} | {@inheritdoc} | entailment |
public static function delete($urls, $data = null, callable $callback = null)
{
return static::make('delete', $urls, $data, $callback);
} | Make one or multiple DELETE requests.
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | entailment |
public static function get($urls, $data = null, callable $callback = null)
{
return static::make('get', $urls, $data, $callback);
} | Make one or multiple GET requests.
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | entailment |
public static function post($urls, $data = null, callable $callback = null)
{
return static::make('post', $urls, $data, $callback);
} | Make one or multiple POST requests.
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | entailment |
public static function put($urls, $data = null, callable $callback = null)
{
return static::make('put', $urls, $data, $callback);
} | Make one or multiple PUT requests.
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | entailment |
protected static function make($verb, $urls, $data, callable $callback = null)
{
if (!is_array($urls)) {
$urls = [$urls => $data];
} elseif (!(bool)count(array_filter(array_keys($urls), 'is_string'))) {
foreach ($urls as $key => $url) {
$urls[$url] = null;
unset($urls[$key]);
}
}
$dispatcher = new Dispatcher;
$requests = [];
$dataStore = [];
foreach ($urls as $url => $data) {
$requests[] = new Request($url);
$dataStore[] = $data;
}
new static($verb, $dispatcher, $requests, $dataStore, $callback);
$requests = $dispatcher->all();
$responses = [];
foreach ($requests as $request) {
$responses[] = $request->getResponse();
}
return $responses;
} | Make one or multiple requests.
@param string $verb
@param mixed $urls
@param mixed $data
@param callable $callback
@return array | entailment |
protected function makeRequest(callable $callback = null)
{
// Foreach request:
foreach ($this->requests as $key => $request) {
$data = (isset($this->data[$key]) and $this->data[$key] !== null) ? $this->data[$key] : null;
// Follow any 3xx HTTP status code.
$request->setOption(CURLOPT_FOLLOWLOCATION, true);
switch ($this->verb) {
case 'DELETE':
$this->prepareDeleteRequest($request);
break;
case 'GET':
$this->prepareGetRequest($request);
break;
case 'POST':
$this->preparePostRequest($request, $data);
break;
case 'PUT':
$this->preparePutRequest($request, $data);
break;
}
// Add the request to the dispatcher.
$this->dispatcher->add($request);
}
// Execute the request(s).
if ($callback !== null) {
$this->dispatcher->execute($callback);
} else {
$this->dispatcher->execute();
}
} | Prepares and sends HTTP requests.
@param callable $callback | entailment |
protected function preparePostRequest(RequestInterface $request, $data)
{
if ($data !== null) {
// Add the POST data to the request.
$request->setOption(CURLOPT_POST, true);
$request->setOption(CURLOPT_POSTFIELDS, $data);
} else {
$request->setOption(CURLOPT_CUSTOMREQUEST, 'POST');
}
} | Sets a request's HTTP verb to POST.
@param RequestInterface $request | entailment |
protected function preparePutRequest(RequestInterface $request, $data)
{
$request->setOption(CURLOPT_CUSTOMREQUEST, 'PUT');
if ($data !== null) {
$request->setOption(CURLOPT_POSTFIELDS, $data);
}
} | Sets a request's HTTP verb to PUT.
@param RequestInterface $request | entailment |
protected function getUniqueLoginKey()
{
$key = $this->request->input($this->loginKey);
$ip = $this->request->ip();
return \mb_strtolower($key).$ip;
} | Get the login key.
@return string | entailment |
public function buildForm(array $form, FormStateInterface $form_state, $gid = 0) {
$this->gid = (int) $gid;
if ($this->gid) {
$this->group = $this->database->characteristicsReadGroup($this->gid);
}
return parent::buildForm($form, $form_state);
} | {@inheritdoc} | entailment |
public function getQuestion() {
return $this->t('Are you sure you want to delete «@title»?', ['@title' => $this->group->title]);
} | {@inheritdoc} | entailment |
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->database->characteristicsDeleteGroup($this->group->gid);
// Очищает cache.
Cache::invalidateTags(['site-commerce-characteristics']);
drupal_set_message($this->t('The object <b>@title</b> was successfully deleted.', ['@title' => $this->group->title]));
$form_state->setRedirect('site_commerce.characteristics_editor');
} | {@inheritdoc} | entailment |
public function toMail($notifiable)
{
$password = $this->password;
$message = new MailMessage();
$message->viewData = [
'email' => $email = $notifiable->getRecipientEmail(),
'fullname' => $notifiable->getRecipientName(),
];
$message->title(\trans('orchestra/foundation::email.register.title'))
->line(\trans('orchestra/foundation::email.register.message.intro'))
->line(\trans('orchestra/foundation::email.register.message.email', \compact('email')));
if (! \is_null($this->password)) {
$message->line(\trans('orchestra/foundation::email.register.message.password', \compact('password')));
}
return $message;
} | Get the notification message for mail.
@param mixed $notifiable
@return \Orchestra\Notifications\Messages\MailMessage | entailment |
public function getSuggestGet()
{
return ! empty($value = $this->getContentValue('suggest_get', null))
? $this->convertToCarbon($value)
: null;
} | Возвращает ориентировочные дату/время, когда отчет будет готов.
@return Carbon|null | entailment |
public function upload(string $name): bool
{
$app = $this->getContainer();
$config = $this->destination($name, $recursively);
try {
$basePath = "{$config->basePath}{$name}/";
$this->changePermission(
$config->workingPath, 0777, $config->recursively
);
$this->prepareDirectory($basePath, 0777);
} catch (RuntimeException $e) {
// We found an exception with Filesystem, but it would be hard to say
// extension can't be activated, let's try activating the
// extension and if it failed, we should actually catching
// those exception instead.
}
$app['orchestra.extension']->activate($name);
$this->changePermission($config->workingPath, 0755, $config->recursively);
return true;
} | Upload the file.
@param string $name
@return bool | entailment |
public function ping()
{
return new B2BResponse($this->client->apiRequest(
'get',
'dev/ping',
[
'value' => $test_value = 'pong',
],
[],
$this->client->isTest() ? new Response(
200, $this->getTestingResponseHeaders(), \json_encode([
'value' => $test_value,
'in' => 0,
'out' => $ts = Carbon::now()->addSeconds(mt_rand(0, 1))->getTimestamp(),
'delay' => $ts + mt_rand(0, 2),
])) : null
));
} | Проверка соединения.
@throws B2BApiException
@return B2BResponse | entailment |
public function token($username, $password, $is_hash = false, $date_from = null, $age = 60)
{
if (\is_string($username) && ! empty($username)) {
if (\is_string($password) && ! empty($password)) {
// Типизируем значения
$date_from = $date_from === null ? Carbon::now() : $this->convertToCarbon($date_from);
$is_hash = boolval($is_hash);
$age = intval($age, 10);
if (! ($date_from instanceof Carbon)) {
throw new B2BApiException('Cannot convert passed date to Carbon object');
}
if ($age <= 1) {
throw new B2BApiException('Age cannot be less then 1 second');
}
return new B2BResponse($this->client->apiRequest(
'get',
'dev/token',
[
'user' => $username,
'pass' => $password,
'is_hash' => $is_hash,
'date' => $date_from->toIso8601String(),
'age' => $age,
],
[],
$this->client->isTest() ? new Response(
200, $this->getTestingResponseHeaders(), \json_encode([
'user' => $username,
'pass' => $password,
'pass_hash' => base64_encode(md5($password, true)),
'date' => Carbon::now()->toIso8601String(),
'stamp' => Carbon::now()->getTimestamp(),
'age' => $age,
'salt' => $not_available = 'NOT:AVAILABLE:DURING:TESTING',
'salted_pass_hash' => $not_available,
'raw_token' => $not_available,
'token' => $not_available,
'header' => $not_available,
])) : null
));
}
throw new B2BApiException('Invalid or empty password passed');
}
throw new B2BApiException('Invalid or empty username passed');
} | Отладка формирования токена.
@param string $username Идентификатор пользователя
@param string $password Пароль (или md5 пароля)
@param bool $is_hash Признак использования MD5 пароля
@param null|Carbon|DateTime|int|string $date_from Дата начала действия токена с точностью до секунды
@param int $age Срок действия токена (в секундах)
@throws B2BApiException
@return B2BResponse | entailment |
public function create()
{
$menu = $this->handler->add($this->name, $this->getAttribute('position'))
->title($this->getAttribute('title'))
->link($this->getAttribute('link'))
->handles($this->menu['link'] ?? null);
$this->attachIcon($menu);
$this->handleNestedMenu();
return $this;
} | Create a new menu.
@return $this | entailment |
public function getAttribute(string $name)
{
$method = 'get'.\ucfirst($name).'Attribute';
$value = $this->menu[$name] ?? null;
if (\method_exists($this, $method)) {
return $this->container->call([$this, $method], ['value' => $value]);
}
return $value;
} | Handle get attributes.
@param string $name
@return mixed | entailment |
public function setAttribute(string $name, $value)
{
if (\in_array($name, ['id'])) {
$this->{$name} = $value;
}
$this->menu[$name] = $value;
return $this;
} | Set attribute.
@param string $name
@param mixed $value
@return $this | entailment |
public function prepare()
{
$id = $this->getAttribute('id');
$menus = $this->menu['with'] ?? [];
$parent = $this->getAttribute('position');
$position = Str::startsWith($parent, '^:') ? $parent.'.' : '^:';
foreach ((array) $menus as $class) {
$menu = $this->container->make($class)
->setAttribute('position', "{$position}{$id}")
->prepare();
if ($menu->passes()) {
$this->childs[] = $menu;
}
}
$this->name = $id;
$this->showToUser = $this->passesAuthorization();
return $this;
} | Prepare nested menu.
@return $this | entailment |
protected function passesAuthorization(): bool
{
$passes = false;
if (\method_exists($this, 'authorize')) {
$passes = $this->container->call([$this, 'authorize']);
}
return (bool) $passes;
} | Determine if the request passes the authorization check.
@return bool | entailment |
public function execute(callable $callback = null)
{
$stacks = $this->buildStacks();
foreach ($stacks as $requests) {
// Tell each request to use this dispatcher.
foreach ($requests as $request) {
$status = curl_multi_add_handle($this->handle, $request->getHandle());
if ($status !== CURLM_OK) {
throw new CurlErrorException(sprintf(
'Unable to add request to cURL multi handle (code #%u)',
$status
));
}
}
// Start dispatching the requests.
$this->dispatch();
// Loop through all requests and remove their relationship to our dispatcher.
foreach ($requests as $request) {
if ($request->isSuccessful() === false) {
throw new CurlErrorException($request->getErrorMessage());
}
$request->setRawResponse(curl_multi_getcontent($request->getHandle()));
curl_multi_remove_handle($this->handle, $request->getHandle());
if ($callback !== null) {
$callback($request->getResponse());
}
}
}
} | {@inheritdoc} | entailment |
public function get($key)
{
// Otherwise, if the key exists; return that request, else return null.
return (isset($this->requests[$key])) ? $this->requests[$key] : null;
} | {@inheritdoc} | entailment |
protected function buildStacks()
{
$stacks = [];
$stackNo = 0;
$currSize = 0;
foreach ($this->requests as $request) {
if ($currSize === $this->stackSize) {
$currSize = 0;
$stackNo++;
}
$stacks[$stackNo][] = $request;
$currSize++;
}
return $stacks;
} | Builds stacks of requests.
@return array | entailment |
protected function dispatch()
{
// Start processing the requests.
list($mrc, $active) = $this->process();
// Keep processing requests until we're done.
while ($active and $mrc === CURLM_OK) {
// Process the next request.
list($mrc, $active) = $this->process();
}
// Throw an exception if something went wrong.
if ($mrc !== CURLM_OK) {
throw new CurlErrorException('cURL read error #'.$mrc);
}
} | Dispatches all requests in the stack. | entailment |
protected function process()
{
// Workaround for PHP Bug #61141.
if (curl_multi_select($this->handle) === -1) {
usleep(100);
}
do {
$mrc = curl_multi_exec($this->handle, $active);
} while ($mrc === CURLM_CALL_MULTI_PERFORM);
return [$mrc, $active];
} | Processes all requests.
@return array | entailment |
public function addPage() {
$content = array();
foreach (\Drupal::entityTypeManager()->getStorage('site_commerce_type')->loadMultiple() as $type) {
$content[$type->id()] = $type;
}
if (!count($content)) {
return $this->redirect('entity.site_commerce_type.add_form');
}
if (count($content) == 1) {
$type = array_shift($content);
return $this->redirect('entity.site_commerce.add_form', array('site_commerce_type' => $type->id()));
}
return array(
'#theme' => 'site_commerce_add_list',
'#content' => $content,
);
} | Displays add content links for available content types.
Redirects to site_commerce/add/[type] if only one content type is available.
@return array|\Symfony\Component\HttpFoundation\RedirectResponse
A render array for a list of the site_commerce types that can be added; however,
if there is only one site_commerce type defined for the site, the function
will return a RedirectResponse to the site_commerce add page for that one site_commerce
type. | entailment |
public function add(SiteCommerceTypeInterface $site_commerce_type) {
$site_commerce = $this->entityManager()->getStorage('site_commerce')->create(array(
'type' => $site_commerce_type->id(),
));
$form = $this->entityFormBuilder()->getForm($site_commerce);
return $form;
} | Provides the site_commerce submission form.
@param \Drupal\site_commerce\Entity\SiteCommerceTypeInterface $site_commerce_type
The site_commerce type entity for the site_commerce.
@return array
A site_commerce submission form. | entailment |
public static function priceEditor($tid = 0) {
$build = [];
$query = \Drupal::database()->select('site_commerce', 'n');
$query->fields('n', array('pid'));
$query->condition('status', 1);
$query->innerJoin('site_commerce_field_data', 'f', 'f.pid=n.pid');
if ($tid) {
$query->innerJoin('site_commerce__field_category', 'c', 'c.entity_id=n.pid');
$query->condition('field_category_target_id', $tid);
}
$query->orderBy('f.weight');
$pids = $query->execute()->fetchCol();
$site_commerces = \Drupal::entityTypeManager()->getStorage('site_commerce')->loadMultiple($pids);
if (count($site_commerces)) {
$build['products'] = array(
'#theme' => 'site_commerce_price_editor',
'#site_commerces' => $site_commerces,
'#tid' => $tid,
'#attached' => array(
'library' => array(
'site_commerce/administer',
),
),
'#cache' => [
'max-age' => 0,
],
);
}
return $build;
} | Страница с перечнем цен товаров. Редактор цен. | entailment |
public static function getStatusStock($site_commerce) {
$build = [];
$status = (int) $site_commerce->field_settings->stock;
if ($status) {
$build['products'] = array(
'#theme' => 'site_commerce_stock_status',
'#site_commerce' => $site_commerce,
'#status' => $status,
'#name' => getStockAvailability($status),
);
}
return $build;
} | Возвращает темизированный статус товара на складе. | entailment |
public static function getPrice($tid) {
$build = [];
$form = new \Drupal\site_commerce\Form\SiteCommerceGetPriceForm($tid);
$form = \Drupal::formBuilder()->getForm($form, $tid);
$build['price_list'] = array(
'#theme' => 'site_commerce_get_price',
'#tid' => (int) $tid,
'#form' => $form,
);
return $build;
} | Возвращает темизированную кнопку на скачивание прайс листа по выбранной категории. | entailment |
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['visible'] = DataDefinition::create('integer')->setLabel(t('Display form add to cart'))->setRequired(TRUE);
$properties['event'] = DataDefinition::create('string')->setLabel(t('Event after adding to cart'))->setRequired(TRUE);
$properties['label_add'] = DataDefinition::create('string')->setLabel(t('Button name adding to cart'));
$properties['label_click'] = DataDefinition::create('string')->setLabel(t('Button name purchase in one click'));
$properties['description'] = DataDefinition::create('string')->setLabel(t('Note on the form of adding to cart'));
return $properties;
} | {@inheritdoc} | entailment |
public function view(Listener $listener)
{
$data['extensions'] = $this->extension->detect();
return $listener->showExtensions($data);
} | View all extension page.
@param \Orchestra\Contracts\Extension\Listener\Viewer $listener
@return mixed | entailment |
protected function addBladeExtensions(Application $app)
{
$blade = $app->make('blade.compiler');
$blade->directive('decorator', function ($expression) {
return "<?php echo \app('orchestra.decorator')->render({$expression}); ?>";
});
$blade->directive('placeholder', function ($expression) {
$expression = \preg_replace('/\(\s*(.*)\)/', '$1', $expression);
return "<?php \$__ps = app('orchestra.widget')->make('placeholder.'.{$expression}); "
."foreach (\$__ps as \$__p) { echo value(\$__p->value ?: ''); } ?>";
});
$blade->directive('get_meta', function ($expression) {
return "<?php echo \get_meta({$expression}); ?>";
});
$blade->directive('set_meta', function ($expression) {
return "<?php \set_meta({$expression}); ?>";
});
$blade->directive('title', function ($expression) {
return "<?php echo \app('html')->title({$expression}); ?>";
});
$blade->extend(function ($view) {
$view = \preg_replace('/(\s*)(<\?\s)/', '$1<?php ', $view);
$view = \preg_replace('/#\{\{\s*(.+?)\s*\}\}/s', '<?php $1; ?>', $view);
return $view;
});
} | Extends blade compiler.
@param \Illuminate\Contracts\Foundation\Application $app
@return void | entailment |
protected function addHtmlExtensions(Application $app)
{
$html = $app->make('html');
$html->macro('title', function ($title = null) use ($html) {
$builder = new Title($html, \memorize('site.name'), [
'site' => \get_meta('html::title.format.site', '{site.name} (Page {page.number})'),
'page' => \get_meta('html::title.format.page', '{page.title} — {site.name}'),
]);
return $builder->title($title ?: \trim(\get_meta('title', '')));
});
} | Add "title" macros for "html" service location.
@param \Illuminate\Contracts\Foundation\Application $app
@return void | entailment |
public function process(array $data, $type = "root", $parentId = null)
{
if (empty($data) || $data == [null]) {
throw new NoDataException("Empty data set received for '{$type}'", [
"data" => $data,
"type" => $type,
"parentId" => $parentId
]);
}
$this->analyzer->analyzeData($data, $type);
$this->structure->generateHeaderNames();
$this->cache->store(["data" => $data, "type" => $type, "parentId" => $parentId]);
} | Analyze and store an array of data for parsing.
The analysis is done immediately, based on the analyzer settings,
then the data is stored using \Keboola\Json\Cache and parsed
upon retrieval using getCsvFiles().
@param array $data
@param string $type is used for naming the resulting table(s)
@param string|array $parentId may be either a string,
which will be saved in a JSON_parentId column,
or an array with "column_name" => "value",
which will name the column(s) by array key provided
@throws NoDataException | entailment |
Subsets and Splits