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 . ' = :i... | \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_... | \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.
@... | 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->set... | \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 t... | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['form'] = $options['form'];
$templateVars['data'] = [
'messages' => $this->getFlashMessages(),
];
$templateVar... | {@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"');
}
... | \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',
... | \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-define... | 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... | \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' => $... | \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_... | 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_notificatio... | \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 me... | 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_mar... | \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.
@par... | 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_i... | \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 change... | 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' =>... | \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 fi... | 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,
... | \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 .we... | 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,
... | \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 5... | 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/bo... | 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... | {@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... | {@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,
... | 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, $opt... | {@inheritdoc} | entailment |
public function configureOptions(OptionsResolver $optionsResolver)
{
$optionsResolver->setDefaults([
'translation_domain' => null,
'resource' => null,
'resources' => null,
'metadata' => null,
'template' => null,
'request_configuration' ... | {@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'], $confi... | {@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:... | {@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(... | {@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_p... | {@inheritdoc} | entailment |
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'choice_label' => function ($object) {
return (string)$object;
},
'route_parameters' => [],
'compound' => false,
'multiple' => false,
... | {@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_... | 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)
),
... | 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... | 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 ... | 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()
->a... | {@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 = $t... | 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
... | \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_m... | \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 ... | \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
Eac... | 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];
... | \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... | 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 ... | \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 ... | entailment |
public function createView($options = []): View
{
$view = parent::createView($options);
$templateVars = $view->getTemplateData();
$templateVars['data']['media'] = [
'items' => [],
'page' => 1,
'loading' => false,
'updateRoute' => 'enhavo_media_... | {@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) ==... | 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;
}
... | {@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();
}
$... | {@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->lang... | \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... | 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()
... | {@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 Referenc... | \brief Add a result passing an array containing data.
\details Create a result of one of these types:
- InlineQueryResultCachedAudio
- InlineQueryResultCachedDocument
- InlineQueryResultCachedGif
- InlineQueryResultCachedMpeg4Gif
- InlineQueryResultCachedPhoto
- InlineQueryResultCachedSticker
- InlineQueryResultCachedV... | 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' ... | \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.
N... | 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);... | {@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->resourceFor... | {@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->reposit... | {@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_... | {@inheritdoc} | entailment |
protected function isGrantedOr403(SyliusRequestConfiguration $configuration, string $permission): void
{
if (!$configuration->hasPermission()) {
$permission = $this->getRoleName($permission);
if (!$this->authorizationChecker->isGranted($configuration, $permission)) {
... | @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'] = [];
... | {@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')
... | {@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($... | {@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-... | 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 $stri... | 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);
... | \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_ke... | \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.boole... | @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 ... | 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')->en... | {@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... | {@inheritdoc} | entailment |
public function saveSubscriber(SubscriberInterface $subscriber)
{
$token = $this->getToken();
$groups = $subscriber->getGroups()->getValues();
$data = [
'postdata' => [
[
'email' => $subscriber->getEmail()
]
]
... | @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... | 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 = ... | \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 n... | \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 Telegr... | 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->targetCla... | 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 targ... | 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... | \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 notificati... | 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,
... | \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_que... | \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... | 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 s... | \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");
}
$pa... | \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 qu... | 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 =... | 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.