sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function toResponseJSON()
{
// successful response
$arr = array('jsonrpc' => self::JSON_RPC_VERSION);
if ($this->result !== null) {
$arr['result'] = $this->result;
$arr['id'] = $this->id;
return json_encode($arr);
// error response
} else {
$arr['error'] = array('code' => $this->error_code, 'message' => $this->error_message);
$arr['id'] = $this->id;
return json_encode($arr);
}
} | return raw JSON response | entailment |
public function toArray() {
$arr = array();
foreach ($this->cells as $key => $cell) {
$arr[] = $cell->toArray();
}
return $arr;
} | returns an array representation of the instance
@return array | entailment |
public function toMatchingArray($colsArr) {
$arr = array();
//var_dump($colsArr);die();
foreach ($colsArr as $key => $col) {
$arr[] = $this->getCellArrayForPosition($col->getId());
}
return $arr;
} | returns an array representation of the instance,
by matching column ids with Row cell key
@return array | entailment |
public function getValueForPosition($pos) {
return (isset($this->cells[$pos])) ? $this->cells[$pos]->getValue(): null;
} | Returns a value in the row at a specific position
@param integer $pos
@return string|number | entailment |
public function createContent() {
// Creates a dummy $10 flat rate shipping method.
$method = ShippingMethod::create([
'name' => t('Flat rate'),
'plugin' => [
'target_plugin_id' => 'flat_rate',
'target_plugin_configuration' => [
'rate_label' => t('Flat rate'),
'rate_amount' => [
'number' => 10,
'currency_code' => 'AUD',
],
'default_package_type' => 'custom_box',
],
],
]);
$storeId = $this->loadStoreId();
if ($storeId !== NULL) {
$method->setStoreIds([$storeId]);
}
$method->save();
// Set default shipment type on order type.
/** @var \Drupal\commerce_order\Entity\OrderTypeInterface $orderType */
$orderType = $this->getDefaultOrderType();
$orderType->setThirdPartySetting(
'commerce_shipping',
'shipment_type',
'default'
);
$orderType->save();
} | {@inheritdoc}
@throws \Drupal\Core\Entity\EntityStorageException
@throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException | entailment |
public function symbols($currencies = null)
{
if (func_num_args() and !is_array(func_get_args()[0])) {
$currencies = func_get_args();
}
$this->symbols = $currencies;
return $this;
} | Sets the currencies to return.
Expects either a list of arguments or
a single argument as array
@param array $currencies
@return Exchange | entailment |
public function get()
{
$url = $this->buildUrl($this->url);
try {
$response = $this->makeRequest($url);
return $this->prepareResponse($response);
}
// The client needs to know only one exception, no
// matter what exception is thrown by Guzzle
catch (TransferException $e) {
throw new ConnectionException($e->getMessage());
}
} | Makes the request and returns the response
with the rates.
@throws ConnectionException if the request is incorrect or times out
@throws ResponseException if the response is malformed
@return array | entailment |
public function getResult()
{
$url = $this->buildUrl($this->url);
try {
$response = $this->makeRequest($url);
return $this->prepareResponseResult($response);
}
// The client needs to know only one exception, no
// matter what exception is thrown by Guzzle
catch (TransferException $e) {
throw new ConnectionException($e->getMessage());
}
} | Makes the request and returns the response
with the rates, as a Result object
@throws ConnectionException if the request is incorrect or times out
@throws ResponseException if the response is malformed
@return Result | entailment |
private function buildUrl($url)
{
$url = $this->protocol . '://' . $url . '/';
if ($this->date) {
$url .= $this->date;
} else {
$url .= 'latest';
}
$url .= '?base=' . $this->base;
if ($this->key) {
$url .= '&access_key=' . $this->key;
}
if ($symbols = $this->symbols) {
$url .= '&symbols=' . implode(',', $symbols);
}
return $url;
} | Forms the correct url from the different parts
@param string $url
@return string | entailment |
public function validateModuleID()
{
if (!empty($this->moduleID)) {
$module = Yii::$app->getModule($this->moduleID);
if ($module === null) {
$this->addError('moduleID', "Module '{$this->moduleID}' does not exist.");
}
}
} | Checks if model ID is valid | entailment |
public function generateActiveField($attribute)
{
$model = new $this->modelClass();
$attributeLabels = $model->attributeLabels();
$tableSchema = $this->getTableSchema();
if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
return "'$attribute' => ['type' => TabularForm::INPUT_PASSWORD,'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...']],";
//return "\$form->field(\$model, '$attribute')->passwordInput()";
} else {
return "'$attribute' => ['type' => TabularForm::INPUT_TEXT, 'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...']],";
//return "\$form->field(\$model, '$attribute')";
}
}
$column = $tableSchema->columns[$attribute];
if ($column->phpType === 'boolean') {
//return "\$form->field(\$model, '$attribute')->checkbox()";
return "'$attribute' => ['type' => Form::INPUT_CHECKBOX, 'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...']],";
} elseif ($column->type === 'text') {
//return "\$form->field(\$model, '$attribute')->textarea(['rows' => 6])";
return "'$attribute' => ['type' => Form::INPUT_TEXTAREA, 'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...','rows' => 6]],";
} elseif ($column->type === 'date') {
return "'$attribute' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => DateControl::classname(),'options' => ['type' => DateControl::FORMAT_DATE]],";
} elseif ($column->type === 'time') {
return "'$attribute' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => DateControl::classname(),'options' => ['type' => DateControl::FORMAT_TIME]],";
} elseif ($column->type === 'datetime' || $column->type === 'timestamp') {
return "'$attribute' => ['type' => Form::INPUT_WIDGET, 'widgetClass' => DateControl::classname(),'options' => ['type' => DateControl::FORMAT_DATETIME]],";
} else {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
$input = 'INPUT_PASSWORD';
} else {
$input = 'INPUT_TEXT';
}
if ($column->phpType !== 'string' || $column->size === null) {
//return "\$form->field(\$model, '$attribute')->$input()";
return "'$attribute' => ['type' => Form::".$input.", 'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...']],";
} else {
//return "\$form->field(\$model, '$attribute')->$input(['maxlength' => $column->size])";
return "'$attribute' => ['type' => Form::".$input.", 'options' => ['placeholder' => 'Enter ".$attributeLabels[$attribute]."...', 'maxlength' => ".$column->size."]],";
}
}
} | Generates code for active field
@param string $attribute
@return string | entailment |
public function generateActionParamComments()
{
/** @var ActiveRecord $class */
$class = $this->modelClass;
$pks = $class::primaryKey();
if (($table = $this->getTableSchema()) === false) {
$params = [];
foreach ($pks as $pk) {
$params[] = '@param ' . (substr(strtolower($pk), -2) == 'id' ? 'integer' : 'string') . ' $' . $pk;
}
return $params;
}
if (count($pks) === 1) {
return ['@param ' . $table->columns[$pks[0]]->phpType . ' $id'];
} else {
$params = [];
foreach ($pks as $pk) {
$params[] = '@param ' . $table->columns[$pk]->phpType . ' $' . $pk;
}
return $params;
}
} | Generates parameter tags for phpdoc
@return array parameter tags for phpdoc | entailment |
public function getQueue(string $queueName): QueueInterface
{
if (isset($this->queues[$queueName])) {
return $this->queues[$queueName];
}
$queueSettings = $this->getQueueSettings($queueName);
if (!isset($queueSettings['className'])) {
throw new JobQueueException(sprintf('Option className for queue "%s" is not configured', $queueName), 1334147126);
}
$queueObjectName = $queueSettings['className'];
if (!class_exists($queueObjectName)) {
throw new JobQueueException(sprintf('Configured class "%s" for queue "%s" does not exist', $queueObjectName, $queueName), 1445611607);
}
if (isset($queueSettings['queueNamePrefix'])) {
$queueNameWithPrefix = $queueSettings['queueNamePrefix'] . $queueName;
} else {
$queueNameWithPrefix = $queueName;
}
$options = isset($queueSettings['options']) ? $queueSettings['options'] : [];
$queue = new $queueObjectName($queueNameWithPrefix, $options);
$this->queues[$queueName] = $queue;
return $queue;
} | Returns a queue with the specified $queueName
@param string $queueName
@return QueueInterface
@throws JobQueueException
@api | entailment |
public function getQueueSettings(string $queueName): array
{
if (isset($this->queueSettingsRuntimeCache[$queueName])) {
return $this->queueSettingsRuntimeCache[$queueName];
}
if (!isset($this->settings['queues'][$queueName])) {
throw new JobQueueException(sprintf('Queue "%s" is not configured', $queueName), 1334054137);
}
$queueSettings = $this->settings['queues'][$queueName];
if (isset($queueSettings['preset'])) {
$presetName = $queueSettings['preset'];
if (!isset($this->settings['presets'][$presetName])) {
throw new JobQueueException(sprintf('Preset "%s", referred to in settings for queue "%s" is not configured', $presetName, $queueName), 1466677893);
}
$queueSettings = Arrays::arrayMergeRecursiveOverrule($this->settings['presets'][$presetName], $queueSettings);
}
$this->queueSettingsRuntimeCache[$queueName] = $queueSettings;
return $this->queueSettingsRuntimeCache[$queueName];
} | Returns the settings for the requested queue, merged with the preset defaults if any
@param string $queueName
@return array
@throws JobQueueException if no queue for the given $queueName is configured
@api | entailment |
public function getStoreValue($data = null)
{
// If Overrite Value
if (isset($this->value) && $this->overwriteValue) {
return $this->value;
}
// If user have user input value
if ($data != null && isset($data[$this->getName()])) {
// Process the value by FieldType
// For example, HTML5's datetime-local is unable insert into the database directly. So the DateTimeLocal have to convert it to the proper format.
return $this->fieldType->beforeStoreValue($data[$this->getName()]);
}
return $this->value;
} | Get the value that will be inserted into the database
@param array $data Most likely refer to $_POST
@return null | entailment |
public function getRenderValue()
{
$name = $this->getName();
$defaultValue = $this->getDefaultValue();
$bean = $this->getBean();
$value = "";
if ($this->isCreate()) {
// Create Page
// Use Default Value if not null
if ($this->value !== null) {
$value = $this->value;
} else if ($defaultValue !== null) {
$value = $defaultValue;
}
} else {
// Edit Page
if ($this->getFieldRelation() == Field::MANY_TO_MANY) {
// Many to many, Value list
$keyName = "shared". ucfirst($name) . "List";
$relatedBeans = $bean->{$keyName};
$value = [];
foreach ($relatedBeans as $relatedBean) {
$value[$relatedBean->id] = $relatedBean->id;
}
} else {
// Single Value
if ($this->isOverwriteValue() && $this->value !== null) {
// Use the value set by user.
$value = $this->value;
} else {
// Use the value from Database
$value = $this->getFieldType()->beforeRenderValue($bean->{$name});
// Escape the html
$value = htmlspecialchars($value);
}
}
}
return $value;
} | GEt the value that will be rendered on HTML page
@return array|mixed|null|string | entailment |
public function isStorable()
{
return
! $this->isReadOnly() &&
! $this->isHidden() &&
$this->getFieldRelation() == Field::NORMAL &&
$this->isStorable;
} | Is the field storable to the current table.
1. Is not read only.
2. Is not hidden field (Clarify: This is not equals to HTML's hidden, it's hide() ).
3. Is no special relation.
@return bool | entailment |
public function validate($value, $postData) {
foreach ($this->validatorList as $validator) {
$result = $validator($value, $postData);
if ($result !== true) {
return $result;
}
}
return true;
} | Validate Before INSERT/UPDATE
@param $value
@param $postData
@return bool | entailment |
public function createContent() {
$modulePath = drupal_get_path('module', 'presto_commerce');
$configPath = "{$modulePath}/config/optional";
$source = new FileStorage($configPath);
// Re-read checkout form display from the export config file.
// This should be safe enough as this only runs within a site install
// context.
$configStorage = Drupal::service('config.storage');
$configStorage->write(
'core.entity_form_display.commerce_product.book.default',
$source->read('core.entity_form_display.commerce_product.book.default')
);
$configStorage->write(
'core.entity_form_display.commerce_product.ebook.default',
$source->read('core.entity_form_display.commerce_product.ebook.default')
);
} | {@inheritdoc}
@throws \Drupal\Core\Config\UnsupportedDataTypeConfigException | entailment |
public function createContent() {
foreach ($this->getAttributeValues() as $attributeId => $values) {
foreach ($values as $value) {
$attributeValue = ProductAttributeValue::create([
'attribute' => $attributeId,
'name' => $value,
]);
$attributeValue->save();
}
}
} | {@inheritdoc}
@throws \Drupal\Core\Entity\EntityStorageException | entailment |
public function createContent() {
$productVariationType = ProductVariationType::load('default');
if ($productVariationType !== NULL) {
$productVariationType->delete();
}
$defaultProductType = ProductType::load('default');
if ($defaultProductType !== NULL) {
$defaultProductType->delete();
}
} | {@inheritdoc}
@throws \Drupal\Core\Entity\EntityStorageException | entailment |
public function getRate($code)
{
// the result won't have the base code in it,
// because that would always be 1. But to make
// dynamic code easier this prevents null if
// the base code is asked for
if ($code == $this->getBase()) {
return 1.0;
}
if (isset($this->rates[$code])) {
return $this->rates[$code];
}
return null;
} | Get an individual rate by Currency code
Will return null if currency is not found in the result
@param string $code
@return float|null | entailment |
public function getArray()
{
$arr = array('jsonrpc' => self::JSON_RPC_VERSION, 'method' => $this->method);
if ($this->params) {
$arr['params'] = $this->params;
}
if ($this->id !== null) {
$arr['id'] = $this->id;
}
return $arr;
} | return an associated array for this object | entailment |
private function recursiveUTF8Decode($result)
{
if (is_array($result)) {
foreach ($result as &$value) {
$value = $this->recursiveUTF8Decode($value);
}
return $result;
} else {
return utf8_decode($result);
}
} | recursively decode utf8 | entailment |
public function createContent() {
// Create node.
$node = Node::create([
'type' => 'page',
'title' => 'Products',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'uid' => 1,
'status' => 1,
'promote' => 0,
'field_fields' => [],
'path' => [
'alias' => '/products',
],
]);
$node->save();
// Create menu link.
$menuLink = MenuLinkContent::create([
'title' => 'Products',
'link' => [
'uri' => "internal:/node/{$node->id()}",
],
'menu_name' => 'main',
'weight' => 30,
'expanded' => TRUE,
]);
$menuLink->save();
} | {@inheritdoc}
@throws \Drupal\Core\Entity\EntityStorageException | entailment |
public function getFilteredDefinitions($type) {
$all = $this->getDefinitions();
return array_filter($all, function ($definition) use ($type) {
return $definition['type'] === $type;
});
} | Filters plugin definitions by a type.
@param string $type
Type to filter by.
@return array
A list of filtered plugin definitions. | entailment |
public function invokeMethod($method, $params)
{
// for named parameters, convert from object to assoc array
if (is_object($params)) {
$array = array();
foreach ($params as $key => $val) {
$array[$key] = $val;
}
$params = array($array);
}
// for no params, pass in empty array
if ($params === null) {
$params = array();
}
$reflection = new \ReflectionMethod($this->exposed_instance, $method);
// only allow calls to public functions
if (!$reflection->isPublic()) {
throw new Serverside\Exception("Called method is not publically accessible.");
}
// enforce correct number of arguments
$num_required_params = $reflection->getNumberOfRequiredParameters();
if ($num_required_params > count($params)) {
throw new Serverside\Exception("Too few parameters passed.");
}
return $reflection->invokeArgs($this->exposed_instance, $params);
} | attempt to invoke the method with params | entailment |
public function process()
{
// try to read input
try {
$json = file_get_contents($this->input);
} catch (\Exception $e) {
$message = "Server unable to read request body.";
$message .= PHP_EOL . $e->getMessage();
throw new Serverside\Exception($message);
}
// handle communication errors
if ($json === false) {
throw new Serverside\Exception("Server unable to read request body.");
}
// create request object
$request = $this->makeRequest($json);
// set content type to json if not testing
if (!(defined('ENV') && ENV == 'TEST')) {
header('Content-type: application/json');
}
// handle json parse error and empty batch
if ($request->error_code && $request->error_message) {
echo $request->toResponseJSON();
return;
}
// respond with json
echo $this->handleRequest($request);
} | process json-rpc request | entailment |
public function handleRequest($request)
{
// recursion for batch
if ($request->isBatch()) {
$batch = array();
foreach ($request->requests as $req) {
$batch[] = $this->handleRequest($req);
}
$responses = implode(',',array_filter($batch, function($a){return $a !== null;}));
if ($responses != null) {
return "[{$responses}]";
} else {
return null;
}
}
// check validity of request
if ($request->checkValid()) {
// check for method existence
if (!$this->methodExists($request->method)) {
$request->error_code = ERROR_METHOD_NOT_FOUND;
$request->error_message = "Method not found.";
return $request->toResponseJSON();
}
// try to call method with params
try {
$response = $this->invokeMethod($request->method, $request->params);
if (!$request->isNotify()) {
$request->result = $response;
} else {
return null;
}
// handle exceptions
} catch (\Exception $e) {
$request->error_code = ERROR_EXCEPTION;
$request->error_message = $e->getMessage();
}
}
// return whatever we got
return $request->toResponseJSON();
} | handle request object / return response json | entailment |
public function computePath($params) {
$route = $this->getPath();
if (!preg_match_all(
'~' . self::VARIABLE_REGEX . '~x', $route, $matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER
)) {
return $route;
}
$offset = 0;
$url = '';
/** @var string[] $matches */
foreach ($matches as $set) {
if ($set[0][1] > $offset) {
$url .= substr($route, $offset, $set[0][1] - $offset);
}
if(isset($params[$set[1][0]])) {
$url .= $params[$set[1][0]];
} else {
throw new \InvalidArgumentException(sprintf('No value supplied for "%s"', $set[1][0]));
}
$offset = $set[0][1] + strlen($set[0][0]);
}
if ($offset !== strlen($route)) {
$url .= substr($route, $offset);
}
return $url;
} | Inspired from https://github.com/nikic/FastRoute
@param array $params
@return string
@throws \InvalidArgumentException | entailment |
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#title'] = $this->t('Configure Presto functionality');
// Clear any module success messages.
drupal_get_messages('status');
// Add configuration forms for optional deps if defined.
$optionalDeps = $this->optionalDependencyManager->getDefinitions();
$form['optional_dependencies'] = [
'#type' => 'fieldset',
'#title' => $this->t('Optional Dependencies'),
'#collapsible' => FALSE,
'#tree' => TRUE,
];
$hasOptionalDepsForm = FALSE;
$form_state->set('optional_dependencies', []);
foreach ($optionalDeps as $optionalDep) {
/** @var \Drupal\presto\Installer\OptionalDependencies\OptionalDependencyInterface $instance */
$instance = $this->optionalDependencyManager->createInstance(
$optionalDep['id']
);
$pluginForm = [];
$subFormState = SubformState::createForSubform(
$pluginForm,
$form,
$form_state
);
$form['optional_dependencies'][$optionalDep['id']] = $instance->buildConfigurationForm(
$pluginForm,
$subFormState
);
if (count($form['optional_dependencies'][$optionalDep['id']]) > 0) {
$hasOptionalDepsForm = TRUE;
}
$form_state->set(['optional_dependencies', $optionalDep['id']], $instance);
}
// Hide optional dependencies fieldset if the config form is empty.
$form['optional_dependencies']['#access'] = $hasOptionalDepsForm;
$form['ecommerce'] = [
'#type' => 'fieldset',
'#title' => $this->t('eCommerce'),
'#collapsible' => FALSE,
];
// Only enable commerce if this profile was installed via Composer
// (which is when the below interface will exist).
$enableCommerce = FALSE;
/** @noinspection ClassConstantCanBeUsedInspection */
if (interface_exists('CommerceGuys\Intl\Currency\CurrencyInterface')) {
$enableCommerce = TRUE;
}
if (!$enableCommerce) {
$disabledMsg = $this->t('<p><strong>Not supported.</strong></p><p>Unfortunately, eCommerce is only supported if you install Presto via Composer. <a href=":url">See the README for more information on installing via Composer.</a></p>', [
':url' => 'https://github.com/Sitback/presto#installing-presto',
]);
$form['ecommerce']['disabled_info'] = [
'#type' => 'markup',
'#markup' => $disabledMsg,
];
}
$form['ecommerce']['enable_ecommerce'] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable eCommerce'),
'#description' => $this->t(
'Enables Drupal Commerce and some sane defaults to help you kickstart your eCommerce site.'
),
'#disabled' => !$enableCommerce,
'#default_value' => $enableCommerce,
];
$form['ecommerce']['ecommerce_install_demo_content'] = [
'#type' => 'checkbox',
'#title' => $this->t('Install Demo Content'),
'#description' => $this->t(
'Creates a few demo products to help you test your new eCommerce site.'
),
'#disabled' => !$enableCommerce,
'#default_value' => $enableCommerce,
'#states' => [
'visible' => [
'input[name="enable_ecommerce"]' => [
'checked' => TRUE,
],
],
'unchecked' => [
'input[name="enable_ecommerce"]' => [
'checked' => FALSE,
],
],
],
];
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save and continue'),
'#button_type' => 'primary',
'#submit' => ['::submitForm'],
];
return $form;
} | {@inheritdoc}
@throws \Drupal\Component\Plugin\Exception\PluginException | entailment |
public function submitForm(array &$form, FormStateInterface $form_state) {
$buildInfo = $form_state->getBuildInfo();
$install_state = $buildInfo['args'];
// Tell the 'presto_apply_configuration' install task that it should go
// ahead and enable eCommerce if required.
$install_state[0]['presto_ecommerce_enabled'] = (bool) $form_state->getValue(
'enable_ecommerce'
);
$install_state[0]['presto_ecommerce_install_demo_content'] = (bool) $form_state->getValue(
'ecommerce_install_demo_content'
);
$install_state[0]['form_state_values'] = $this->value(
$form_state->getValues()
);
// Submit any plugin forms.
$install_state[0][OptionalDependenciesInstaller::CONFIG_KEY] = [];
$depConfig =& $install_state[0][OptionalDependenciesInstaller::CONFIG_KEY];
foreach (Element::children($form['optional_dependencies']) as $dependencyId) {
/** @var \Drupal\presto\Installer\OptionalDependencies\OptionalDependencyInterface $instance */
/** @noinspection ReferenceMismatchInspection */
$instance = $form_state->get(['optional_dependencies', $dependencyId]);
$subFormState = SubformState::createForSubform(
$form['optional_dependencies'][$dependencyId],
$form,
$form_state
);
$instance->submitConfigurationForm($form, $subFormState);
$depConfig[$dependencyId] = $instance->getConfiguration();
}
$buildInfo['args'] = $install_state;
$form_state->setBuildInfo($buildInfo);
} | {@inheritdoc} | entailment |
protected function fetchResourceOwnerDetails(AccessToken $token)
{
$url = $this->getResourceOwnerDetailsUrl($token);
$request = $this->getAuthenticatedRequest(self::METHOD_POST, $url, $token);
return $this->getParsedResponse($request);
} | Requests resource owner details.
@param AccessToken $token
@return mixed | entailment |
public static function createCurrency() {
// If default country is Australia do not import the AUD Dollar.
$default_country = \Drupal::config('system.date')->get('country.default');
if ($default_country !== 'AU') {
$currency_importer = \Drupal::service('commerce_price.currency_importer');
$currency_importer->importByCountry('AU');
}
} | Create currency.
We do a manual currency create if the site country is not Australia as
the shop is setup for Australia.
@throws \Drupal\Core\Entity\EntityStorageException | entailment |
protected function sortByWeight(array $definitions) {
// Sort definitions by weight before returning.
uasort($definitions, function ($first, $second) {
if ($first['weight'] === $second['weight']) {
return 0;
}
return ($first['weight'] < $second['weight']) ? -1 : 1;
});
return $definitions;
} | Sorts plugins by weight.
@param array $definitions
List of plugin definitions, each MUST have a 'weight' key.
@return array
Sorted definitions. | entailment |
public function installIfEnabled() {
$operations = [];
// Attempt to install modules if we can.
if ($this->shouldInstallModules()) {
$operations = array_merge($operations, $this->addDependencyOperations());
}
if ($this->shouldInstallDemoContent()) {
$operations = array_merge($operations, $this->addDemoContentOperations());
}
return $operations;
} | {@inheritdoc} | entailment |
private function shouldInstallDemoContent() {
if (!array_key_exists('presto_ecommerce_install_demo_content', $this->installState)) {
return FALSE;
}
$create = (bool) $this->installState['presto_ecommerce_install_demo_content'];
return $this->shouldInstallModules() && $create;
} | Check if we should create demo content too.
@return bool
TRUE if allowed, FALSE otherwise. | entailment |
private function addDependencyOperations() {
$operations = [];
foreach ($this->dependencies as $module => $type) {
$operations[] = [
[static::class, 'installDependency'],
[
$module,
$type,
],
];
}
return $operations;
} | Crates a set of batch operations to install all required dependencies.
@return array
A set of Drupal batch operations. | entailment |
private function addDemoContentOperations() {
$operations = [];
$contentDefs = $this->demoContentManager->getFilteredDefinitions(
DemoContentTypes::ECOMMERCE
);
// Add module install task to install our commerce exports module.
$operations[] = [
[static::class, 'installDependency'],
[
'presto_commerce',
DependencyTypes::MODULE,
],
];
// Run any further content tasks.
foreach ($contentDefs as $def) {
$operations[] = [
[static::class, 'createDemoContent'],
[$def['id']],
];
}
return $operations;
} | Crates a set of batch operations to create demo content.
@return array
A set of Drupal batch operations. | entailment |
public static function createDemoContent($pluginId, array &$context) {
// Reset time limit so we don't timeout.
drupal_set_time_limit(0);
// Needs to be resolved manually since we don't have a context.
/** @var \Drupal\presto\Installer\DemoContentManager $demoContentManager */
$demoContentManager = Drupal::service(
'plugin.manager.presto.demo_content'
);
$definition = $demoContentManager->getDefinition($pluginId);
/** @var \Drupal\Core\StringTranslation\TranslatableMarkup $label */
$label = $definition['label'];
/** @var \Drupal\presto\Plugin\Presto\DemoContent\AbstractDemoContent $instance */
$instance = $demoContentManager->createInstance($pluginId);
$instance->createContent();
$context['results'][] = $pluginId;
$context['message'] = t('Running %task_name', [
'%task_name' => lcfirst($label->render()),
]);
} | Creates a demo content item.
This is a Drupal batch callback operation and as such, needs to be both a
public and a static function so that the Batch API can access it outside
the context of this class.
@param string $pluginId
Demo content class plugin ID.
@param array $context
Batch context.
@throws \Drupal\Component\Plugin\Exception\PluginException | entailment |
public function url($routeName, $data = []) {
$data2 = [];
$i = 1;
// Map key (p1, p2, p3....)
foreach ($data as $value) {
$data2["p" . $i++] = $value;
}
return $this->slim->urlFor("_louisCRUD_" . $routeName, $data2);
} | $crud->url("user", ["male", "1970"]);
@param $routeName
@param array $data
@return string | entailment |
public function renderExcel()
{
$this->beforeRender();
$list = $this->getListViewData();
$helper = new ExcelHelper();
$helper->setHeaderClosure(function ($key, $value) {
$this->getSlim()->response()->header($key, $value);
});
$helper->genExcel($this, $list, $this->getExportFilename());
} | Override render Excel function
@throws Exception\NoFieldException | entailment |
public function page($route, $callback) {
if ($this->configFunction != null) {
$function = $this->configFunction;
$result = $function();
if ($result === false) {
return;
}
}
$crud = $this;
$this->getSlim()->get($route, function () use ($crud, $callback) {
$content = $callback();
$this->render($this->getPageLayout(), [
"content" => $content
], true);
});
} | Content Page
@param $route
@param callable $callback | entailment |
public function render($echo = false)
{
$name = $this->field->getName();
$display = $this->field->getDisplayName();
$value = $this->getValue();
$readOnly = $this->getReadOnlyString();
$required = $this->getRequiredString();
$type = $this->type;
$crud = $this->field->getCRUD();
$html = <<< HTML
<div class="form-group">
<label for="field-$name">$display</label> <input id="field-$name" class="form-control" type="$type" name="$name" value="" $readOnly $required />
</div>
<div class="form-group">
<label for="field-$name-confirm">Confirm $display</label> <input id="field-$name-confirm" class="form-control" type="$type" value="" $readOnly $required />
</div>
HTML;
$crud->addScript(<<< HTML
<script>
$(document).ready(function () {
crud.addValidator(function (data) {
if ($("#field-$name-confirm").val() != $("#field-$name").val()) {
crud.addErrorMsg("Passwords are not matched.");
return false;
} else {
return true;
}
});
});
</script>
HTML
);
if ($echo) {
echo $html;
}
return $html;
} | Render Field for Create/Edit
@param bool|true $echo
@return string | entailment |
public function check() {
if (! self::$active) {
return;
}
// Check sessions are enabled.
if (session_id() === '') {
throw new \Exception('Sessions are required to use the CSRF Guard middleware.');
}
if (isset($_SESSION["csrf_time"])) {
$expired = (time() - $_SESSION["csrf_time"]) > 3600;
} else {
$expired = true;
}
if (isset($_GET["expire_token"])) {
$_SESSION["csrf_time"] = time() - 10000;
}
if (! isset($_SESSION[$this->key]) || $expired) {
$_SESSION[$this->key] = sha1(serialize($_SERVER) . rand(0, 0xffffffff));
$_SESSION["csrf_time"] = time();
}
$token = $_SESSION[$this->key];
// Validate the CSRF token.
if (in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE'))) {
$userToken = $this->app->request()->post($this->key);
if ($token !== $userToken) {
$this->app->halt(400, 'Invalid or missing or expired CSRF token.');
}
}
// Assign CSRF token key and value to view.
self::$token = $token;
} | Check CSRF token is valid.
Note: Also checks POST data to see if a Moneris RVAR CSRF token exists.
@return void
@throws \Exception | entailment |
public function installIfEnabled() {
$operations = [];
$dependencies = $this->optionalDependencyManager->getDefinitions();
foreach ($dependencies as $dependency) {
/** @var \Drupal\presto\Installer\OptionalDependencies\OptionalDependencyInterface $instance */
$instance = $this->optionalDependencyManager->createInstance(
$dependency['id'],
$this->getPluginConfig($dependency['id'])
);
if ($instance->shouldInstall($this->installState)) {
$operations[] = $instance->getInstallOperations();
}
}
// Prevent a greedy array_merge (argument unpacking not used for PHP 5.5
// support).
if (count($operations) > 0) {
/** @noinspection ArgumentUnpackingCanBeUsedInspection */
$operations = call_user_func_array('array_merge', $operations);
}
return $operations;
} | {@inheritdoc} | entailment |
private function getPluginConfig($pluginId) {
if (!array_key_exists(static::CONFIG_KEY, $this->installState)) {
return [];
}
if (!array_key_exists($pluginId, $this->installState[static::CONFIG_KEY])) {
return [];
}
return $this->installState[static::CONFIG_KEY][$pluginId];
} | Get plugin config from the install state.
@param string $pluginId
Plugin ID.
@return array
Plugin config (if any). | entailment |
public function addColumns(array $cols) {
foreach ($cols as $col) {
$this->cols[] = DataColumn::fromArray($col);
}
} | Adds multiple columns at the end of the array
the column should be an associative array, that can have 'label', 'id' and 'type'
@param array $cols | entailment |
public function addColumn($id, $label, $type) {
$this->cols[] = new DataColumn($id, $label, $type);
} | Adds a column at the end of the DataTable
@param string $id
@param string $label
@param string $type | entailment |
public function getLabels() {
$labels = array();
foreach ($this->cols as $col) {
$labels[] = $col->getLabel();
}
return $labels;
} | Returns all the column labels
@return array | entailment |
public function addRows(array $rows) {
foreach ($rows as $row) {
$this->rows[] = DataRow::fromArray($row);
}
} | adds rows at the end of the DataTable
each row can be an array, or just a value (string or number)
@param array $rows | entailment |
public function toArray() {
$colsArray = $this->getColArray();
$rowsArray = $this->rows;
array_walk($rowsArray, function (&$item) {
$item = array('c' => $item->toArray());
});
//remove nulls
return self::getFilteredArray($colsArray, $rowsArray, $this->p);
} | Return an array representation of the DataTable (to JSON)
It doesn't try to match the column ids to data ids
so all the dataRows cell needs to be defined (put null if you need)
@return array | entailment |
public function toStrictArray() {
$colsArray = $this->getColArray();
$rowsArray = $this->rows;
array_walk($rowsArray, function (&$item, $key, $cols) {
$item = array('c' => $item->toMatchingArray($cols));
}, $this->cols);
return self::getFilteredArray($colsArray, $rowsArray, $this->p);
} | Return an array representation of the DataTable (to JSON)
It doesn't try to match the column ids to data ids
so all the dataRows cell needs to be defined (put null if you need)
@return array | entailment |
public function getValuesForPosition($pos) {
$arr = array();
foreach ($this->rows as $key => $row) {
$arr[$key] = $row->getValueForPosition($pos);
}
return $arr;
} | Returns an array that contains the values for a specific column
@param integer $pos
@return array | entailment |
public static function fromSimpleMatrix(array $array, $hasHeader = true) {
$dataTable = new DataTable();
$labelArray = array();
if ($hasHeader) {
$labelArray = $array[0];
array_shift($array);
}
//need to found out the data type... just string or number
$firstDataRow = $array[0];
foreach ($firstDataRow as $key => $value) {
$type = "string";
$label = isset($labelArray[$key])? $labelArray[$key]: 'c'.$key;
if (is_object($value) && $value instanceof \DateTime) {
$type = 'datetime';
} elseif (is_bool($value)) {
$type = 'boolean';
} elseif (is_numeric($value)) {
$type = 'number';
}
$dataTable->addColumn('id'.$key, $label, $type);
}
//now the data...
foreach ($array as $key => $row) {
$dataTable->addRow($row);
}
return $dataTable;
} | Returns a DataTable from a simple matrix (array of array, with first row = label if hasHeader = true)
@param array $array
@param boolean $hasHeader if true, indicates that the first row contains the labels
@return DataTable | entailment |
public function execute(QueueInterface $queue, Message $message): bool
{
$service = $this->objectManager->get($this->className);
$this->deferMethodCallAspect->setProcessingJob(true);
try {
$methodName = $this->methodName;
call_user_func_array([$service, $methodName], $this->arguments);
return true;
} catch (\Exception $exception) {
throw $exception;
} finally {
$this->deferMethodCallAspect->setProcessingJob(false);
}
} | Execute the job
A job should finish itself after successful execution using the queue methods.
@param QueueInterface $queue
@param Message $message
@return boolean TRUE If the execution was successful
@throws \Exception | entailment |
public function render($echo = false)
{
$name = $this->field->getName();
$display = $this->field->getDisplayName();
$bean = $this->field->getBean();
$value = $this->getValue();
$disabled = $this->getDisabledString();
$required = $this->getRequiredString();
$readOnly = $this->getReadOnlyString(); // No used actually, because radio is not supported.
$html = "<label>$display</label>";
foreach ($this->options as $v =>$optionName) {
if ($value == $v) {
$selected = "checked";
} else {
$selected = "";
}
$html .= <<< EOF
<div class="radio">
<label><input type="radio" name="$name" value="$v" $disabled $required $selected /> $optionName</label>
</div>
EOF;
}
if ($echo)
echo $html;
return $html;
} | Render Field for Create/Edit
@param bool|true $echo
@return string | entailment |
public static function installDependency($dependency, $type, array &$context) {
// Reset time limit so we don't timeout.
drupal_set_time_limit(0);
switch ($type) {
case DependencyTypes::MODULE:
/** @var \Drupal\Core\Extension\ModuleInstaller $moduleInstaller */
$moduleInstaller = Drupal::service('module_installer');
$moduleInstaller->install([$dependency]);
break;
case DependencyTypes::THEME:
/** @var \Drupal\Core\Extension\ThemeInstaller $themeInstaller */
$themeInstaller = Drupal::service('theme_installer');
$themeInstaller->install([$dependency]);
break;
default:
throw new InstallerException(
"Unknown dependency type '{$type}'."
);
}
$context['results'][] = $dependency;
$context['message'] = t(
'Installed @dependency_type %dependency.',
[
'@dependency_type' => $type,
'%dependency' => $dependency,
]
);
} | Installs a Drupal dependency (e.g. a module or a theme).
This is a Drupal batch callback operation and as such, needs to be both a
public and a static function so that the Batch API can access it outside
the context of this class.
@param string $dependency
Dependency machine name.
@param string $type
Dependency type.
@param array $context
Batch API context.
@throws \Drupal\Core\Extension\ExtensionNameLengthException
@throws \Drupal\Core\Extension\MissingDependencyException
@throws \Drupal\presto\Installer\InstallerException | entailment |
public function buildConfigurationForm(
array $form,
FormStateInterface $form_state
) {
$form['presto_theme'] = [
'#type' => 'checkbox',
'#title' => t('Install Presto Theme'),
'#description' => t(
'Install and set as default the Presto Theme.'
),
'#default_value' => $this->configuration[static::THEME_NAME],
];
return $form;
} | {@inheritdoc} | entailment |
public function submitConfigurationForm(
array &$form,
FormStateInterface $form_state
) {
$this->configuration[static::THEME_NAME] = (bool) $form_state->getValue(
'presto_theme'
);
} | {@inheritdoc} | entailment |
public static function definePrestoThemeAsDefault() {
// Set presto_theme as default.
Drupal::configFactory()
->getEditable('system.theme')
->set('default', 'presto_theme')
->save();
// Set seven as admin theme.
Drupal::configFactory()
->getEditable('system.theme')
->set('admin', 'seven')
->save();
} | Define Presto Theme as Default. Used by the batch during install process.
@throws \Drupal\Core\Config\ConfigValueException | entailment |
public function render($echo = false)
{
$name = $this->field->getName();
$display = $this->field->getDisplayName();
$value = $this->getValue();
$readOnly = $this->getReadOnlyString();
$disabled = $this->getDisabledString();
$required = $this->getRequiredString();
$star = $this->getRequiredStar();
$type = $this->type;
if ($this->prefix == null && $this->postfix == null) {
$inputGroupOpenTag = "";
$inputGroupEndTag = "";
} else {
$inputGroupOpenTag = "<div class=\"input-group\">";
$inputGroupEndTag = "</div>";
}
if ($this->prefix != null) {
$prefixHTML = " <span class=\"input-group-addon\" >$this->prefix</span>";
} else {
$prefixHTML = "";
}
if ($this->postfix != null) {
$postfixHTML = " <span class=\"input-group-addon\" >$this->postfix</span>";
} else {
$postfixHTML = "";
}
$html = <<< EOF
<div class="form-group">
<label for="field-$name">$star $display</label>
$inputGroupOpenTag
$prefixHTML
<input id="field-$name" class="form-control" type="$type" name="$name" value="$value" $readOnly $required $disabled />
$postfixHTML
$inputGroupEndTag
</div>
EOF;
if ($echo)
echo $html;
return $html;
} | Render Field for Create/Edit
@param bool|true $echo
@return string | entailment |
protected static function readConfig($path, $file) {
$source = new FileStorage($path);
// Re-read checkout flow from the export config file.
// This should be safe enough as this only runs within a site install
// context.
/** @var \Drupal\Core\Config\StorageInterface $configStorage */
$configStorage = Drupal::service('config.storage');
return $configStorage->write(
$file,
$source->read($file)
);
} | Re-read config from file into active storage.
@param string $path
Config path.
@param string $file
Config file name.
@return bool
TRUE if successful, FALSE otherwise.
@throws \Drupal\Core\Config\StorageException
If a config write failure occurs.
@throws \Drupal\Core\Config\UnsupportedDataTypeConfigException
If a config read failur occurs. | entailment |
public function getFunctions() {
return array(
new \Twig_SimpleFunction('gchart_area_chart', array($this, 'gchartAreaChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_bar_chart', array($this, 'gchartBarChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_bubble_chart', array($this, 'gchartBubbleChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_calendar', array($this, 'gchartCalendar'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_candlestick_chart', array($this, 'gchartCandleStickChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_column_chart', array($this, 'gchartColumnChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_combo_chart', array($this, 'gchartComboChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_donut_chart', array($this, 'gchartDonutChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_gantt', array($this, 'gchartGantt'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_gauge', array($this, 'gchartGauge'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_geo_chart', array($this, 'gchartGeoChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_get_icon_pin_url', array($this, 'getIconPinUrl'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('gchart_get_icon_url', array($this, 'getIconUrl'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('gchart_get_letter_pin_url', array($this, 'getLetterPinUrl'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('gchart_get_pie_chart_url', array($this, 'getPieChartUrl'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('gchart_get_pie_chart3d_url', array($this, 'getPieChart3DUrl'), array('is_safe' => array('html'))),
new \Twig_SimpleFunction('gchart_get_qrcode_url', array($this, 'getQrCodeUrl')),
new \Twig_SimpleFunction('gchart_histogram', array($this, 'gchartHistogram'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_interval', array($this, 'gchartInterval'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_line_chart', array($this, 'gchartLineChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_map', array($this, 'gchartMap'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_org_chart', array($this, 'gchartOrgChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_pie_chart', array($this, 'gchartPieChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_sankey', array($this, 'gchartSankey'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_scatter_chart', array($this, 'gchartScatterChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_stepped_area_chart', array($this, 'gchartSteppedAreaChart'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_table', array($this, 'gchartTable'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_timeline', array($this, 'gchartTimeline'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_treemap', array($this, 'gchartTreeMap'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_trendlines', array($this, 'gchartTrendlines'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_waterfall', array($this, 'gchartWaterfall'), array('is_safe' => array('html'), 'needs_environment' => true)),
new \Twig_SimpleFunction('gchart_word_tree', array($this, 'gchartWordTree'), array('is_safe' => array('html'), 'needs_environment' => true)),
);
} | Defines the Twig functions exposed by this extension
@return array list of Twig functions | entailment |
public function gchartAreaChart(\Twig_Environment $env, $data, $id, $width, $height, $title = null, $config = array(), $events = array()) {
return $this->renderGChart($env, $data, $id, 'AreaChart', $width, $height, $title, $config, false, $events);
} | gchart_area_chart definition | entailment |
public function gchartComboChart(\Twig_Environment $env, $data, $id, $width, $height, $seriesType = 'line', $title = null, $config = array(), $events = array()) {
if (isset($seriesType) && !isset($config['seriesType'])) {
$config['seriesType'] = $seriesType;
}
return $this->renderGChart($env, $data, $id, 'ComboChart', $width, $height, $title, $config, false, $events);
} | gchart_combo_chart definition | entailment |
public function gchartSteppedAreaChart(\Twig_Environment $env, $data, $id, $width, $height, $title = null, $config = array(), $events = array()) {
if (!is_null($yLabel)) {
$vAxis = isset($config['vAxis'])? $config['vAxis']: array();
$vAxis['title'] = $yLabel;
$config['vAxis'] = $vAxis;
}
return $this->renderGChart($env, $data, $id, 'SteppedAreaChart', $width, $height, $title, $config, false, $events);
} | gchart_stepped_area_chart definition | entailment |
public function gchartTable(\Twig_Environment $env, $data, $id, $config = null, $events = array()) {
return $this->renderTemplate($env, 'gChartTemplate', array('chartType' => 'Table', 'data' => $data, 'id' => $id, 'config' => $config, 'events' => $events ));
} | gchart_table definition | entailment |
public function gchartTreeMap(\Twig_Environment $env, $data, $id, $width, $height, $title = '', $config = array(), $events = array()) {
return $this->renderGChart($env, $data, $id, 'TreeMap', $width, $height, $title, $config, true, $events);
} | gchart_treemap definition - needs 4 cols
@see http://code.google.com/apis/chart/interactive/docs/gallery/treemap.html#Data_Format | entailment |
public function gchartTrendlines(\Twig_Environment $env, $data, $id, $width, $height, $title = null, $xLabel = null, $yLabel = null, $config = array(), $events = array()) {
if (!is_null($xLabel)) {
$hAxis = isset($config['hAxis'])? $config['hAxis']: array();
$hAxis['title'] = $xLabel;
$config['hAxis'] = $hAxis;
}
if (!is_null($yLabel)) {
$vAxis = isset($config['vAxis'])? $config['vAxis']: array();
$vAxis['title'] = $yLabel;
$config['vAxis'] = $vAxis;
}
return $this->renderGChart($env, $data, $id, 'Trendlines', $width, $height, $title, $config, false, $events);
} | gchart_trendlines
note: The x-axis column cannot be of type string | entailment |
protected function renderGChart(\Twig_Environment $env, $data, $id, $type, $width, $height, $title = null, $config = array(), $addDivWithAndHeight = false, $events = array()) {
$config['width'] = $width;
$config['height'] = $height;
if (!isset($config['title']) && !is_null($title) && trim($title) != '') { $config['title'] = $title;}
return $this->renderTemplate($env, 'gChartTemplate', array('chartType' => $type, 'data' => $data, 'id' => $id, 'config' => $config, 'events' => $events ), $addDivWithAndHeight);
} | Generic method that returns html of gchart charts | entailment |
protected function renderTemplate(\Twig_Environment $env, $templateName, $params, $addDivWithAndHeight = false) {
$templ = false;
if (isset($this->resources[$templateName])) {
$templ = $env->loadTemplate($this->resources[$templateName]);
} else {
throw new \Exception('mmm, template not found');
}
if ($addDivWithAndHeight && isset($params['config']) && isset($params['config']['width']) && isset($params['config']['height'])) {
$params['addDivWithAndHeight'] = true;
$params['width'] = $params['config']['width'];
$params['height'] = $params['config']['height'];
} else {
$params['addDivWithAndHeight'] = false;
}
return $templ->render($params);
} | generic method that generates a Twig template based on its name | entailment |
public function getQrCodeUrl($text, $params = array(), $rawParams = array() ) {
$chart = new Chart\QrCode();
return $chart->getUrl($text, $params, $rawParams);
} | gchart_get_qrcode_url definition | entailment |
public function createContent() {
$productDetails = $this->productDetails();
/** @var \Drupal\commerce_product\Entity\Product $product */
$product = Product::create($productDetails);
$product->save();
foreach ($this->productVariations() as $variationAttrs) {
$variationAttrs['product_id'] = $product->id();
$variation = ProductVariation::create($variationAttrs);
$variation->save();
$product->addVariation($variation);
}
$storeId = $this->loadStoreId();
if ($storeId !== NULL) {
$product->setStoreIds([$storeId]);
}
$product->save();
} | {@inheritdoc}
@throws \Drupal\Core\Entity\EntityStorageException | entailment |
protected function loadAttributeValue($name, $attribute) {
$query = Drupal::entityQuery('commerce_product_attribute_value');
$result = $query->condition('name', $name)
->condition('attribute', $attribute)
->execute();
// There should only ever be one value returned so we naively use the first
// item in the array. This should generally be safe as this should only run
// within a Drupal site install context.
$attributeValue = NULL;
if (count($result) > 0) {
$attributeValue = ProductAttributeValue::load(reset($result));
}
return $attributeValue;
} | Loads a product attribute value by attribute ID and name.
@param string $name
Attribute value name.
@param string $attribute
Attribute ID.
@return \Drupal\commerce_product\Entity\ProductAttributeValue|null
Loaded attribute value or NULL if one couldn't be found. | entailment |
public static function fromArray(array $arr) {
$v = isset($arr['v'])? $arr['v'] : null;
$f = isset($arr['f'])? $arr['f'] : null;
$p = isset($arr['p'])? $arr['p'] : null;
return new DataCell($v, $f, $p);
} | Create an instance of DataCell from an array.
@param array $arr asssociative array expected
keys:
- 'v': value - recommanded, almost mandatory
- 'f' (text representation of value
- 'p': some options (array) - see http://code.google.com/apis/chart/interactive/docs/reference.html#rowsproperty
@return DataCell | entailment |
public function toArray() {
$arr = array_filter(
array(
'v' => $this->getValueForArray(),
'f' => $this->f,
'p' => $this->p,
), function ($val) { return !is_null($val);}
);
// mm, some charts don't work if 'v' is not present
if (!isset($arr['v'])) {
$arr['v'] = null;
}
return $arr;
} | returns an array representation of the cell (useful for JSON)
@return array | entailment |
public function render($echo = false)
{
$name = $this->field->getName();
$display = $this->field->getDisplayName();
$value = $this->getValue();
$readOnly = $this->getReadOnlyString();
$required = $this->getRequiredString();
$crud = $this->field->getCRUD();
$key = self::$apiKey;
$longitudeFieldName = $this->longitudeField->getName();
$html = <<< HTML
<div class="form-group">
<label for="field-$name">$display</label>
<input id="field-$name" class="form-control" type="hidden" name="$name" value="$value" $readOnly $required />
<div id="map-$name" style="width:100%; height:500px"></div>
</div>
HTML;
$crud->addScript(<<< HTML
<script src="https://maps.googleapis.com/maps/api/js?key=$key"></script>
<script>
$(document).ready(function () {
var latitude = $("#field-$name").val();
var longitude = $("#field-$longitudeFieldName").val();
var zoom = 14;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: zoom,
center: LatLng,
panControl: false,
zoomControl: false,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-$name"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(map, 'click', function(event) {
marker.setPosition(event.latLng);
$("#field-$name").val(latLng.lat());
$("#field-$longitudeFieldName").val(latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function(marker) {
var latLng = marker.latLng;
$("#field-$name").val(latLng.lat());
$("#field-$longitudeFieldName").val(latLng.lng());
});
});
</script>
HTML
);
if ($echo)
echo $html;
return $html;
} | Render Field for Create/Edit
@param bool|true $echo
@return string | entailment |
public function render($echo = false)
{
$name = $this->field->getName();
$display = $this->field->getDisplayName();
$bean = $this->field->getBean();
$valueList = $this->getValue();
$readOnly = $this->getDisabledString();
$required = $this->getRequiredString();
$html = <<<TAG
<label for="field-$name" >$display</label>
TAG;
$html .= <<<TAG
<div class="form-group checkboxes-group">
TAG;
foreach ($this->options as $v =>$optionName) {
if (isset($valueList[$v])) {
$selected = "checked";
} else {
$selected = "";
}
$nameAttr = 'name="'. $name .'[]"';
$html .= <<< HTML
<div class="checkbox">
<label>
<input type="checkbox" value="$v" $nameAttr $required $readOnly $selected /> $optionName
</label>
</div>
HTML;
}
$html .= " </div><br />";
if ($echo)
echo $html;
return $html;
} | Render Field for Create/Edit
@param bool|true $echo
@return string | entailment |
public function call($procedure, $varArgs = null /*..., $argN*/) {
if (!is_string($procedure)) {
throw new \InvalidArgumentException(
sprintf('%s requires a string at Argument 1', __METHOD__)
);
}
if (!$this->isStarted) {
$this->start();
}
if ($this->maxTaskQueueSize < 0 || $this->maxTaskQueueSize > $this->outstandingTaskCount) {
$task = $this->taskReflection->newInstanceArgs(func_get_args());
return $this->acceptNewTask($task);
} else {
return new Failure(new TooBusyException(
sprintf("Cannot execute '%s' task; too busy", $procedure)
));
}
} | Dispatch a procedure call to the thread pool
This method will auto-start the thread pool if workers have not been spawned.
@param string $procedure The name of the function to invoke
@param mixed $varArgs A variable-length argument list to pass the procedure
@throws \InvalidArgumentException if the final parameter is not a valid callback
@return \Amp\Promise | entailment |
public function execute(\Stackable $task) {
if (!$this->isStarted) {
$this->start();
}
if ($this->maxTaskQueueSize < 0 || $this->maxTaskQueueSize > $this->outstandingTaskCount) {
return $this->acceptNewTask($task);
} else {
return new Failure(new TooBusyException(
sprintf('Cannot execute task of type %s; too busy', get_class($task))
));
}
} | Dispatch a pthreads Stackable to the thread pool for processing
This method will auto-start the thread pool if workers have not been spawned.
@param \Stackable $task A custom pthreads stackable
@return \Amp\Promise | entailment |
public function start() {
if (!$this->isStarted) {
$this->generateIpcServer();
$this->isStarted = true;
for ($i=0;$i<$this->poolSizeMin;$i++) {
$this->spawnWorker();
}
$this->registerTaskTimeoutWatcher();
}
return $this;
} | Spawn worker threads
No tasks will be dispatched until Dispatcher::start is invoked.
@return \Amp\Dispatcher Returns the current object instance | entailment |
public function setOption($option, $value) {
switch ($option) {
case self::OPT_THREAD_FLAGS:
$this->setThreadStartFlags($value); break;
case self::OPT_POOL_SIZE_MIN:
$this->setPoolSizeMin($value); break;
case self::OPT_POOL_SIZE_MAX:
$this->setPoolSizeMax($value); break;
case self::OPT_TASK_TIMEOUT:
$this->setTaskTimeout($value); break;
case self::OPT_IDLE_WORKER_TIMEOUT:
$this->setIdleWorkerTimeout($value); break;
case self::OPT_EXEC_LIMIT:
$this->setExecutionLimit($value); break;
case self::OPT_IPC_URI:
$this->setIpcUri($value); break;
case self::OPT_UNIX_IPC_DIR:
$this->setUnixIpcSocketDir($value); break;
default:
throw new \DomainException(
sprintf('Unknown option: %s', $option)
);
}
return $this;
} | Configure dispatcher options
@param string $option A case-insensitive option key
@param mixed $value The value to assign
@throws \DomainException On unknown option key
@return \Amp\Dispatcher Returns the current object instance | entailment |
public function removeStartTask(\Stackable $task) {
if ($this->workerStartTasks->contains($task)) {
$this->workerStartTasks->detach($task);
}
} | Clear a worker task currently stored for execution each time a worker spawns
@param \Stackable $task
@return void | entailment |
public function updateSearchResults(&$results, &$properties)
{
// Customise empty results
$customNoSearchResultsText = SiteConfig::current_site_config()->NoSearchResults;
if ($customNoSearchResultsText) {
$properties['NoSearchResults'] = $customNoSearchResultsText;
}
// Customise empty search
$customEmptyText = SiteConfig::current_site_config()->EmptySearch;
if ($customEmptyText) {
$properties['EmptySearch'] = $customEmptyText;
}
} | See BasePage_Controller::results()
@param CwpSearchResult $results
@param array $properties | entailment |
public function parse($arrAttributes=null)
{
// Return a wildcard in the back end
if (TL_MODE == 'BE')
{
/** @var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ' . $GLOBALS['TL_LANG']['FFL']['colStart'][0] . ' ###';
return $objTemplate->parse();
}
return parent::parse($arrAttributes);
} | Parse the template file and return it as string
@param array $arrAttributes An optional attributes array
@return string The template markup | entailment |
public function boot()
{
Blade::directive('captcha', function ($siteKey = null) {
$siteKey = $this->loadSiteKey($siteKey);
return "<script src='https://www.google.com/recaptcha/api.js'></script>".
"<div class='g-recaptcha' data-sitekey='{$siteKey}'></div>";
});
Blade::directive('invisiblecaptcha', function ($siteKey = null) {
$siteKey = $this->loadSiteKey($siteKey);
return "<script src='https://www.google.com/recaptcha/api.js'></script>".
"<script>
function onSubmit(token) {
document.forms[0].submit();
}
</script>".
"<button
class='g-recaptcha'
data-sitekey='{$siteKey}'
data-callback='onSubmit'>
Submit
</button>";
});
} | Perform post-registration booting of services.
@return void | entailment |
public function call(callable $func, ...$args): int
{
$memory = $this->allocateMemory();
$pid = pcntl_fork();
if ($pid == -1) {
throw new Exception("Failed to fork");
}
# If the child process was started then return its pid
if ($pid) {
return $pid;
}
# If this is the child process, then run the requested function
try {
$func(...$args);
} catch (\Throwable $e) {
$memory->addException($e);
exit(1);
}
# Then we must exit or else we will end up the child process running the parent processes code
die();
} | Run some code in a thread.
@param callable $func The function to execute
@param mixed ...$args The arguments to pass to the function
@return int The pid of the thread created to execute this code
@throws Exception | entailment |
public function cleanup()
{
if (!$this->memory) {
throw new \LogicException("Cleanup should be used after allocate.");
}
$this->memory->delete();
$this->memory = null;
} | Method to be called when the adapter is finished with.
@return void
@throws \LogicException | entailment |
public function parse($arrAttributes=null)
{
// Return a wildcard in the back end
if (TL_MODE == 'BE')
{
$strCustomClasses = "";
if($this->strClass) {
$strCustomClasses .= ", ";
$strCustomClasses .= str_replace(" ", ", ", $this->strClass);
}
/** @var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### E&F GRID: ' . $GLOBALS['TL_LANG']['FFL']['rowStart'][0] . ' ###';
$objTemplate->wildcard .= '<div class="tl_content_right tl_gray m12">('.$GLOBALS['EUF_GRID_SETTING']['row'].$strCustomClasses.')</div>';
return $objTemplate->parse();
}
return parent::parse($arrAttributes);
} | Parse the template file and return it as string
@param array $arrAttributes An optional attributes array
@return string The template markup | entailment |
public function request($url, $requestData) {
$request = new CurlRequest($url);
$request->setPostData($requestData);
$this->setOptionsOnRequest($request, $this->options);
return $request->execute();
} | {@inheritDoc}
@codeCoverageIgnore | entailment |
protected function setOptionsOnRequest(CurlRequest $request, $options) {
foreach($options as $option => $value) {
$request->setOption($option, $value);
}
} | Set the defined options on the given CurlRequest instance
@param \Phabricator\Client\Curl\CurlRequest $request
@param $options
@throws \BuildR\Foundation\Exception\RuntimeException
@codeCoverageIgnore | entailment |
public function updateCMSFields(FieldList $fields)
{
$gridField = GridField::create(
'CarouselItems',
_t(__CLASS__ . 'TITLE', 'Hero/Carousel'),
$this->getCarouselItems(),
GridFieldConfig_RelationEditor::create()
);
$gridField->setDescription(_t(
__CLASS__ . 'NOTE',
'NOTE: Carousel functionality will automatically be loaded when 2 or more items are added below'
));
$gridConfig = $gridField->getConfig();
$gridConfig->getComponentByType(GridFieldAddNewButton::class)->setButtonName(
_t(__CLASS__ . 'ADDNEW', 'Add new')
);
$gridConfig->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
$gridConfig->removeComponentsByType(GridFieldDeleteAction::class);
$gridConfig->addComponent(new GridFieldDeleteAction());
$gridConfig->addComponent(new GridFieldOrderableRows('SortOrder'));
$gridConfig->removeComponentsByType(GridFieldSortableHeader::class);
$gridField->setModelClass(CarouselItem::class);
$fields->findOrMakeTab(
'Root.Carousel',
_t(__CLASS__ . 'TITLE', 'Hero/Carousel')
);
$fields->addFieldToTab('Root.Carousel', $gridField);
} | Add the carousel management GridField to the Page's CMS fields
@param FieldList $fields | entailment |
protected function processRawResponse($rawResult) {
$result = json_decode($rawResult, TRUE);
if(json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Malformed JSON response! Message: ' . json_last_error_msg());
}
return $result;
} | Process the raw JSON response, given from conduit.
Throw an exception when given JSON is malformed
@param $rawResult
@throws \BuildR\Foundation\Exception\RuntimeException
@return mixed | entailment |
public function call(callable $func, ...$args): int
{
$pid = ++$this->pid;
$this->status[$pid] = 0;
try {
$func(...$args);
} catch (\Throwable $e) {
$this->exceptions[] = $e;
$this->status[$pid] = 256;
}
return $pid;
} | Run some code in a thread.
@param callable $func The function to execute
@param mixed ...$args The arguments to pass to the function
@return int The pid of the thread created to execute this code | entailment |
private function waitForAnyThread()
{
while (true) {
foreach ($this->getPIDs() as $pid) {
if (!$this->isRunning($pid)) {
return;
}
}
# If none of the threads have finished let, wait for a second before checking again
sleep(1);
}
} | If we've exhausted our limit of threads, wait for one to finish.
@return void | entailment |
public function request($url, $requestData) {
if(!class_exists('GuzzleHttp\Client')) {
throw new RuntimeException('The guzzle client is not installed. Please install guzzlehttp/guzzle');
}
$client = new Client();
//We do not care exceptions, this will handled by the user
$response = $client->request('POST', $url, ['form_params' => $requestData]);
return $response->getBody()->getContents();
} | {@inheritDoc}
@codeCoverageIgnore | entailment |
public function initialize() {
$this->handler = curl_init();
$this->setOption(CURLOPT_URL, $this->requestUrl)
->setOption(CURLOPT_VERBOSE, 0)
->setOption(CURLOPT_HEADER, 0);
} | Initialize the CURL session | entailment |
public function setOption($option, $value) {
//Silence it because errors handled differently
$res = @curl_setopt($this->handler, $option, $value);
if($res === TRUE) {
return $this;
}
throw new RuntimeException('Failed to set the following option: ' . $option);
} | Set an opt in current curl handler
@param int $option
@param mixed $value
@throws \BuildR\Foundation\Exception\RuntimeException
@return \Phabricator\Client\Curl\CurlRequest | entailment |
public function setOptionFromArray($options) {
foreach($options as $option => $value) {
$this->setOption($option, $value);
}
return $this;
} | Set multiple options with an associative array
@param $options
@return \Phabricator\Client\Curl\CurlRequest | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.