sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function setLanguageDatabase(string $language) : bool
{
$pdo = $this->bot->getPDO();
// Update the language in the database
$sth = $pdo->prepare('UPDATE ' . $this->user_table . ' SET language = :language WHERE '
. $this->id_column . ' = :id');
$sth->bindParam(':language', $language);
$chat_id = $this->bot->chat_id;
$sth->bindParam(':id', $chat_id);
try {
$sth->execute();
} catch (\PDOException $e) {
throw new BotException($e->getMessage());
}
$this->language = $language;
return true;
} | \brief Set the current user language in database and internally.
\details Save it into database first.
@param string $language The language to set.
@return bool On sucess, return true, throws exception otherwise. | entailment |
public function getLanguageRedis(int $expiring_time = 86400) : string
{
$redis = $this->bot->getRedis();
$chat_id = $this->bot->chat_id;
// Check if the language exists on Redis
if ($redis->exists($this->bot->chat_id . ':language')) {
$this->language = $redis->get($chat_id . ':language');
return $this->language;
}
// Set the value from the database
$redis->setEx(
$this->bot->chat_id . ':language',
$expiring_time,
$this->getLanguageDatabase()
);
return $this->language;
} | \brief Get current user language from Redis (as a cache) and set it in language.
\details Using Redis as cache, check for the language. On failure, get the language
from the database and store it (with default expiring time of one day) in Redis.
It also change $language parameter of the bot to the language returned.
@param int $expiring_time <i>Optional</i>. Set the expiring time for the language on redis each time it is took from the sql database.
@return string Language for the current user, $default_language on errors. | entailment |
public function setLanguageRedis(string $language, int $expiring_time = 86400) : bool
{
$redis = $this->bot->getRedis();
// If we could successfully set the language in the database
if ($this->setLanguageDatabase($language)) {
// Set the language in Redis
$redis->setEx($this->bot->chat_id . ':language', $expiring_time, $language);
return true;
}
return false;
} | \brief Set the current user language in both Redis, database and internally.
\details Save it into database first, then create the expiring key on Redis.
@param string $language The language to set.
@param int $expiring_time <i>Optional</i>. Time for the language key in redis to expire.
@return bool On sucess, return true, throws exception otherwise. | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['form'] = $options['form'];
$templateVars['data'] = [
'messages' => $this->getFlashMessages(),
];
$templateVars = array_merge($templateVars, $options['parameters']);
$view->setTemplateData($templateVars);
return $view;
} | {@inheritdoc} | entailment |
public function getNbResults()
{
if (!$this->resultSet) {
return $this->searchable->search($this->query)->getTotalHits();
}
return $this->resultSet->getTotalHits();
} | Returns the number of results.
@return integer The number of results. | entailment |
public function getSlice($offset, $length)
{
$this->resultSet = $this->searchable->search($this->query, array(
'from' => $offset,
'size' => $length
));
return $this->convertResultSet($this->resultSet);
} | Returns an slice of the results.
@param integer $offset The offset.
@param integer $length The length.
@return array|\Traversable The slice. | entailment |
public function checkCommand(array $callback_query) : bool
{
if (isset($callback_query['data'])) {
// If command is found in callback data
if (strpos($this->data, $callback_query['data']) !== false) {
return true;
}
}
return false;
} | \brief (<i>Internal</i>) Process the callback query and check if it triggers a command of this type.
@param array $callback_query Callback query to process.
@return bool True if the callback query triggered a command. | entailment |
public function setPayment(string $provider_token, string $currency = 'EUR')
{
if (!$provider_token) {
$this->logger->warning('setPayment expects a valid provider token, an invalid one given.');
throw new BotException('Invalid provider token given to "setPayment"');
}
$this->_provider_token = $provider_token;
$this->_payment_currency = $currency;
} | \brief Set data for bot payments used across 'sendInvoice'.
@param string $provider_token The token for the payment provider got using BotFather.
@param string $currency The payment currency (represented with 'ISO 4217 currency mode'). | entailment |
public function sendInvoice(string $title, string $description, string $start_parameter, $prices, $optionals = [])
{
$OPTIONAL_FIELDS = [
'photo_url',
'photo_width',
'photo_height',
'need_name',
'need_phone_number',
'need_email',
'need_shipping_address',
'is_flexible',
'disable_notification',
'reply_to_message_id',
'reply_markup'
];
$payload = $this->generateSecurePayload();
$this->parameters = [
'chat_id' => $this->chat_id,
'title' => $title,
'description' => $description,
'payload' => $payload,
'provider_token' => $this->_provider_token,
'start_parameter' => $start_parameter,
'currency' => $this->_payment_currency,
'prices' => $this->generateLabeledPrices($prices)
];
// Add optional fields if available
foreach ($OPTIONAL_FIELDS as $field)
{
if (isset($optionals[$field]))
{
$this->parameters[$field] = $optionals[$field];
}
}
return [$payload, $this->processRequest('sendInvoice', 'Message')];
} | \brief Send an invoice.
\details Send an invoice in order receive real money. [API reference](https://core.telegram.org/bots/api#sendinvoice).
@param $title The title of product or service to pay (e.g. Free Donation to Telegram).
@param $description A description of product or service to pay.
@param $payload Bot-defined invoice payload.
@param $start_parameter Unique deep-linking parameter used to generate this invoice.
@param $prices The various prices to pay (e.g array('Donation' => 14.50, 'Taxes' => 0.50)).
@return string The payload for that specific invoice.
@return Message|false message sent on success, false otherwise. | entailment |
private function generateLabeledPrices(array $prices)
{
$response = [];
foreach ($prices as $item => $price)
{
if ($price < 1)
{
$this->logger->warning('Invalid or negative price passed to "sendInvoice"');
throw new \Exception('Invalid or negative price passed to "sendInvoice"');
}
// Format the price value following the official guideline:
// https://core.telegram.org/bots/api#labeledprice
$formatted_price = intval($price * 100);
array_push($response, ['label' => $item, 'amount' => $formatted_price]);
}
return json_encode($response);
} | \brief Convert a matrix of prices in a JSON string object accepted by 'sendInvoice'.
@param $prices The matrix of prices.
@return string The JSON string response. | entailment |
public function sendMessage($text, string $reply_markup = null, int $reply_to = null, string $parse_mode = 'HTML', bool $disable_web_preview = true, bool $disable_notification = false)
{
$this->parameters = [
'chat_id' => $this->chat_id,
'text' => $text,
'parse_mode' => $parse_mode,
'disable_web_page_preview' => $disable_web_preview,
'reply_markup' => $reply_markup,
'reply_to_message_id' => $reply_to,
'disable_notification' => $disable_notification
];
return $this->processRequest('sendMessage', 'Message');
} | \brief Send a text message.
\details Use this method to send text messages. [API reference](https://core.telegram.org/bots/api#sendmessage)
@param $text Text of the message.
@param $reply_markup <i>Optional</i>. Reply_markup of the message.
@param $parse_mode <i>Optional</i>. Parse mode of the message.
@param $disable_web_preview <i>Optional</i>. Disables link previews for links in this message.
@param $disable_notification <i>Optional</i>. Sends the message silently.
@return Message|false Message sent on success, false otherwise. | entailment |
public function forwardMessage($from_chat_id, int $message_id, bool $disable_notification = false)
{
$this->parameters = [
'chat_id' => $this->chat_id,
'message_id' => $message_id,
'from_chat_id' => $from_chat_id,
'disable_notification' => $disable_notification
];
return $this->processRequest('forwardMessage', 'Message');
} | \brief Forward a message.
\details Use this method to forward messages of any kind. [API reference](https://core.telegram.org/bots/api#forwardmessage)
@param $from_chat_id The chat where the original message was sent.
@param $message_id Message identifier (id).
@param $disable_notification <i>Optional</i>. Sends the message silently.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendPhoto(&$photo, string $reply_markup = null, string $caption = '', bool $disable_notification = false)
{
$this->_file->init($photo, 'photo');
$this->parameters = [
'chat_id' => $this->chat_id,
'caption' => $caption,
'reply_markup' => $reply_markup,
'disable_notification' => $disable_notification,
];
return $this->processRequest('sendPhoto', 'Message', $this->checkCurrentFile());
} | \brief Send a photo.
\details Use this method to send photos. [API reference](https://core.telegram.org/bots/api#sendphoto)
@param $photo Photo to send, can be a file_id or a string referencing the location of that image(both local or remote path).
@param $reply_markup <i>Optional</i>. Reply markup of the message.
@param $caption <i>Optional</i>. Photo caption (may also be used when resending photos by file_id), 0-200 characters.
@param $disable_notification <i>Optional<i>. Sends the message silently.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendAudio($audio, string $caption = null, string $reply_markup = null, int $duration = null, string $performer, string $title = null, bool $disable_notification = false, int $reply_to_message_id = null)
{
$this->_file->init($audio, 'audio');
$this->parameters = [
'chat_id' => $this->chat_id,
'caption' => $caption,
'duration' => $duration,
'performer' => $performer,
'title' => $title,
'reply_to_message_id' => $reply_to_message_id,
'reply_markup' => $reply_markup,
'disable_notification' => $disable_notification,
];
return $this->processRequest('sendAudio', 'Message', $this->checkCurrentFile());
} | \brief Send an audio.
\details Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .mp3 format. [API reference](https://core.telegram.org/bots/api/#sendaudio)
Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
@param $audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or give the local path of an audio to upload.
@param $caption <i>Optional</i>. Audio caption, 0-200 characters.
@param $reply_markup <i>Optional</i>. Reply markup of the message.
@param $duration <i>Optional</i>. Duration of the audio in seconds.
@param $performer <i>Optional</i>. Performer.
@param $title <i>Optional</i>. Track name.
@param $disable_notification <i>Optional</i>. Sends the message silently.
@param $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendDocument(string $document, string $caption = '', string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null)
{
$this->_file->init($document, 'document');
$this->parameters = [
'chat_id' => $this->chat_id,
'caption' => $caption,
'reply_to_message_id' => $reply_to_message_id,
'reply_markup' => $reply_markup,
'disable_notification' => $disable_notification,
];
return $this->processRequest('sendDocument', 'Message', $this->checkCurrentFile());
} | \brief Send a document.
\details Use this method to send general files. [API reference](https://core.telegram.org/bots/api/#senddocument)
@param string $document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or give the local path of an document to upload it.
Only some document are allowed through url sending (this is a Telegram limitation).
@param string $caption <i>Optional</i>. Document caption (may also be used when resending documents by file_id), 0-200 characters.
@param string $reply_markup <i>Optional</i>. Reply markup of the message.
@param bool $disable_notification <i>Optional</i>. Sends the message silently.
@param int $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendSticker($sticker, string $reply_markup = null, bool $disable_notification = false, int $reply_to_message_id = null)
{
$this->parameters = [
'chat_id' => $this->chat_id,
'sticker' => $sticker,
'disable_notification' => $disable_notification,
'reply_to_message_id' => $reply_to_message_id,
'reply_markup' => $reply_markup
];
return $this->processRequest('sendSticker', 'Message');
} | \brief Send a sticker
\details Use this method to send .webp stickers. [API reference](https://core.telegram.org/bots/api/#sendsticker)
@param mixed $sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data.
@param string $reply_markup <i>Optional</i>. Reply markup of the message.
@param bool $disable_notification Sends the message silently.
@param int $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
@param bool On success, the sent message.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendVoice($voice, string $caption, int $duration, string $reply_markup = null, bool $disable_notification, int $reply_to_message_id = 0)
{
$this->_file->init($voice, 'voice');
$this->parameters = [
'chat_id' => $this->chat_id,
'caption' => $caption,
'duration' => $duration,
'disable_notification', $disable_notification,
'reply_to_message_id' => $reply_to_message_id,
'reply_markup' => $reply_markup
];
return $this->processRequest('sendVoice', 'Message', $this->checkCurrentFile());
} | \brief Send audio files.
\details Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).o
Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
@param mixed $voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or the local path of a voice to upload.
@param string $caption <i>Optional</i>. Voice message caption, 0-200 characters
@param int $duration <i>Optional</i>. Duration of the voice message in seconds
@param string $reply_markup <i>Optional</i>. Reply markup of the message.
@param bool $disable_notification <i>Optional</i>. Sends the message silently.
@param int $reply_to_message_id <i>Optional</i>. If the message is a reply, ID of the original message.
@return Message|false Message sent on success, false otherwise. | entailment |
public function sendChatAction(string $action) : bool
{
$parameters = [
'chat_id' => $this->chat_id,
'action' => $action
];
return $this->execRequest('sendChatAction?' . http_build_query($parameters));
} | \brief Say the user what action bot's going to do.
\details Use this method when you need to tell the user that something is happening on the bot's side.
The status is set for 5 seconds or less (when a message arrives from your bot,
Telegram clients clear its typing status). [API reference](https://core.telegram.org/bots/api#sendchataction)
@param string $action Type of action to broadcast. Choose one, depending on what the user is about to receive:
- <code>typing</code> for text messages
- <code>upload_photo</code> for photos
- <code>record_video</code> or <code>upload_video</code> for videos
- <code>record_audio</code> or <code>upload_audio</code> for audio files
- <code>upload_document</code> for general files
- <code>find_location</code> for location data
@return bool True on success. | entailment |
public function buildForm(FormBuilderInterface $builder, array $options)
{
$data = null;
// save origin value that was set as data
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use (&$data) {
$item = $event->getData();
$data = $item;
return;
});
// reorder if origin was array
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use (&$data){
$item = $event->getData();
if(is_array($data) && is_array($item)) {
$itemKeys = array_keys($item);
$copyValues = array_values($item);
sort($itemKeys);
$result = array();
for($i = 0; $i < count($itemKeys); $i++) {
$result[intval($itemKeys[$i])] = $copyValues[$i];
}
$event->setData($result);
}
return;
});
// reindex data, so array starts with index 0
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use (&$data){
$items = $event->getData();
if(is_array($data) && is_array($items)) {
$result = [];
$i = 0;
foreach($items as $item) {
$result[$i] = $item;
$i++;
}
$event->setData($result);
}
return;
});
} | {@inheritdoc} | entailment |
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['border'] = $options['border'];
$view->vars['sortable'] = $options['sortable'];
$view->vars['sortable_property'] = $options['sortable_property'];
$view->vars['allow_delete'] = $options['allow_delete'];
$view->vars['allow_add'] = $options['allow_add'];
$view->vars['block_name'] = $options['block_name'];
$lastIndex = null;
$array = $form->getData();
if ($array instanceof Collection) {
$array = $array->toArray();
}
if($array != null) {
end($array);
$lastIndex = key($array);
} else {
$lastIndex = -1;
}
$view->vars['index'] = $lastIndex+1;
$view->vars['prototype_name'] = $options['prototype_name'];
} | {@inheritdoc} | entailment |
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'border' => false,
'sortable' => false,
'sortable_property' => 'position',
'prototype' => true,
'allow_add' => true,
'by_reference' => false,
'allow_delete' => true
));
$resolver->setNormalizer('prototype_name', function(Options $options, $value) {
return '__' . uniqid() . '__';
});
} | Configures the options for this type.
@param OptionsResolver $resolver The resolver for the options. | entailment |
public function createView($options = []): View
{
$view = $this->create($options);
$requestConfiguration = $this->getRequestConfiguration($options);
// set template data
$parameters = new ParameterBag();
$this->buildTemplateParameters($parameters, $requestConfiguration, $options);
$templateVars = [];
foreach($parameters as $key => $value) {
$templateVars[$key] = $value;
}
$view->setTemplateData($templateVars);
// set template
if(isset($options['template'])) {
$view->setTemplate($this->resolveTemplate($requestConfiguration, $options));
}
return $view;
} | {@inheritdoc} | entailment |
public function configureOptions(OptionsResolver $optionsResolver)
{
$optionsResolver->setDefaults([
'translation_domain' => null,
'resource' => null,
'resources' => null,
'metadata' => null,
'template' => null,
'request_configuration' => null,
'request' => null,
]);
} | {@inheritdoc} | entailment |
public function load(array $config, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $config);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$this->registerResources('enhavo_shop', $config['driver'], $config['resources'], $container);
$container->setParameter('enhavo_shop.mailer.confirm', $config['mailer']['confirm']);
$container->setParameter('enhavo_shop.mailer.confirm.service', $config['mailer']['confirm']['service']);
$container->setParameter('enhavo_shop.mailer.tracking', $config['mailer']['tracking']);
$container->setParameter('enhavo_shop.mailer.tracking.service', $config['mailer']['tracking']['service']);
$container->setParameter('enhavo_shop.mailer.notification', $config['mailer']['notification']);
$container->setParameter('enhavo_shop.mailer.notification.service', $config['mailer']['notification']['service']);
$container->setParameter('enhavo_shop.document.billing', $config['document']['billing']); //Todo: Can be removed in next version
$container->setParameter('enhavo_shop.document.billing.generator', $config['document']['billing']['generator']);
$container->setParameter('enhavo_shop.document.billing.options', isset($config['document']['billing']['options']) ? $config['document']['billing']['options'] : []);
$container->setParameter('enhavo_shop.document.packing_slip', $config['document']['packing_slip']); //Todo: Can be removed in next version
$container->setParameter('enhavo_shop.document.packing_slip.generator', $config['document']['packing_slip']['generator']);
$container->setParameter('enhavo_shop.document.packing_slip.options', isset($config['document']['packing_slip']['options']) ? $config['document']['packing_slip']['options'] : []);
$container->setParameter('enhavo_shop.payment.paypal.logo', $config['payment']['paypal']['logo']);
$container->setParameter('enhavo_shop.payment.paypal.branding', $config['payment']['paypal']['branding']);
$configFiles = array(
'services/locale.yml',
// 'services/services.yml',
// 'services/order.yml',
// 'services/form.yml'
);
foreach ($configFiles as $configFile) {
$loader->load($configFile);
}
} | {@inheritdoc} | entailment |
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('quantity', TextType::class, [
'label' => 'order_item.form.label.quantity',
'translation_domain' => 'EnhavoShopBundle'
])
->add('product', EntityType::class, [
'class' => $this->productClass,
'choice_name' => 'title',
'label' => 'order_item.form.label.product',
'translation_domain' => 'EnhavoShopBundle'
])
->setDataMapper($this->orderItemQuantityDataMapper)
;
} | {@inheritdoc} | entailment |
public function addNode(Node $node)
{
$node->setNavigation($this);
$this->nodes[] = $node;
return $this;
} | Add nodes
@param Node $node
@return Navigation | entailment |
public function removeNode(Node $node)
{
$node->setNavigation(null);
$this->nodes->removeElement($node);
} | Remove nodes
@param Node $node | entailment |
public function setMagazine(\Enhavo\Bundle\ProjectBundle\Entity\Magazine $magazine = null)
{
$this->magazine = $magazine;
return $this;
} | Set magazine
@param \Enhavo\Bundle\ProjectBundle\Entity\Magazine $magazine
@return Content | entailment |
public function buildForm(FormBuilderInterface $builder, array $options)
{
$repository = $this->entityManager->getRepository($options['class']);
$propertyAccessor = $this->propertyAccessor;
if($options['multiple'] === true) {
$builder->addViewTransformer(new CallbackTransformer(
function ($originalDescription) use ($options, $propertyAccessor) {
$collection = new ArrayCollection();
if($originalDescription instanceof Collection) {
$collection = $originalDescription;
}
$data = [];
foreach($collection as $entry) {
if(!method_exists($entry, 'getId')) {
throw new \Exception('class need to be an entity with getId function');
}
$id = call_user_func([$entry, 'getId']);
if($options['choice_label'] instanceof \Closure) {
$label = $options['choice_label']($entry);
} elseif(is_string($options['choice_label'])) {
$label = $propertyAccessor->getValue($entry, $options['choice_label']);
} else {
$label = (string)$entry;
}
$data[] = [
'id' => $id,
'text' => $label
];
}
return $data;
},
function ($submittedDescription) use ($repository) {
$collection = new ArrayCollection();
if(empty($submittedDescription)) {
return $collection;
}
$ids = explode(',', $submittedDescription);
foreach($ids as $id) {
$collection->add($repository->find($id));
}
return $collection;
}
));
} else {
$builder->addViewTransformer(new CallbackTransformer(
function ($originalDescription) use ($options, $propertyAccessor) {
if($originalDescription !== null) {
if(!method_exists($originalDescription, 'getId')) {
throw new \Exception('class need to be an entity with getId function');
}
$id = call_user_func([$originalDescription, 'getId']);
if($options['choice_label'] instanceof \Closure) {
$label = $options['choice_label']($originalDescription);
} elseif(is_string($options['choice_label'])) {
$label = $propertyAccessor->getValue($originalDescription, $options['choice_label']);
} else {
$label = (string)$originalDescription;
}
return [
'id' => $id,
'text' => $label
];
}
return null;
},
function ($submittedDescription) use ($repository) {
if(empty($submittedDescription)) {
return null;
}
return $repository->find($submittedDescription);
}
));
}
} | {@inheritdoc} | entailment |
public function finishView(FormView $view, FormInterface $form, array $options)
{
$view->vars['auto_complete_data'] = [
'url' => $this->router->generate($options['route'], $options['route_parameters']),
'route' => $options['route'],
'route_parameters' => $options['route_parameters'],
'value' => $view->vars['value'],
'multiple' => $options['multiple'],
'minimum_input_length' => $options['minimum_input_length'],
'placeholder' => $options['placeholder'],
'id_property' => $options['id_property'],
'label_property' => $options['label_property'],
];
$view->vars['multiple'] = $options['multiple'];
$view->vars['create_route'] = $options['create_route'];
$view->vars['create_button_label'] = $options['create_button_label'];
if ($options['multiple'] === false) {
$value = $view->vars['value'];
if (is_object($value) && method_exists($value, 'getId')) {
$view->vars['value'] = $value->getId();
} elseif (is_array($value) && isset($value['id'])) {
$view->vars['value'] = $value['id'];
}
}
} | {@inheritdoc} | entailment |
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'choice_label' => function ($object) {
return (string)$object;
},
'route_parameters' => [],
'compound' => false,
'multiple' => false,
'minimum_input_length' => 0,
'placeholder' => null,
'create_route' => null,
'create_button_label' => null,
'id_property' => 'id',
'label_property' => null,
]);
$resolver->setRequired([
'route',
'class',
]);
} | {@inheritdoc} | entailment |
public function acquireLock($name, $timeout = null)
{
if (!$this->setupPDO($name)) {
return false;
}
return parent::acquireLock($name, $timeout);
} | Acquire lock
@param string $name name of lock
@param null|int $timeout 1. null if you want blocking lock
2. 0 if you want just lock and go
3. $timeout > 0 if you want to wait for lock some time (in milliseconds)
@return bool | entailment |
public function releaseLock($name)
{
if (!$this->setupPDO($name)) {
return false;
}
$released = (bool) $this->pdo[$name]->query(
sprintf(
'SELECT RELEASE_LOCK(%s)',
$this->pdo[$name]->quote($name)
),
PDO::FETCH_COLUMN,
0
)->fetch();
if (!$released) {
return false;
}
unset($this->pdo[$name]);
unset($this->locks[$name]);
return true;
} | Release lock
@param string $name name of lock
@return bool | entailment |
public function isLocked($name)
{
if (empty($this->pdo) && !$this->setupPDO($name)) {
return false;
}
return !current($this->pdo)->query(
sprintf(
'SELECT IS_FREE_LOCK(%s)',
current($this->pdo)->quote($name)
),
PDO::FETCH_COLUMN,
0
)->fetch();
} | Check if lock is locked
@param string $name name of lock
@return bool | entailment |
public function findNextInDateOrder(Content $currentContent, \DateTime $currentDate = null)
{
if (null === $currentDate) {
$currentDate = new \DateTime();
}
// Find contents with same date
$query = $this->createQueryBuilder('n');
$query->andWhere('n.public = true');
$query->andWhere('n.publicationDate <= :currentDate');
$query->andWhere('n.publicationDate = :contentDate');
$query->andWhere('n.publishedUntil >= :currentDate OR n.publishedUntil IS NULL');
$query->setParameter('currentDate', $currentDate);
$query->setParameter('contentDate', $currentContent->getPublicationDate());
$contentsSameDate = $query->getQuery()->getResult();
if (!empty($contentsSameDate) && !($contentsSameDate[0]->getId() == $currentContent->getId())) {
// Return previous in list
for($i = 0; $i < count($contentsSameDate); $i++) {
if ($contentsSameDate[$i]->getId() == $currentContent->getId()) {
return $contentsSameDate[$i - 1];
}
}
}
// No next one at current date, search for newer ones
$query = $this->createQueryBuilder('n');
$query->andWhere('n.public = true');
$query->andWhere('n.publicationDate <= :currentDate');
$query->andWhere('n.publicationDate > :contentDate');
$query->andWhere('n.publishedUntil >= :currentDate OR n.publishedUntil IS NULL');
$query->setParameter('currentDate', $currentDate);
$query->setParameter('contentDate', $currentContent->getPublicationDate());
$query->addOrderBy('n.publicationDate','asc');
$query->addOrderBy('n.id','desc');
$query->setMaxResults(1);
$nextContent = $query->getQuery()->getResult();
if (empty($nextContent)) {
// No newer contents
return null;
} else {
return $nextContent[0];
}
} | Returns the next published content in order if sorted by publication date.
Only returns contents that are published and whose publication date does not lie in the future.
The order used is the same as in findPublished().
@param Content $currentContent The current content
@param \DateTime $currentDate The date used to determine if a publication date lies in the future. If null or omitted, today is used.
@return null|Content The next content after $currentContent, or null if $currentContent is the last one. | entailment |
public function setGrid(GridInterface $grid = null)
{
$this->grid = $grid;
if($grid === null) {
$this->setItemType(null);
$this->setItemTypeId(null);
$this->setItemTypeClass(null);
}
return $this;
} | Set grid
@param GridInterface $grid
@return Item | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_app');
$rootNode
->children()
->scalarNode('translate')->defaultValue(false)->end()
->end()
->children()
->arrayNode('login')
->addDefaultsIfNotSet()
->children()
->scalarNode('route')->defaultValue('enhavo_dashboard_index')->end()
->scalarNode('route_parameters')->defaultValue([])->end()
->end()
->end()
->end()
->children()
->arrayNode('template')
->addDefaultsIfNotSet()
->children()
->scalarNode('base')->defaultValue('EnhavoAppBundle::base.html.twig')->end()
->scalarNode('dialog')->defaultValue('EnhavoAppBundle::dialog.html.twig')->end()
->scalarNode('theme_base')->defaultValue('EnhavoAppBundle:Theme:base.html.twig')->end()
->end()
->end()
->end()
->children()
->arrayNode('form_themes')
->prototype('scalar')->end()
->end()
->end()
->children()
->arrayNode('branding')
->addDefaultsIfNotSet()
->children()
->scalarNode('enable')->defaultValue(true)->end()
->scalarNode('enable_version')->defaultValue(true)->end()
->scalarNode('enable_created_by')->defaultValue(true)->end()
->scalarNode('logo')->defaultValue(null)->end()
->scalarNode('text')->defaultValue('enhavo is an open source content-management-system based on symfony and sylius.')->end()
->scalarNode('version')->defaultValue(EnhavoAppBundle::VERSION)->end()
->scalarNode('background_image')->defaultValue(null)->end()
->end()
->end()
->end()
->children()
->arrayNode('stylesheets')
->prototype('scalar')->end()
->end()
->end()
->children()
->arrayNode('javascripts')
->prototype('scalar')->end()
->end()
->end()
->children()
->arrayNode('apps')
->prototype('scalar')->end()
->end()
->end()
->children()
->variableNode('menu')->end()
->end()
->children()
->arrayNode('roles')
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('role')->end()
->scalarNode('label')->defaultValue('')->end()
->scalarNode('translationDomain')->defaultValue(null)->end()
->scalarNode('display')->defaultValue(true)->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function submitAction(Request $request)
{
$template = 'EnhavoSearchBundle:Admin:Search/result.html.twig';
$term = $request->get('q', '');
$filter = new Filter();
$filter->setTerm($term);
$results = $this->searchEngine->searchPaginated($filter);
$results = $this->resultConverter->convert($results, $term);
return $this->render($template, [
'results' => $results,
'term' => $term
]);
} | Handle search submit
@param Request $request
@return Response | entailment |
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->remove('staticPrefix');
$builder->add('staticPrefix', 'text', [
'translation' => $this->translation
]);
} | {@inheritdoc} | entailment |
public function init(string $file, string $format_name)
{
$this->file = $file;
$this->format_name = $format_name;
} | \brief Fill this object with another file.
@param string $file File_id or local/remote path to the file.
@param string $format_name Format name of the file (audio, document, ...) | entailment |
public function isLocal() : bool
{
$host = parse_url($this->file, PHP_URL_HOST);
// If it has not an url host
if ($host === null) {
// Is the string a file_id?
if (preg_match('/^([\w\d]*[-_]*[\w\d]*)*$/', $this->file)) {
// It is a file_id
return false;
}
// It is local
return true;
}
// It is an url
return false;
} | \brief (<i>Internal</i>) Check if the path to the file given is local or a file_id/url.
@return bool True if the file is a local path. | entailment |
public function get(bool $clear_keyboard = true) : string
{
if (empty($this->inline_keyboard)) {
throw new BotException("Inline keyboard is empty");
}
// Create a new array to put our buttons
$reply_markup = ['inline_keyboard' => $this->inline_keyboard];
$reply_markup = json_encode($reply_markup);
if ($clear_keyboard) {
$this->clearKeyboard();
}
return $reply_markup;
} | \brief Get a JSON object containing the inline keyboard.
@param bool $clear_keyboard Remove all the buttons from this object.
@return string JSON object. | entailment |
public function getArray(bool $clean_keyboard = true) : array
{
if (empty($this->inline_keyboard)) {
throw new BotException("Inline keyboard is empty");
}
// Create a new array to put the buttons
$reply_markup = ['inline_keyboard' => $this->inline_keyboard];
if ($clean_keyboard) {
$this->clearKeyboard();
}
return $reply_markup;
} | \brief Get the array containing the buttons.
\details Use this method when adding keyboard to inline query results.
@param bool $clean_keyboard If it's true, it'll clean the inline keyboard.
@return array An array containing the buttons. | entailment |
public function addLevelButtons(array ...$buttons)
{
// If the user has already added a button in this row
if ($this->column != 0) {
$this->nextRow();
}
// Add buttons to the next row
$this->inline_keyboard[] = $buttons;
$this->nextRow();
} | \brief Add buttons for the current row.
\details Each array sent as parameter requires a text key
and one another key
(see <a href="https://core.telegram.org/bots/api/#inlinekeyboardbutton" target="blank">here</a>)
like:
- url
- callback_data
- switch_inline_query
- switch_inline_query_current_chat
- callback_game
Each call to this function add one or more button to a row.
The next call add buttons on the next row.
There are twelve columns and eight buttons per row.
Let's see an example:
addLevelButtons(['text' => 'Click me!', 'url' => 'https://telegram.me']);
If you want to add more than a button:
addLevelButtons(['text' => 'Button 1', 'url' => 'https://telegram.me/gamedev_ita'], ['text' => 'Button 2', 'url' => 'https://telegram.me/animewallpaper']);
@param array ...$buttons One or more arrays which represents buttons. | entailment |
public function addButton(string $text, string $data_type, string $data)
{
// If we get the end of the row
if ($this->column == 8) {
$this->nextRow();
}
// Add the button
$this->inline_keyboard[$this->row][$this->column] = ['text' => $text, $data_type => $data];
$this->column++;
} | \brief Add a button.
\details The button will be added next to the last one or
in the next row if the bot has reached the limit of <b>buttons per row<b>.
Each row allows eight buttons per row and a maximum of twelve columns.
addButton('Click me!', 'url', 'https://telegram.me');
@param string $text Text showed on the button.
@param string $data_type The type of the button data.
Select one from these types.
- url
- callback_data
- switch_inline_query
- switch_inline_query_current_chat
- callback_game
@param string $data Data for the type selected. | entailment |
public function addListKeyboard(int $index, int $list, $prefix = 'list')
{
$buttons = [];
if (($list > 0) && ($index >= 0)) {
if ($index == 0) {
if ($list > 1) {
if ($list > 2) {
if ($list > 3) {
if ($list > 4) {
if ($list > 5) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4 ›',
'callback_data' => $prefix . '/4'
],
[
'text' => "$list ››",
'callback_data' => $prefix . "/$list"
]
];
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
],
[
'text' => '5',
'callback_data' => $prefix . '/5'
]
];
}
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
],
];
}
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
];
}
} elseif ($list == 2) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
];
}
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
]
];
}
} elseif ($index == 1) {
if ($list > 1) {
if ($list > 2) {
if ($list > 3) {
if ($list > 4) {
if ($list > 5) {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4 ›',
'callback_data' => $prefix . '/4'
],
[
'text' => "$list ››",
'callback_data' => $prefix . "/$list"
]
];
} else {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
],
[
'text' => '5',
'callback_data' => $prefix . '/5'
]
];
}
} else {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
]
];
}
} else {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
]
];
}
} elseif ($list == 2) {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
]
];
}
} else {
$buttons = [
[
'text' => '• 1 •',
'callback_data' => 'null'
]
];
}
} elseif ($index == 2) {
if ($list > 3) {
if ($list > 4) {
if ($list > 5) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '• 2 •',
'callback_data' => 'null'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4 ›',
'callback_data' => $prefix . '/4'
],
[
'text' => "$list ››",
'callback_data' => $prefix . "/$list"
]
];
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '• 2 •',
'callback_data' => 'null'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => '4'
],
[
'text' => '5',
'callback_data' => $prefix . '/5'
]
];
}
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '• 2 •',
'callback_data' => 'null'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
]
];
}
} elseif ($list == 3) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '• 2 •',
'callback_data' => 'null'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
]
];
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '• 2 •',
'callback_data' => 'null'
]
];
}
} elseif ($index == 3) {
if ($list > 4) {
if ($list > 5) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '• 3 •',
'callback_data' => 'null'
],
[
'text' => '4 ›',
'callback_data' => $prefix . '/4'
],
[
'text' => "$list ››",
'callback_data' => $prefix . "/$list"
]
];
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '• 3 •',
'callback_data' => 'null'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
],
[
'text' => '5',
'callback_data' => $prefix . '/5'
]
];
}
} elseif ($list == 4) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '• 3 •',
'callback_data' => 'null'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
]
];
} else {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '• 3 •',
'callback_data' => 'null'
]
];
}
} elseif ($index == 4 && $list <= 5) {
if ($list == 4) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '• 4 •',
'callback_data' => 'null'
]
];
} elseif ($list == 5) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '• 4 •',
'callback_data' => 'null'
],
[
'text' => '5',
'callback_data' => $prefix . '/5'
]
];
}
} elseif ($index == 5 && $list == 5) {
$buttons = [
[
'text' => '1',
'callback_data' => $prefix . '/1'
],
[
'text' => '2',
'callback_data' => $prefix . '/2'
],
[
'text' => '3',
'callback_data' => $prefix . '/3'
],
[
'text' => '4',
'callback_data' => $prefix . '/4'
],
[
'text' => '• 5 •',
'callback_data' => 'null'
]
];
} else {
if ($index < $list - 2) {
$indexm = $index - 1;
$indexp = $index + 1;
$buttons = [
[
'text' => '‹‹ 1',
'callback_data' => $prefix . '/1'
],
[
'text' => '‹ ' . $indexm,
'callback_data' => $prefix . '/' . $indexm
],
[
'text' => '• ' . $index . ' •',
'callback_data' => 'null',
],
[
'text' => $indexp . ' ›',
'callback_data' => $prefix . '/' . $indexp
],
[
'text' => $list . ' ››',
'callback_data' => $prefix . '/' . $list
]
];
} elseif ($index == ($list - 2)) {
$indexm = $index - 1;
$indexp = $index + 1;
$buttons = [
[
'text' => '‹‹1',
'callback_data' => $prefix . '/1'
],
[
'text' => '' . $indexm,
'callback_data' => $prefix . '/' . $indexm
],
[
'text' => '• ' . $index . ' •',
'callback_data' => 'null',
],
[
'text' => '' . $indexp,
'callback_data' => $prefix . '/' . $indexp
],
[
'text' => "$list",
'callback_data' => $prefix . "/$list"
]
];
} elseif ($index == ($list - 1)) {
$indexm = $index - 1;
$indexmm = $index - 2;
$buttons = [
[
'text' => '‹‹ 1',
'callback_data' => $prefix . '/1'
],
[
'text' => '‹ ' . $indexmm,
'callback_data' => $prefix . '/' . $indexmm
],
[
'text' => '' . $indexm,
'callback_data' => $prefix . '/' . $indexm
],
[
'text' => '• ' . $index . ' •',
'callback_data' => $prefix . '/' . $index
],
[
'text' => "$list",
'callback_data' => $prefix . "/$list"
]
];
} elseif ($index == $list) {
$indexm = $index - 1;
$indexmm = $index - 2;
$indexmmm = $index - 3;
$buttons = [
[
'text' => '‹‹ 1',
'callback_data' => $prefix . '/1'
],
[
'text' => '‹ ' . $indexmmm,
'callback_data' => $prefix . '/' . $indexmmm
],
[
'text' => '' . $indexmm,
'callback_data' => $prefix . '/' . $indexmm,
],
[
'text' => '' . $indexm,
'callback_data' => $prefix . '/' . $indexm
],
[
'text' => '• ' . $index . ' •',
'callback_data' => $prefix . '/' . $index
]
];
}
}
}
// If there are other buttons in this row (checking the column)
if ($this->column !== 0) {
// Go to the next
$this->nextRow();
}
$this->inline_keyboard[$this->row] = $buttons;
// We added a row
$this->nextRow();
} | \brief Add a list keyboard.
\details A list keyboard can be useful if you want separate
data in multiple "pages" and allows users to navigate it easily.
The keyboard is generated at runtime.
@param int $index The current index of the list.
@param int $list The length of the list.
@param string $prefix Prefix to add at each callback_data of the button. Eg.: 'list/1'. | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['data']['media'] = [
'items' => [],
'page' => 1,
'loading' => false,
'updateRoute' => 'enhavo_media_library_update'
];
$view->setTemplateData($templateVars);
return $view;
} | {@inheritdoc} | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->installDatabase($input, $output);
$this->insertUser($input, $output);
$this->createBundle($input, $output);
} | {@inheritdoc} | entailment |
private function isEmailValid($email)
{
$constraints = array(
new \Symfony\Component\Validator\Constraints\Email(),
new \Symfony\Component\Validator\Constraints\NotBlank()
);
$errors = $this->validator->validate($email, $constraints);
return count($errors) === 0;
} | Validate single email
@param string $email
@return boolean | entailment |
public function isPublished()
{
if($this->isPublic() === false) {
return false;
}
$now = new \DateTime();
if($now > $this->publicationDate) {
if($this->publishedUntil !== null && $now > $this->publishedUntil) {
return false;
}
return true;
}
return false;
} | {@inheritdoc} | entailment |
public function getTaxTotal()
{
$total = 0;
foreach($this->getUnits() as $unit) {
$adjustments = $unit->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT);
foreach($adjustments as $adjustment) {
$total += $adjustment->getAmount();
}
$adjustments = $unit->getAdjustments(AdjustmentInterface::TAX_PROMOTION_ADJUSTMENT);
foreach($adjustments as $adjustment) {
$total += $adjustment->getAmount();
}
}
return $total;
} | {@inheritdoc} | entailment |
public function addItem(ItemInterface $item)
{
$item->setGrid($this);
$this->items[] = $item;
return $this;
} | Add items
@param ItemInterface $item
@return Grid | entailment |
public function removeItem(ItemInterface $item)
{
$item->setGrid(null);
$this->items->removeElement($item);
} | Remove items
@param ItemInterface $item | entailment |
public function getStr($index)
{
if (!isset($this->language)) {
$this->getLanguageRedis();
}
$this->loadCurrentLocalization();
// Check if the requested string exists
if (isset($this->local[$this->language][$index])) {
return $this->local[$this->language][$index];
}
throw new BotException("Index '$index' is not set for {$this->language}");
} | \brief Get a localized string giving an index.
\details Using LocalizedString::language this method get the string of the index given localized string in language of the current user/group.
This method will load the language first, using PhpBotFramework\Localization\Language::getLanguage(), if the language has not been set.
If the localization file for the user/group language has not been load yet, it will load it (load only the single localization file if the bot is using webhook, load all otherwise).
@param string $index Index of the localized string to get.
@return string Localized string in the current user/group language. | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_navigation');
$rootNode
// Driver used by the resource bundle
->children()
->scalarNode('driver')->defaultValue('doctrine/orm')->end()
->end()
->children()
->arrayNode('resources')
->addDefaultsIfNotSet()
->children()
->arrayNode('navigation')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Navigation::class)->end()
->scalarNode('controller')->defaultValue(ResourceController::class)->end()
->scalarNode('repository')->defaultValue(NavigationRepository::class)->end()
->scalarNode('factory')->defaultValue(NavigationFactory::class)->end()
->scalarNode('form')->defaultValue(NavigationType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->arrayNode('node')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Node::class)->end()
->scalarNode('controller')->defaultValue(ResourceController::class)->end()
->scalarNode('repository')->defaultValue(NodeRepository::class)->end()
->scalarNode('factory')->defaultValue(Factory::class)->end()
->scalarNode('form')->defaultValue(NodeType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
->children()
->arrayNode('default')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Node::class)->end()
->scalarNode('form')->defaultValue(NodeType::class)->end()
->scalarNode('repository')->defaultValue(NodeRepository::class)->end()
->scalarNode('factory')->defaultValue(NodeFactory::class)->end()
->scalarNode('template')->defaultValue('@EnhavoNavigation/Form/node.html.twig')->end()
->end()
->end()
->end()
->children()
->arrayNode('render')
->addDefaultsIfNotSet()
->children()
->arrayNode('sets')
->useAttributeAsKey('name')
->prototype('array')
->useAttributeAsKey('name')
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->children()
->arrayNode('items')
->isRequired()
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('model')->end()
->scalarNode('form')->end()
->scalarNode('content_model')->end()
->scalarNode('configuration_form')->end()
->scalarNode('content_form')->end()
->scalarNode('repository')->end()
->scalarNode('label')->end()
->scalarNode('translationDomain')->end()
->scalarNode('type')->end()
->scalarNode('parent')->end()
->scalarNode('factory')->end()
->scalarNode('content_factory')->end()
->scalarNode('template')->end()
->scalarNode('render_template')->end()
->arrayNode('options')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
} | {@inheritDoc} | entailment |
public function addResult(array $result) : int
{
if (array_key_exists('type', $result) && ! in_array($result['type'], $this->accepted_type)) {
throw new BotException("Result has wrong or no type at all. Check that the result has a value of key 'type' that correspond to a type in the API Reference");
}
// Set the id of the result to add
$result['id'] = (string)$this->id_result;
$this->results[] = $result;
return $this->id_result++;
} | \brief Add a result passing an array containing data.
\details Create a result of one of these types:
- InlineQueryResultCachedAudio
- InlineQueryResultCachedDocument
- InlineQueryResultCachedGif
- InlineQueryResultCachedMpeg4Gif
- InlineQueryResultCachedPhoto
- InlineQueryResultCachedSticker
- InlineQueryResultCachedVideo
- InlineQueryResultCachedVoice
- InlineQueryResultArticle
- InlineQueryResultAudio
- InlineQueryResultContact
- InlineQueryResultGame
- InlineQueryResultDocument
- InlineQueryResultGif
- InlineQueryResultLocation
- InlineQueryResultMpeg4Gif
- InlineQueryResultPhoto
- InlineQueryResultVenue
- InlineQueryResultVideo
- InlineQueryResultVoice
To add a result, create an array containing data as showed on API Reference,
'id' parameter will be automatically genereted so there is no need to add it.
Example of adding an article result:
$data = [
'type' => 'result',
'title' => 'Example title',
'message_text' => 'Text of the message'
];
$handler->addResult($data);
@param array $result Array containing data result to add.
@return int Id of the result added. | entailment |
public function newArticle(
string $title,
string $message_text,
string $description = '',
array $reply_markup = null,
$parse_mode = 'HTML',
$disable_web_preview = false
) : int {
array_push($this->results, [
'type' => 'article',
'id' => (string)$this->id_result,
'title' => $title,
'message_text' => $message_text,
'description' => $description,
'parse_mode' => $parse_mode,
'reply_markup' => $reply_markup,
'disable_web_page_preview' => $disable_web_preview
]);
if ( is_null($reply_markup) ) {
unset( $this->results[ $this->id_result ]['reply_markup'] );
}
return $this->id_result++;
} | \brief Add a result of type Article.
\details Add a result that will be show to the user.
@param string $title Title of the result.
@param string $message_text Text of the message to be sent.
@param string $description <i>Optional</i>. Short description of the result
@param array $reply_markup Inline keyboard object.
Not JSON serialized, use getArray from InlineKeyboard class.
@param string $parse_mode <i>Optional</i>. Formattation style for the message.
@param string $disable_web_preview <i>Optional</i>. Disables link previews for
links in the sent message.
@return int Id the the article added. | entailment |
public function get()
{
$encoded_results = json_encode($this->results);
// Clear results by resetting ID counter and results' container
$this->results = [];
$this->id_result = 0;
return $encoded_results;
} | \brief Get all results created.
@return string JSON string containing the results. | entailment |
public function createAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::CREATE);
$newResource = $this->newResourceFactory->create($configuration, $this->factory);
$form = $this->resourceFormFactory->create($configuration, $newResource);
if ($request->isMethod('POST')) {
if($form->handleRequest($request)->isValid()) {
$newResource = $form->getData();
$this->appEventDispatcher->dispatchPreEvent(ResourceActions::CREATE, $configuration, $newResource);
$this->eventDispatcher->dispatchPreEvent(ResourceActions::CREATE, $configuration, $newResource);
$this->repository->add($newResource);
$this->appEventDispatcher->dispatchPreEvent(ResourceActions::CREATE, $configuration, $newResource);
$this->eventDispatcher->dispatchPostEvent(ResourceActions::CREATE, $configuration, $newResource);
$this->addFlash('success', $this->get('translator')->trans('form.message.success', [], 'EnhavoAppBundle'));
$route = $configuration->getRedirectRoute(null);
return $this->redirectToRoute($route, [
'id' => $newResource->getId(),
'tab' => $request->get('tab'),
'view_id' => $request->get('view_id')
]);
} else {
$this->addFlash('error', $this->get('translator')->trans('form.message.error', [], 'EnhavoAppBundle'));
foreach($form->getErrors() as $error) {
$this->addFlash('error', $error->getMessage());
}
}
}
$view = $this->viewFactory->create('create', [
'request_configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $newResource,
'form' => $form
]);
return $this->viewHandler->handle($configuration, $view);
} | {@inheritdoc} | entailment |
public function updateAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::UPDATE);
$resource = $this->findOr404($configuration);
$form = $this->resourceFormFactory->create($configuration, $resource);
$form->handleRequest($request);
if (in_array($request->getMethod(), ['POST', 'PUT', 'PATCH']) && $form->isSubmitted()) {
if($form->isValid()) {
$resource = $form->getData();
$this->appEventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
$this->eventDispatcher->dispatchPreEvent(ResourceActions::UPDATE, $configuration, $resource);
$this->manager->flush();
$this->appEventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
$this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);
$this->addFlash('success', $this->get('translator')->trans('form.message.success', [], 'EnhavoAppBundle'));
} else {
$this->addFlash('error', $this->get('translator')->trans('form.message.error', [], 'EnhavoAppBundle'));
foreach($form->getErrors() as $error) {
$this->addFlash('error', $error->getMessage());
}
}
}
$view = $this->viewFactory->create('update', [
'request_configuration' => $configuration,
'metadata' => $this->metadata,
'resource' => $resource,
'form' => $form
]);
return $this->viewHandler->handle($configuration, $view);
} | {@inheritdoc} | entailment |
public function tableAction(Request $request): Response
{
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::INDEX);
$resources = $this->resourcesCollectionProvider->get($configuration, $this->repository);
$view = $this->viewFactory->create('table', [
'request_configuration' => $configuration,
'metadata' => $this->metadata,
'resources' => $resources,
'request' => $request,
]);
$response = $this->viewHandler->handle($configuration, $view);
$response->headers->set('Content-Type', 'application/json');
return $response;
} | {@inheritdoc} | entailment |
public function listDataAction(Request $request): Response
{
$request->query->set('limit', 1000000); // never show pagination
$configuration = $this->requestConfigurationFactory->create($this->metadata, $request);
$this->isGrantedOr403($configuration, ResourceActions::INDEX);
if(in_array($request->getMethod(), ['POST'])) {
if ($configuration->isCsrfProtectionEnabled() && !$this->isCsrfTokenValid('list_data', $request->get('_csrf_token'))) {
throw new HttpException(Response::HTTP_FORBIDDEN, 'Invalid csrf token.');
}
$this->sortingManger->handleSort($request, $configuration, $this->repository);
return new JsonResponse();
}
$resources = $this->resourcesCollectionProvider->get($configuration, $this->repository);
$view = $this->viewFactory->create('list_data', [
'request_configuration' => $configuration,
'metadata' => $this->metadata,
'resources' => $resources,
'request' => $request,
]);
$response = $this->viewHandler->handle($configuration, $view);
$response->headers->set('Content-Type', 'application/json');
return $response;
} | {@inheritdoc} | entailment |
protected function isGrantedOr403(SyliusRequestConfiguration $configuration, string $permission): void
{
if (!$configuration->hasPermission()) {
$permission = $this->getRoleName($permission);
if (!$this->authorizationChecker->isGranted($configuration, $permission)) {
throw $this->createAccessDeniedException();
}
return;
}
$permission = $configuration->getPermission($permission);
if (!$this->authorizationChecker->isGranted($configuration, $permission)) {
throw $this->createAccessDeniedException();
}
return;
} | @param SyliusRequestConfiguration $configuration
@param string $permission
@throws AccessDeniedException | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['data']['url'] = $this->container->get('router')->generate($this->getResourcePreviewUrl($options));
$templateVars['data']['inputs'] = [];
$view->setTemplateData($templateVars);
return $view;
} | {@inheritdoc} | entailment |
public function process(OrderInterface $order)
{
if($order->getShippingState() === ShipmentInterface::STATE_SHIPPED && !$order->isTrackingMail()) {
$this->trackingMailer->sendMail($order);
$order->setTrackingMail(true);
}
} | {@inheritdoc} | entailment |
public function releaseLock($name)
{
if (isset($this->locks[$name])) {
rmdir($this->getDirectoryPath($name));
unset($this->locks[$name]);
return true;
}
return false;
} | Release lock
@param string $name name of lock
@return bool | entailment |
public function isLocked($name)
{
if ($this->acquireLock($name, false)) {
return !$this->releaseLock($name);
}
return true;
} | Check if lock is locked
@param string $name name of lock
@return bool | entailment |
public function addSlide(SlideInterface $slides)
{
$this->slides[] = $slides;
$slides->setSlider($this);
return $this;
} | Add slides
@param SlideInterface $slides
@return Slider | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_content');
$rootNode
->children()
->arrayNode('sitemap')
->children()
->arrayNode('collectors')
->useAttributeAsKey('name')
->prototype('variable')->end()
->end()
->end()
->end()
->end()
->children()
->scalarNode('driver')->defaultValue('doctrine/orm')->end()
->end()
->children()
->arrayNode('resources')
->addDefaultsIfNotSet()
->children()
->arrayNode('redirect')
->addDefaultsIfNotSet()
->children()
->variableNode('options')->end()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue(Redirect::class)->end()
->scalarNode('controller')->defaultValue(RedirectController::class)->end()
->scalarNode('repository')->defaultValue(RedirectRepository::class)->end()
->scalarNode('factory')->defaultValue(Factory::class)->end()
->scalarNode('form')->defaultValue(RedirectType::class)->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritdoc} | entailment |
public function getNbResults()
{
$queryBuilder = clone $this->queryBuilder;
return count($queryBuilder->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY));
} | {@inheritdoc} | entailment |
public function getSlice($offset, $length)
{
$queryBuilder = clone $this->queryBuilder;
$queryBuilder->setFirstResult($offset);
$queryBuilder->setMaxResults($length);
$rows = $queryBuilder->getQuery()->getResult(AbstractQuery::HYDRATE_ARRAY);
$result = [];
foreach($rows as $item) {
$result[] = $this->resolver->find($item['id'], $item['class']);
}
return $result;
} | {@inheritdoc} | entailment |
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['translation'] = isset($options['translation']) && $options['translation'] === true;
$view->vars['currentLocale'] = $this->defaultLocale;
if($view->vars['translation']) {
$parent = $form->getParent();
if($parent instanceof Form) {
$property = new Property($form->getPropertyPath());
$entity = $parent->getConfig()->getDataClass();
if(is_object($parent->getData())) {
$entity = $parent->getData();
}
$translations = $this->translator->getTranslationData($entity, $property);
if($translations === null) {
$view->vars['translation'] = false;
return;
}
$view->vars['translations'] = $translations;
}
}
} | Pass the image URL to the view
@param FormView $view
@param FormInterface $form
@param array $options | entailment |
public static function getHashtags(string $string) : array
{
if (preg_match_all("/(#\w+)/u", $string, $matches) != 0) {
$hashtagsArray = array_count_values($matches[0]);
$hashtags = array_keys($hashtagsArray);
}
return $hashtags ?? [];
} | \brief Get hashtag contained in a string.
\details Check hashtags in a string using a regular expression.
All valid hashtags will be returned in an array.
See the following [StackOverflow thread](http://stackoverflow.com/questions/3060601/retrieve-all-hashtags-from-a-tweet-in-a-php-function) to learn more.
@param $string The string to check for hashtags.
@return array An array of valid hashtags, can be empty. | entailment |
public static function camelCase($str, array $noStrip = [])
{
// Non-alpha and non-numeric characters become spaces.
$str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str);
$str = trim($str);
// Make each word's letter uppercase.
$str = ucwords($str);
$str = str_replace(" ", "", $str);
$str = lcfirst($str);
return $str;
} | \brief Convert a string into camelCase style.
\details Take a look [here](http://www.mendoweb.be/blog/php-convert-string-to-camelcase-string/)
to learn more.
@param string $str The string to convert.
@param array $noStrip
@return string $str The input string converted to camelCase. | entailment |
public static function removeUsernameFormattation(string $string, string $tag) : string
{
// Check if there are usernames in string using regex
if (preg_match_all('/(@\w+)/u', $string, $matches) != 0) {
$usernamesArray = array_count_values($matches[0]);
$usernames = array_keys($usernamesArray);
// Count how many username we've got
$count = count($usernames);
// Delimitator to make the formattation start
$delimitator_start = '<' . $tag . '>';
// and to make it end
$delimitator_end = '</' . $tag . '>';
// For each username
for ($i = 0; $i !== $count; $i++) {
// Put the Delimitator_end before the username and the start one after it
$string = str_replace($usernames[$i], $delimitator_end . $usernames[$i] . $delimitator_start, $string);
}
}
return $string;
} | \brief Remove HTML formattation from Telegram usernames.
\details Remove the $modificator html formattation from a message
containing Telegram usernames.
@param string $string to parse.
@param string $tag Formattation tag to remove.
@return string The string, modified if there are usernames. Otherwise $string. | entailment |
public function createResourceViewData(array $options, $item)
{
if ($item->getType() === Setting::SETTING_TYPE_TEXT) {
return $item->getValue();
}
if ($item->getType() === Setting::SETTING_TYPE_BOOLEAN) {
$booleanWidget = $this->container->get('enhavo_app.table.boolean');
$options['property'] = 'value';
return $booleanWidget->createResourceViewData($options, $item);
}
if ($item->getType() === Setting::SETTING_TYPE_FILE) {
$pictureWidget = $this->container->get('enhavo_media.table.picture_widget');
$options['property'] = 'file';
return $pictureWidget->createResourceViewData($options, $item);
}
if ($item->getType() === Setting::SETTING_TYPE_FILES) {
$pictureWidget = $this->container->get('enhavo_media.table.picture_widget');
$options['property'] = 'files';
return $pictureWidget->createResourceViewData($options, $item);
}
if ($item->getType() === Setting::SETTING_TYPE_WYSIWYG) {
return $item->getValue();
}
if ($item->getType() === Setting::SETTING_TYPE_DATE) {
$date = $item->getDate();
if($date instanceof \DateTime) {
return $date->format('d.m.y');
}
return '';
}
if ($item->getType() === Setting::SETTING_TYPE_DATETIME) {
$date = $item->getDate();
if($date instanceof \DateTime) {
return $date->format('d.m.y H:i');
}
return '';
}
return '';
} | @param array $options
@param Setting $item
@return mixed | entailment |
public function simplify($text)
{
//UTF-8
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// Lowercase
$text = mb_strtolower($text, 'UTF-8');
// To improve searching for numerical data such as dates, IP addresses
// or version numbers, we consider a group of numerical characters
// separated only by punctuation characters to be one piece.
// This also means that searching for e.g. '20/03/1984' also returns
// results with '20-03-1984' in them.
// Readable regexp: ([number]+)[punctuation]+(?=[number])
$text = preg_replace('/([' . $this->getClassNumbers() . ']+)[' . $this->getClassPunctuation() . ']+(?=[' . $this->getClassNumbers() . '])/u', '\1', $text);
// Multiple dot and dash groups are word boundaries and replaced with space.
// No need to use the unicode modifier here because 0-127 ASCII characters
// can't match higher UTF-8 characters as the leftmost bit of those are 1.
$text = preg_replace('/[.-]{2,}/', ' ', $text);
// The dot, underscore and dash are simply removed. This allows meaningful
// search behavior with acronyms and URLs. See unicode note directly above.
$text = preg_replace('/[._-]+/', '', $text);
// With the exception of the rules above, we consider all punctuation,
// marks, spacers, etc, to be a word boundary.
$text = preg_replace('/[' . $this->getClassWordBoundary() . ']+/u', ' ', $text);
return trim($text);
} | Simplifies and preprocesses text for searching.
Processing steps:
- Entities are decoded.
- Text is lower-cased and diacritics (accents) are removed.
- Punctuation is processed (removed or replaced with spaces, depending on
where it is; see code for details). | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('enhavo_media');
$rootNode
->children()
->arrayNode('formats')
->useAttributeAsKey('name')
->prototype('variable')->end()
->end()
->scalarNode('provider')->defaultValue('enhavo_media.provider.default_provider')->end()
->scalarNode('storage')->defaultValue('enhavo_media.storage.local_file_storage')->end()
->end()
->children()
->arrayNode('form')
->addDefaultsIfNotSet()
->children()
->scalarNode('parameters_type')->defaultValue(null)->end()
->end()
->end()
->end()
->children()
->arrayNode('filter')
->addDefaultsIfNotSet()
->children()
->arrayNode('video_image')
->addDefaultsIfNotSet()
->children()
->scalarNode('ffmpeg_path')->defaultValue('/usr/local/bin/ffmpeg')->end()
->scalarNode('ffprobe_path')->defaultValue('/usr/local/bin/ffprobe')->end()
->scalarNode('timeout')->defaultValue(3600)->end()
->scalarNode('ffmpeg_threads')->defaultValue(12)->end()
->end()
->end()
->arrayNode('image_compression')
->addDefaultsIfNotSet()
->children()
->scalarNode('optipng_path')->defaultValue('optipng')->end()
->scalarNode('jpegoptim_path')->defaultValue('jpegoptim')->end()
->scalarNode('svgo_path')->defaultValue('svgo')->end()
->scalarNode('gifsicle_path')->defaultValue('gifsicle')->end()
->scalarNode('pngquant_path')->defaultValue('pngquant')->end()
->end()
->end()
->end()
->end()
->end()
// Driver used by the resource bundle
->children()
->scalarNode('driver')->defaultValue('doctrine/orm')->end()
->end()
->children()
->arrayNode('resources')
->addDefaultsIfNotSet()
->children()
->arrayNode('file')
->addDefaultsIfNotSet()
->children()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue('Enhavo\Bundle\MediaBundle\Entity\File')->end()
->scalarNode('controller')->defaultValue(FileController::class)->end()
->scalarNode('repository')->defaultValue('Enhavo\Bundle\MediaBundle\Repository\FileRepository')->end()
->scalarNode('factory')->defaultValue('Enhavo\Bundle\MediaBundle\Factory\FileFactory')->end()
->scalarNode('form')->defaultValue('Enhavo\Bundle\MediaBundle\Factory\FileType')->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->arrayNode('format')
->addDefaultsIfNotSet()
->children()
->arrayNode('classes')
->addDefaultsIfNotSet()
->children()
->scalarNode('model')->defaultValue('Enhavo\Bundle\MediaBundle\Entity\Format')->end()
->scalarNode('controller')->defaultValue('Enhavo\Bundle\AppBundle\Controller\ResourceController')->end()
->scalarNode('repository')->defaultValue('Enhavo\Bundle\MediaBundle\Repository\FormatRepository')->end()
->scalarNode('factory')->defaultValue('Enhavo\Bundle\MediaBundle\Factory\FormatFactory')->end()
->scalarNode('form')->defaultValue('Enhavo\Bundle\MediaBundle\Factory\FormatType')->cannotBeEmpty()->end()
->end()
->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritDoc} | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$alreadyInDatabase = 0;
$addedToDatabase = 0;
foreach($this->translationStrings as $translationString) {
$exists = $this->repository->findBy(array(
'translationKey' => $translationString
));
if ($exists) {
$alreadyInDatabase++;
} else {
/** @var TranslationString $newEntity */
$newEntity = $this->factory->createNew();
$newEntity->setTranslationKey($translationString);
$newEntity->setTranslationValue('');
$this->em->persist($newEntity);
$addedToDatabase++;
}
}
if ($addedToDatabase > 0) {
$this->em->flush();
}
if (count($this->translationStrings) == 0) {
$output->writeln('No translation strings defined in configuration files.');
} else {
$output->writeln($addedToDatabase . ' new translation strings added to database, ' . $alreadyInDatabase . ' already set.');
}
} | {@inheritdoc} | entailment |
public function saveSubscriber(SubscriberInterface $subscriber)
{
$token = $this->getToken();
$groups = $subscriber->getGroups()->getValues();
$data = [
'postdata' => [
[
'email' => $subscriber->getEmail()
]
]
];
$event = new CleverReachEvent($subscriber, $data);
$this->eventDispatcher->dispatch(NewsletterEvents::EVENT_CLEVERREACH_PRE_SEND, $event);
if($event->getDataArray()){
$data = $event->getDataArray();
}
/** @var Group $group */
foreach ($groups as $group) {
if ($this->exists($subscriber->getEmail(), $group)) {
continue;
}
$groupId = $this->mapGroup($group);
$res = $this->guzzleClient->request('POST', 'groups.json/' . $groupId . '/receivers/insert' . '?token=' . $token, [
'json' => $data
]);
$response = $res->getBody()->getContents();
if (json_decode($response)[0]->status !== 'insert success') {
throw new InsertException(
sprintf('Insertion in group "%s" with id "%s" failed.', $group->getName(), $groupId)
);
}
}
} | @param SubscriberInterface $subscriber
@throws InsertException
@throws MappingException | entailment |
public function deleteFile(FileInterface $file)
{
$this->storage->deleteFile($file);
$this->formatManager->deleteFormats($file);
$this->em->remove($file);
$this->em->flush();
} | Deletes file and associated formats.
@param FileInterface $file | entailment |
public function saveFile(FileInterface $file)
{
$this->em->persist($file);
$this->em->flush();
$this->storage->saveFile($file);
} | Save file to system.
@param FileInterface $file | entailment |
public function releaseLock($name)
{
if (isset($this->locks[$name]) && $this->client->del($name)) {
unset($this->locks[$name]);
return true;
}
return false;
} | Release lock
@param string $name name of lock
@return bool | entailment |
public function create($name)
{
$this->checkName($name);
$configuration = new Configuration();
$configuration->setName($name);
$configuration->setModel($this->getParameter($name, 'model'));
$configuration->setForm($this->getParameter($name, 'form'));
$configuration->setFormTemplate($this->getParameter($name, 'template.form'));
$configuration->setRecipientTemplate($this->getParameter($name, 'template.recipient'));
$configuration->setRecipient($this->getParameter($name, 'recipient'));
$configuration->setConfirmTemplate($this->getParameter($name, 'template.confirm'));
$configuration->setPageTemplate($this->getParameter($name, 'template.page'));
$configuration->setFrom($this->getParameter($name, 'from'));
$configuration->setSenderName($this->getParameter($name, 'sender_name'));
$configuration->setSubject($this->getParameter($name, 'subject'));
$configuration->setTranslationDomain($this->getParameter($name, 'translation_domain'));
$configuration->setConfirmMail($this->getParameter($name, 'confirm_mail'));
return $configuration;
} | Create configuration
@param $name
@return Configuration | entailment |
public function addUser($chat_id) : bool
{
if (!isset($this->pdo)) {
throw new BotException("Database connection not set");
}
// Create insertion query and initialize variable
$query = "INSERT INTO $this->user_table ($this->id_column) VALUES (:chat_id)";
$sth = $this->pdo->prepare($query);
$sth->bindParam(':chat_id', $chat_id);
try {
$sth->execute();
$success = true;
} catch (\PDOException $e) {
echo $e->getMessage();
$success = false;
}
return $success;
} | \brief Add a user to the database.
\details Add a user to the database in Bot::$user_table table and Bot::$id_column column using Bot::$pdo connection.
@param string|int $chat_id chat ID of the user to add.
@return bool True on success. | entailment |
public function broadcastMessage(
string $text,
string $reply_markup = null,
string $parse_mode = 'HTML',
bool $disable_web_preview = true,
bool $disable_notification = false
) : int {
if (!isset($this->pdo)) {
throw new BotException("Database connection not set");
}
$sth = $this->pdo->prepare("SELECT $this->id_column FROM $this->user_table");
try {
$sth->execute();
} catch (\PDOException $e) {
echo $e->getMessage();
}
// Iterate over all the row got
while ($user = $sth->fetch()) {
$user_data = $this->getChat($user[$this->id_column]);
if ($user_data !== false) {
// Change the chat_id for the next API method
$this->bot->chat_id = $user[$this->id_column];
$this->bot->sendMessage($text, $reply_markup, null, $parse_mode, $disable_web_preview, $disable_notification);
}
// Wait after each message sent to avoid spamming
sleep(1);
}
return $sth->rowCount();
} | \brief Send a message to every user available on the database.
\details Send a message to all subscribed users, change Bot::$user_table and Bot::$id_column to match your database structure.
This method requires Bot::$pdo connection set.
All parameters are the same as CoreBot::sendMessage.
Because a limitation of Telegram Bot API the bot will have a delay after 20 messages sent in different chats.
@return int How many messages were sent.
@see CoreBot::sendMessage | entailment |
public function postLoad(LifecycleEventArgs $args)
{
$object = $args->getObject();
if(get_class($object) === $this->targetClass) {
$this->loadEntity($object);
}
} | Insert target class on load
@param $args LifecycleEventArgs | entailment |
public function preFlush(PreFlushEventArgs $args)
{
$uow = $args->getEntityManager()->getUnitOfWork();
$result = $uow->getIdentityMap();
if(isset($result[$this->targetClass])) {
foreach ($result[$this->targetClass] as $entity) {
$this->updateEntity($entity);
}
}
} | Update entity before flush to prevent a possible after flush
@param PreFlushEventArgs $args | entailment |
public function postFlush(PostFlushEventArgs $args)
{
$change = false;
$em = $args->getEntityManager();
$uow = $args->getEntityManager()->getUnitOfWork();
$result = $uow->getIdentityMap();
if(isset($result[$this->targetClass])) {
foreach ($result[$this->targetClass] as $entity) {
$updated = $this->updateEntity($entity);
if($updated) {
$change = true;
}
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$targetProperty = $propertyAccessor->getValue($entity, $this->targetProperty);
if($targetProperty && $uow->getEntityState($targetProperty) !== UnitOfWork::STATE_MANAGED) {
$em->persist($targetProperty);
$change = true;
}
}
}
if($change) {
$em->flush();
}
} | Check if entity is not up to date an trigger flush again if needed
@param PostFlushEventArgs $args | entailment |
private function updateEntity($entity)
{
$change = false;
$propertyAccessor = PropertyAccess::createPropertyAccessor();
$targetProperty = $propertyAccessor->getValue($entity, $this->targetProperty);
// if entity state is still proxy, we try to load its entity to make sure that target property is correct
if($entity instanceof Proxy && $targetProperty === null) {
$this->loadEntity($entity);
$targetProperty = $propertyAccessor->getValue($entity, $this->targetProperty);
}
if($targetProperty) {
// update id property
$idProperty = $propertyAccessor->getValue($entity, $this->idProperty);
$id = $propertyAccessor->getValue($targetProperty, 'id');
if($idProperty != $id) {
$propertyAccessor->setValue($entity, $this->idProperty, $id);
$change = true;
}
// update class property
$classProperty = $propertyAccessor->getValue($entity, $this->classProperty);
$class = $this->targetClassResolver->resolveClass($targetProperty);
if($classProperty != $class) {
$propertyAccessor->setValue($entity, $this->classProperty, $class);
$change = true;
}
} else {
if(null !== $propertyAccessor->getValue($entity, $this->idProperty)) {
$propertyAccessor->setValue($entity, $this->idProperty, null);
$change = true;
}
if(null !== $propertyAccessor->getValue($entity, $this->classProperty)) {
$propertyAccessor->setValue($entity, $this->classProperty, null);
$change = true;
}
}
return $change;
} | Update entity values
@param object $entity
@return boolean | entailment |
public function answerCallbackQuery($text = '', $show_alert = false, string $url = '') : bool
{
if (!isset($this->_callback_query_id)) {
throw new BotException("Callback query id not set, wrong update");
}
$parameters = [
'callback_query_id' => $this->_callback_query_id,
'text' => $text,
'show_alert' => $show_alert,
'url' => $url
];
return $this->execRequest('answerCallbackQuery?' . http_build_query($parameters));
} | \brief Answer a callback query.
\details Remove the 'updating' circle icon on an inline keyboard button showing a message/alert to the user.
It'll always answer the current callback query. [Api reference](https://core.telegram.org/bots/api#answercallbackquery)
@param string $text <i>Optional</i>. Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters.
@param bool $show_alert <i>Optional</i>. If true, an alert will be shown by the client instead of a notification at the top of the chat screen.
@param string $url <i>Optional</i>. URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button.
Otherwise, you may use links like telegram.me/your_bot?start=XXXX that open your bot with a parameter.
@return bool True on success. | entailment |
public function answerPreCheckoutQuery(bool $ok = true, string $error = null) {
if (!isset($this->_pre_checkout_query_id)) {
throw new BotException('Callback query ID not set, wrong update');
}
$parameters = [
'pre_checkout_query_id' => $this->_pre_checkout_query_id,
'ok' => $ok,
'error_message' => $error
];
return $this->execRequest('answerPreCheckoutQuery?' . http_build_query($parameters));
} | \brief Send an update once the user has confirmed their payment.
@param bool $ok True is everything is alright, elsewhere False.
@param string $error The error message if something went wrong.
@return bool True on success. | entailment |
public function answerShippingQuery(bool $ok = true, string $error = null, array $shipping_options) {
if (!isset($this->_shipping_query_id)) {
throw new BotException('Callback query ID not set, wrong update');
}
$parameters = [
'shipping_query_id' => $this->_shipping_query_id,
'ok' => $ok,
'error_message' => $error,
'shipping_options' => $this->generateShippingOptions($shipping_options)
];
return $this->execRequest('answerShippingQuery?' . http_build_query($parameters));
} | \brief Send an update once the user has confirmed their shipping details.
@param bool $ok True is everything is alright, elsewhere False.
@param string $error The error message if something went wrong.
@param array $shipping_options The various shipping options available.
For example: array('FedEx' => ['Dispatch' => 15.90, 'Italy Taxes' => 2.50])
@return bool True on success. | entailment |
private function generateShippingOptions(array $shipping_options) {
$response = [];
$option_index = 1;
foreach ($shipping_options as $option => $prices) {
array_push($response, ['id' => strval($option_index), 'title' => $option, 'prices' => []]);
// Register prices for the specific shipping option
foreach ($prices as $service => $price) {
if ($price < 0) {
throw new Exception('Invalid negative price passed to "answerShippingQuery"');
}
$formatted_price = intval($price * 100);
// Selects the most recent shipping option pushed into the array.
array_push($response[$option_index - 1]['prices'], [
'label' => $service, 'amount' => $formatted_price
]);
}
$option_index++;
}
return json_encode($response);
} | \brief Generate shipping options to pass to 'answerShippingQuery'.
@param array $shipping_options The various shipping options represented like PHP data types.
@return string A JSON string representation of the shipping options. | entailment |
public function answerInlineQuery(string $results = '', string $switch_pm_text = '', $switch_pm_parameter = '', bool $is_personal = true, int $cache_time = 300) : bool
{
if (!isset($this->_inline_query_id)) {
throw new BotException("Inline query id not set, wrong update");
}
$parameters = [
'inline_query_id' => $this->_inline_query_id,
'switch_pm_text' => $switch_pm_text,
'is_personal' => $is_personal,
'switch_pm_parameter' => $switch_pm_parameter,
'cache_time' => $cache_time
];
if (isset($results) && $results !== '') {
$parameters['results'] = $results;
}
return $this->execRequest('answerInlineQuery?' . http_build_query($parameters));
} | \brief Answer a inline query (when the user write @botusername "Query") with a button, that will make user switch to the
private chat with the bot, on the top of the results. [Api reference](https://core.telegram.org/bots/api#answerinlinequery)
@param string $results A JSON-serialized array of results for the inline query. Use PhpBotFramework\Entities\InlineQueryResult class to create and get them.
@param string $switch_pm_text If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter $switch_pm_parameter.
@param bool $is_personal Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.
@param int $cache_time The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.
@return bool True on success. | entailment |
public function findUser ($userId) {
$query = $this->database->pdo->prepare('SELECT username, points FROM users WHERE userId = :userId');
$query->bindParam(':userId', $userId);
$query->execute();
return (object) $query->fetch(PDO::FETCH_ASSOC);
} | Find the user by her user ID.
@param $userId The user ID.
@return object The user found. | entailment |
public function storeUserIfMissing ($message) {
$userId = $message['from']['id'];
$username = strtolower($message['from']['username']);
$query = $this->database->pdo->prepare('SELECT username FROM users WHERE userId = :userId');
$query->bindParam(':userId', $userId);
$query->execute();
$user = $query->fetch(PDO::FETCH_ASSOC) ?? false;
// If the user is not registered.
if (!$user) {
$query = $this->database->pdo->prepare('INSERT INTO users (userId, username, points) VALUES(:userId, :username, 0)');
$query->bindParam(':userId', $userId);
$query->bindParam(':username', $username);
$query->execute();
return;
}
// If the username changed.
if ($username !== $user['username']) {
$query = $this->database->pdo->prepare('UPDATE users SET username = :username WHERE userId = :userId');
$query->bindParam(':userId', $userId);
$query->bindParam(':username', $username);
$query->execute();
}
} | Checks if the user is already registered.
If yes, checks if her username is changed and update it.
Otherwise, register the new user.
@param $db The reference to the PDO object.
@param $message The incoming message.
@return void | entailment |
public function setActive($active)
{
$this->active = $active;
if($active && $this->activatedAt === null) {
$this->activatedAt = new \DateTime();
}
if(!$active) {
$this->activatedAt = null;
}
return $this;
} | Set active
@param boolean $active
@return Subscriber | entailment |
public function addGroup(\Enhavo\Bundle\NewsletterBundle\Entity\Group $group)
{
$this->group[] = $group;
return $this;
} | Add group
@param \Enhavo\Bundle\NewsletterBundle\Entity\Group $group
@return Subscriber | entailment |
public function removeGroup(\Enhavo\Bundle\NewsletterBundle\Entity\Group $group)
{
$this->group->removeElement($group);
} | Remove group
@param \Enhavo\Bundle\NewsletterBundle\Entity\Group $group | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.