sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getRespondentFields($requests)
{
$token = $this->token;
$results = [];
$respondent = $token->getRespondent();
foreach ($requests as $original => $upperField) {
switch ($upperField) {
case 'AGE':
$results[$original] = $respondent->getAge();
break;
case 'SEX':
$results[$original] = $respondent->getGender();
break;
case 'BIRTHDATE':
$birthDate = $respondent->getBirthday();
if (!is_null($birthDate) && $birthDate instanceof \MUtil_Date) {
$birthDate = $birthDate->get('yyyy-MM-dd');
$results[$original] = $birthDate;
}
break;
default:
break;
}
}
return $results;
} | Tries to fulfill request to respondent fields
@param array $requests
@return array | entailment |
public function getTrackFields($requests)
{
$token = $this->token;
$results = [];
// Read fieldcodes and convert to uppercase since requests are uppercase too
$respondentTrack = $token->getRespondentTrack();
$fieldCodes = $respondentTrack->getCodeFields();
$rawFieldData = $respondentTrack->getFieldData(); // Date (time) fields are unprocessed here
$keysMixed = array_keys($fieldCodes);
$keysUpper = array_change_key_case($fieldCodes, CASE_UPPER);
$fieldCodesMap = array_combine(array_keys($keysUpper), $keysMixed);
foreach ($requests as $original => $upperField) {
if (array_key_exists($upperField, $fieldCodesMap)) {
$trackField = $fieldCodesMap[$upperField];
$value = $fieldCodes[$trackField];
// If it is a date(/time) field export it in ISO format
if (array_key_exists($trackField, $rawFieldData) && $rawFieldData[$trackField] instanceof \MUtil_Date) {
$value = $rawFieldData[$trackField]->get('yyyy-MM-dd HH:mm:ss');
}
$results[$original] = $value;
}
}
return $results;
} | Tries to fulfill request to track fields
@param array $requests
@return array | entailment |
protected function performAction()
{
$data = $this->getModel()->loadFirst();
parent::performAction();
$this->accesslog->logChange($this->request, $this->getTitle(), $data);
} | Overrule this function if you want to perform a different
action than deleting when the user choose 'yes'. | entailment |
protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model)
{
$footer = $bridge->tfrow();
$footer[] = $this->getQuestion();
$footer[] = ' ';
$footer->actionLink(array($this->confirmParameter => 1), $this->_('Yes'));
$footer[] = ' ';
$footer->actionLink(array($this->request->getActionKey() => $this->abortAction), $this->_('No'));
} | Set the footer of the browse table.
Overrule this function to set the header differently, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_VerticalTableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@return void | entailment |
protected function addFormElements(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
{
$bridge->addHtml('to', 'label', $this->_('To'));
$bridge->addHtml('prefered_language', 'label', $this->_('Prefered Language'));
$bridge->addElement($this->mailElements->createTemplateSelectElement('select_template', $this->_('Template'),$this->mailTarget, $this->templateOnly, true));
if ($this->templateOnly) {
$bridge->addHidden('subject');
} else {
$bridge->addText('subject', 'label', $this->_('Subject'), 'size', 100);
}
$mailBody = $bridge->addElement($this->mailElements->createBodyElement('mailBody', $this->_('Message'), $model->get('gctt_body', 'required'), $this->templateOnly));
if ($mailBody instanceof \Gems_Form_Element_CKEditor) {
$mailBody->config['availablefields'] = $this->mailer->getMailFields();
$mailBody->config['availablefieldsLabel'] = $this->_('Fields');
$mailBody->config['extraPlugins'] .= ',availablefields';
$mailBody->config['toolbar'][] = array('availablefields');
}
if (!$this->templateOnly) {
$bridge->addFakeSubmit('preview', array('label' => $this->_('Preview')));
}
$bridge->addElement($this->createFromSelect('from', $this->_('From')));
$bridge->addElement($this->mailElements->createSubmitButton('send', $this->_('Send')));
$bridge->addElement($this->mailElements->createPreviewHtmlElement('Preview HTML'));
$bridge->addElement($this->mailElements->createPreviewTextElement('Preview Text'));
if (!$this->templateOnly) {
$bridge->addHtml('available_fields', array('label' => $this->_('Available fields')));
}
} | Adds elements from the model to the bridge that creates the form.
Overrule this function to add different elements to the browse table, without
having to recode the core table building code.
@param \MUtil_Model_Bridge_FormBridgeInterface $bridge
@param \MUtil_Model_ModelAbstract $model | entailment |
protected function createMultiOption(array $requestData, $name, $email, $extra = null, $disabledTitle = false, $menuFind = false)
{
return $this->mailElements->getEmailOption($requestData, $name, $email, $extra, $disabledTitle, $menuFind);
} | Create the option values with links for the select
@param array $requestData Needed for the links
@param string $name Sender name
@param string $email Sender Email
@param string $extra Extra info after the mail address
@param boolean $disabledTitle Is the link disabled
@param boolean $menuFind Find the url in the menu?
@return string Options | entailment |
protected function createFromSelect($elementName='from', $label='')
{
$valid = array();
$invalid = array();
$organization = $this->mailer->getOrganization();
// The organization
$key = 'organization';
if ($name = $organization->getContactName()) {
$extra = $organization->getName();
} else {
$name = $organization->getName();
$extra = null;
}
if ($email = $organization->getEmail()) {
$title = false;
$valid[] = $key;
} else {
$title = $this->_('Organization does not have an e-mail address.');
$invalid[] = $key;
}
$options[$key] = $this->createMultiOption(array(\MUtil_Model::REQUEST_ID => $organization->getId()),
$name, $email, $extra, $title,
array('controller' => 'organization', 'action' => 'edit'));
$this->fromOptions[$key] = $email;//$name . ' <' . $email . '>';
// The user
$key = 'user';
$name = $this->currentUser->getFullName();
$extra = null;
if ($email = $this->currentUser->getEmailAddress()) {
$title = false;
$valid[] = $key;
} else {
$title = $this->_('You do not have an e-mail address.');
$invalid[] = $key;
}
$options[$key] = $this->createMultiOption(array(),
$name, $email, $extra, $title,
array('controller' => 'option', 'action' => 'edit'));
$this->fromOptions[$key] = $email;//$name . ' <' . $email . '>';
// As "the" application
$key = 'application';
$user = $this->loader->getCurrentUser();
if ($user->hasPrivilege('pr.plan.mail-as-application') &&
isset($this->project->email['site'])) {
if ($email = $this->project->email['site']) {
$options['application'] = $this->createMultiOption(array(), $this->project->name, $email);
$valid[] = 'application';
$this->fromOptions[$key] = $email;//$this->project->name . ' <' . $email . '>';
}
}
$firstSelectable = reset($valid);
$element = $this->form->createElement('radio', $elementName, array(
'disable' => $invalid,
'escape' => (!$this->view),
'label' => $label,
'multiOptions' => $options,
'required' => true,
'value' => $firstSelectable,
));
$element->addValidator('InArray', false, array('haystack' => $valid));
return $element;
} | Create the options for the Select | entailment |
public function getHtmlOutput(\Zend_View_Abstract $view)
{
// If there is data, populate
if (!empty($this->formData)) {
$this->form->populate($this->formData);
}
if ($this->mailer->bounceCheck()) {
$this->addMessage($this->_('On this test system all mail will be delivered to the from address.'));
}
$this->beforeDisplay();
$htmlDiv = \MUtil_Html::div();
$htmlDiv->h3($this->getTitle());
$htmlDiv[] = $this->form;
return $htmlDiv;
} | Create the snippets content
This is a stub function either override getHtmlOutput() or override render()
@param \Zend_View_Abstract $view Just in case it is needed here
@return \MUtil_Html_HtmlInterface Something that can be rendered | entailment |
protected function getModel()
{
if (! $this->model) {
$this->model = $this->createModel();
$this->prepareModel($this->model);
}
return $this->model;
} | Returns the model, always use this function
@return \MUtil_Model_ModelAbstract | entailment |
public function hasHtmlOutput()
{
if (parent::hasHtmlOutput()) {
if ($this->mailer->getDataLoaded()) {
return $this->processForm();
} else {
$this->addMessage($this->mailer->getMessages());
return true;
}
}
} | The place to check if the data set in the snippet is valid
to generate the snippet.
When invalid data should result in an error, you can throw it
here but you can also perform the check in the
checkRegistryRequestsAnswers() function from the
{@see \MUtil_Registry_TargetInterface}.
@return boolean | entailment |
protected function loadForm()
{
$form = $this->createForm();
$bridge = $this->model->getBridgeFor('form', $form);
$this->addFormElements($bridge, $this->model);
$this->form = $bridge->getForm();
} | Makes sure there is a form. | entailment |
protected function loadFormData()
{
$presetTargetData = $this->mailer->getPresetTargetData();
if ($this->request->isPost()) {
$requestData = $this->request->getPost();
foreach($requestData as $key=>$value) {
if (!is_array($value)) {
$this->formData[$key] = htmlspecialchars($value);
} else {
$this->formData[$key] = array_map('htmlspecialchars', $value);
}
}
}
if (empty($this->formData['preview']) && !isset($this->formData['send'])) {
if (isset($this->formData['select_template']) && !empty($this->formData['select_template'])) {
if ($template = $this->mailer->getTemplate($this->formData['select_template'])) {
$this->formData['subject'] = $template['gctt_subject'];
$this->formData['mailBody'] = $template['gctt_body'];
}
}
}
$this->formData['available_fields'] = $this->mailElements->displayMailFields($this->mailer->getMailFields());
if (!empty($this->formData['subject']) || !empty($this->formData['mailBody'])) {
$content = '[b]';
$content .= $this->_('Subject:');
$content .= '[/b] [i]';
$content .= $this->mailer->applyFields($this->formData['subject']);
$content .= "[/i]\n\n";
$content .= $this->mailer->applyFields($this->formData['mailBody']);
} else {
$content = ' ';
}
$htmlView = \MUtil_Html::create()->div();
$textView = \MUtil_Html::create()->div();
$htmlView->div(array('class' => 'mailpreview'))->raw(\MUtil_Markup::render($content, 'Bbcode', 'Html'));
$textView->pre(array('class' => 'mailpreview'))->raw(\MUtil_Markup::render($content, 'Bbcode', 'Text'));
$this->formData['preview_html'] = $htmlView;
$this->formData['preview_text'] = $textView;
$this->formData = array_merge($this->formData, $presetTargetData);
} | Hook that loads the form data from $_POST or the model
Or from whatever other source you specify here. | entailment |
protected function setAfterSendRoute()
{
if ($this->routeAction && ($this->request->getActionName() !== $this->routeAction)) {
$this->afterSendRouteUrl = array('action' => $this->routeAction);
$keys = $this->model->getKeys();
if (count($keys) == 1) {
$key = reset($keys);
if (isset($this->formData[$key])) {
$this->afterSendRouteUrl[\MUtil_Model::REQUEST_ID] = $this->formData[$key];
}
} else {
$i = 1;
foreach ($keys as $key) {
if (isset($this->formData[$key])) {
$this->afterSendRouteUrl[\MUtil_Model::REQUEST_ID . $i] = $this->formData[$key];
}
$i++;
}
}
$this->afterSendRouteUrl['controller'] = $this->request->getControllerName();
$find['action'] = $this->afterSendRouteUrl['action'];
$find['controller'] = $this->afterSendRouteUrl['controller'];
if (null == $this->menu->find($find)) {
$this->afterSendRouteUrl['action'] = 'index';
$this->resetRoute = true;
}
}
} | Set the route destination after the mail is sent | entailment |
public function delete($filter = true, $saveTables = null)
{
$deleted = 0;
// If we update a field instead of really deleting we don't delete the related record
if (!$this->_deleteValues) {
$saveTables = $this->_checkSaveTables($saveTables);
$filter = $this->_checkFilterUsed($filter);
if (array_key_exists('gct_id_template', $filter)) {
$id = $filter['gct_id_template'];
}
}
$deleted = parent::delete($filter, $saveTables);
// If we had an ID and the result was that we deleted something, propagate to the other model
if ($id > 0 && $deleted > 0) {
$model = new \MUtil_Model_TableModel('gems__comm_template_translations');
$model->delete(['gctt_id_template' => $id]);
}
return $deleted;
} | Delete items from the model
The filter is propagated using over $this->_joinFields.
Table rows are only deleted when there exists a value in the filter for
ALL KEY FIELDS of that table. In other words: a partial key is not enough
to actually delete an item.
@param mixed $filter True to use the stored filter, array to specify a different filter
@return int The number of items deleted | entailment |
public function filterAnswers(\MUtil_Model_Bridge_TableBridge $bridge, \MUtil_Model_ModelAbstract $model, array $currentNames)
{
return $this->restoreHeaderPositions($model, array_reverse($currentNames));
} | This function is called in addBrowseTableColumns() to filter the names displayed
by AnswerModelSnippetGeneric.
@see \Gems_Tracker_Snippets_AnswerModelSnippetGeneric
@param \MUtil_Model_Bridge_TableBridge $bridge
@param \MUtil_Model_ModelAbstract $model
@param array $currentNames The current names in use (allows chaining)
@return array Of the names of labels that should be shown | entailment |
public function boot()
{
if (config('smsir.panel-routes', true)) {
// the main router
include_once __DIR__.'/routes.php';
}
// the main views folder
$this->loadViewsFrom(__DIR__.'/views', 'smsir');
// the main migration folder for create smsir tables
// for publish the views into main app
$this->publishes([
__DIR__.'/views' => resource_path('views/vendor/smsir'),
]);
$this->publishes([
__DIR__.'/migrations/' => database_path('migrations')
], 'migrations');
// for publish the assets files into main app
$this->publishes([
__DIR__.'/assets' => public_path('vendor/smsir'),
], 'public');
// for publish the smsir config file to the main app config folder
$this->publishes([
__DIR__.'/config/smsir.php' => config_path('smsir.php'),
]);
} | Bootstrap the application services.
@return void | entailment |
public function startQuery($sql, array $params = null, array $types = null)
{
if (null !== $this->stopwatch) {
$tags = array(
'server' => $this->databaseHost ?: (isset($_SERVER['HOSTNAME']) ? $_SERVER['HOSTNAME'] : ''),
);
if (preg_match('/^\s*(\w+)\s/u', $sql, $matches)) {
$tags['group'] = 'doctrine::' . strtolower($matches[1]);
}
else {
$tags['group'] = 'doctrine::';
}
$this->stopwatchEvent = $this->stopwatch->start($tags);
}
} | {@inheritdoc} | entailment |
public function stopQuery()
{
if (null !== $this->stopwatchEvent) {
$this->stopwatchEvent->stop();
$this->stopwatchEvent = null;
}
} | {@inheritdoc} | entailment |
public function shorten($num) {
$str = '';
while ($num > 0) {
$str = $this->alphabet[($num % $this->base)] . $str;
$num = (int) ($num / $this->base);
}
return $str;
} | Converts the specified integer ID to a short string
This is done by performing a (bijective) base conversion
@param int $num the integer ID to convert
@return string the short string | entailment |
public function unshorten($str) {
$num = 0;
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$num = $num * $this->base + strpos($this->alphabet, $str[$i]);
}
return $num;
} | Converts the specified short string to an integer ID
This is done by performing a (bijective) base conversion
@param string $str the short string to convert
@return int the integer ID | entailment |
public function index() {
$credit = Smsir::credit();
$smsir_logs = SmsirLogs::orderBy('id','DESC')->paginate(config('smsir.in-page'));
return view('smsir::index',compact('credit','smsir_logs'));
} | the main index page for administrators | entailment |
public function tag_add($tag, $key)
{
if ($this->stopwatch) {
$e = $this->getStopwatchEvent('tag_add');
}
$result = parent::tag_add($tag, $key);
if ($this->stopwatch) {
$e->stop();
}
return $result;
} | -------------------------- | entailment |
public static function DBlog($result, $messages, $numbers) {
if(config('smsir.db-log')) {
$res = json_decode($result->getBody()->getContents(),true);
if(count($messages) === 1) {
foreach ( $numbers as $number ) {
SmsirLogs::create( [
'response' => $res['Message'],
'message' => $messages[0],
'status' => $res['IsSuccessful'],
'from' => config('smsir.line-number'),
'to' => $number,
]);
}
} else {
foreach ( array_combine( $messages, $numbers ) as $message => $number ) {
SmsirLogs::create( [
'response' => $res['Message'],
'message' => $message,
'status' => $res['IsSuccessful'],
'from' => config('smsir.line-number'),
'to' => $number,
]);
}
}
}
} | This method used for log the messages to the database if db-log set to true (@ smsir.php in config folder).
@param $result
@param $messages
@param $numbers
@internal param bool $addToCustomerClub | set to true if you want to log another message instead main message | entailment |
public static function getToken()
{
$client = new Client();
$body = ['UserApiKey'=>config('smsir.api-key'),'SecretKey'=>config('smsir.secret-key'),'System'=>'laravel_v_1_4'];
$result = $client->post('http://restfulsms.com/api/Token',['json'=>$body,'connect_timeout'=>30]);
return json_decode($result->getBody(),true)['TokenKey'];
} | this method used in every request to get the token at first.
@return mixed - the Token for use api | entailment |
public static function credit()
{
$client = new Client();
$result = $client->get('http://restfulsms.com/api/credit',['headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
return json_decode($result->getBody(),true)['Credit'];
} | this method return your credit in sms.ir (sms credit, not money)
@return mixed - credit | entailment |
public static function send($messages,$numbers,$sendDateTime = null)
{
$client = new Client();
$messages = (array)$messages;
$numbers = (array)$numbers;
if($sendDateTime === null) {
$body = ['Messages'=>$messages,'MobileNumbers'=>$numbers,'LineNumber'=>config('smsir.line-number')];
} else {
$body = ['Messages'=>$messages,'MobileNumbers'=>$numbers,'LineNumber'=>config('smsir.line-number'),'SendDateTime'=>$sendDateTime];
}
$result = $client->post('http://restfulsms.com/api/MessageSend',['json'=>$body,'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
self::DBlog($result,$messages,$numbers);
return json_decode($result->getBody(),true);
} | Simple send message with sms.ir account and line number
@param $messages = Messages - Count must be equal with $numbers
@param $numbers = Numbers - must be equal with $messages
@param null $sendDateTime = don't fill it if you want to send message now
@return mixed, return status | entailment |
public static function addToCustomerClub($prefix,$firstName,$lastName,$mobile,$birthDay = '',$categotyId = '')
{
$client = new Client();
$body = ['Prefix'=>$prefix,'FirstName'=>$firstName,'LastName'=>$lastName,'Mobile'=>$mobile,'BirthDay'=>$birthDay,'CategoryId'=>$categotyId];
$result = $client->post('http://restfulsms.com/api/CustomerClubContact',['json'=>$body,'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
$res = json_decode($result->getBody()->getContents(),true);
self::DBlog($res,"افزودن $firstName $lastName به مخاطبین باشگاه ",$mobile);
return json_decode($result->getBody(),true);
} | add a person to the customer club contacts
@param $prefix = mr, dr, dear...
@param $firstName = first name of this contact
@param $lastName = last name of this contact
@param $mobile = contact mobile number
@param string $birthDay = birthday of contact, not require
@param string $categotyId = which category id of your customer club to join this contact?
@return \Psr\Http\Message\ResponseInterface = $result as json | entailment |
public static function sendToCustomerClub($messages,$numbers,$sendDateTime = null,$canContinueInCaseOfError = true)
{
$client = new Client();
$messages = (array)$messages;
$numbers = (array)$numbers;
if($sendDateTime !== null) {
$body = ['Messages'=>$messages,'MobileNumbers'=>$numbers,'SendDateTime'=>$sendDateTime,'CanContinueInCaseOfError'=>$canContinueInCaseOfError];
} else {
$body = ['Messages'=>$messages,'MobileNumbers'=>$numbers,'CanContinueInCaseOfError'=>$canContinueInCaseOfError];
}
$result = $client->post('http://restfulsms.com/api/CustomerClub/Send',['json'=>$body,'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
self::DBlog($result,$messages,$numbers);
return json_decode($result->getBody(),true);
} | this method send message to your customer club contacts (known as white sms module)
@param $messages
@param $numbers
@param null $sendDateTime
@param bool $canContinueInCaseOfError
@return \Psr\Http\Message\ResponseInterface | entailment |
public static function addContactAndSend($prefix,$firstName,$lastName,$mobile,$message,$birthDay = '',$categotyId = '')
{
$client = new Client();
$body = ['Prefix'=>$prefix,'FirstName'=>$firstName,'LastName'=>$lastName,'Mobile'=>$mobile,'BirthDay'=>$birthDay,'CategoryId'=>$categotyId,'MessageText'=>$message];
$result = $client->post('http://restfulsms.com/api/CustomerClub/AddContactAndSend',['json'=>[$body],'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
self::DBlog($result,$message,$mobile);
return json_decode($result->getBody(),true);
} | this method add contact to the your customer club and then send a message to him/her
@param $prefix
@param $firstName
@param $lastName
@param $mobile
@param $message
@param string $birthDay
@param string $categotyId
@return mixed | entailment |
public static function sendVerification($code,$number,$log = false)
{
$client = new Client();
$body = ['Code'=>$code,'MobileNumber'=>$number];
$result = $client->post('http://restfulsms.com/api/VerificationCode',['json'=>$body,'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
if($log) {
self::DBlog($result,$code,$number);
}
return json_decode($result->getBody(),true);
} | this method send a verification code to your customer. need active the module at panel first.
@param $code
@param $number
@param bool $log
@return mixed | entailment |
public static function getReceivedMessages($perPage,$pageNumber,$formDate,$toDate)
{
$client = new Client();
$result = $client->get("http://restfulsms.com/api/ReceiveMessage?Shamsi_FromDate={$formDate}&Shamsi_ToDate={$toDate}&RowsPerPage={$perPage}&RequestedPageNumber={$pageNumber}",['headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
return json_decode($result->getBody()->getContents())->Messages;
} | this method used for fetch received messages
@param $perPage
@param $pageNumber
@param $formDate
@param $toDate
@return mixed | entailment |
public static function deleteContact($mobile) {
$client = new Client();
$body = ['Mobile' => $mobile, 'CanContinueInCaseOfError' => false];
$result = $client->post('http://restfulsms.com/api/UltraFastSend',['json'=>$body,'headers'=>['x-sms-ir-secure-token'=>self::getToken()],'connect_timeout'=>30]);
return json_decode($result->getBody(),true);
} | @param $mobile = The mobile number of that user who you wanna to delete it
@return mixed = the result | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($this->validator()->fails()) {
$this->error($this->formatErrors());
// Exit with status code 1
return 1;
}
return parent::execute($input, $output);
} | Execute the console command.
@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return mixed | entailment |
protected function validator() : Validator
{
if (isset($this->validator)) {
return $this->validator;
}
return $this->validator = $this->laravel['validator']->make(
$this->getDataToValidate(),
$this->rules(),
$this->messages(),
$this->attributes()
);
} | Retrieve the command input validator
@return \Illuminate\Contracts\Validation\Validator | entailment |
protected function getDataToValidate() : array
{
$data = array_merge($this->argument(), $this->option());
return array_filter($data, function ($value) {
return $value !== null;
});
} | Retrieve the data to validate
@return array | entailment |
protected function formatErrors() : string
{
$errors = implode(PHP_EOL, $this->getErrorMessages());
return PHP_EOL . PHP_EOL . $errors . PHP_EOL;
} | Format the validation errors
@return string | entailment |
public function handle(ServerRequestInterface $request)
{
$actor = $request->getAttribute('actor');
if ($actor !== null && $actor->isAdmin()) {
$data = array_get($request->getParsedBody(), 'data', []);
if ($data['forAll']) {
$users = $this->users->query()->whereVisibleTo($actor)->get();
foreach ($users as $user) {
$this->sendMail($user->email, $data['subject'], $data['text']);
}
} else {
foreach ($data['emails'] as $email) {
$this->sendMail($email, $data['subject'], $data['text']);
}
}
}
return new EmptyResponse;
} | {@inheritdoc}
@throws \InvalidArgumentException | entailment |
public function boot()
{
$this->package('bradleyboy/laravel-braintree');
Braintree_Configuration::environment(
$this->app['config']->get('laravel-braintree::braintree.environment')
);
Braintree_Configuration::merchantId(
$this->app['config']->get('laravel-braintree::braintree.merchantId')
);
Braintree_Configuration::publicKey(
$this->app['config']->get('laravel-braintree::braintree.publicKey')
);
Braintree_Configuration::privateKey(
$this->app['config']->get('laravel-braintree::braintree.privateKey')
);
$encryptionKey = $this->app['config']->get('laravel-braintree::braintree.clientSideEncryptionKey');
// Register blade compiler for the Stripe publishable key.
$blade = $this->app['view']->getEngineResolver()->resolve('blade')->getCompiler();
$blade->extend(function($value, $compiler) use($encryptionKey)
{
$matcher = "/(?<!\w)(\s*)@braintreeClientSideEncryptionKey/";
return preg_replace($matcher, $encryptionKey, $value);
});
} | Bootstrap the application events.
@return void | entailment |
public function handle(): void
{
$this->info('Crafting application..');
$this->composer->createProject(
'laravel-zero/laravel-zero',
$this->argument('name'),
['--prefer-dist']
);
$this->comment('Application ready! Build something amazing.');
} | Execute the command. Here goes the code.
@return void | entailment |
public function render($name, array $parameters = array())
{
$e = $this->stopwatch->start(array(
'server' => 'localhost',
'group' => 'twig::render',
'twig_template' => (string) $name,
));
$ret = parent::render($name, $parameters);
$e->stop();
return $ret;
} | {@inheritdoc} | entailment |
public function hasParameter($parameterName)
{
return isset($this->parameters[$parameterName]) || $this->innerView->hasParameter($parameterName);
} | Checks if $parameterName exists.
@param string $parameterName
@return bool | entailment |
public function getParameter($parameterName)
{
if ($this->hasParameter($parameterName)) {
return $this->parameters[$parameterName];
}
if ($parameterName === 'content') {
@trigger_error('Access to current content via getParameter() is deprecated. Use getContent() instead.', E_USER_DEPRECATED);
} elseif ($parameterName === 'location') {
@trigger_error('Access to current location via getParameter() is deprecated. Use getLocation() instead.', E_USER_DEPRECATED);
}
return $this->innerView->getParameter($parameterName);
} | Returns parameter value by $parameterName.
@param string $parameterName
@return mixed | entailment |
public function removeOption(GetPropertyOptionsEvent $event)
{
$environment = $event->getEnvironment();
if (('type' !== $event->getPropertyName())
|| ('tl_metamodel_attribute' !== $environment->getDataDefinition()->getName())
) {
return;
}
$options = $event->getOptions();
if (!\array_key_exists('filesort', $options)) {
return;
}
unset($options['filesort']);
$event->setOptions($options);
} | Remove the internal sort attribute from the option list.
@param GetPropertyOptionsEvent $event The event.
@return void | entailment |
public function addTask(Task $task)
{
if (!isset($this->tasks[$task->uniq])) {
$this->tasks[$task->uniq] = $task;
++$this->tasksCount;
}
} | Add a task to the set.
@param Task $task Task to add to the set
@see \MHlavac\Gearman\Task, \MHlavac\Gearman\Set::$tasks | entailment |
public function getTask($handle)
{
if (!isset($this->handles[$handle])) {
throw new Exception('Unknown handle');
}
if (!isset($this->tasks[$this->handles[$handle]])) {
throw new Exception('No task by that handle');
}
return $this->tasks[$this->handles[$handle]];
} | Get a task.
@param string $handle Handle of task to get
@throws \MHlavac\Gearman\Exception
@return object Instance of task | entailment |
public function finished()
{
if ($this->tasksCount == 0) {
if (isset($this->callback)) {
$results = array();
foreach ($this->tasks as $task) {
$results[] = $task->result;
}
call_user_func($this->callback, $results);
}
return true;
}
return false;
} | Is this set finished running?
This function will return true if all of the tasks in the set have
finished running. If they have we also run the set callbacks if there
is one.
@return bool | entailment |
public function addme()
{
//control captcha
$captcha = oxNew('oeCaptcha');
if (!$captcha->passCaptcha(false)) {
$this->_iPriceAlarmStatus = 2;
return;
}
return parent::addme();
} | Validates email
address. If email is wrong - returns false and exits. If email
address is OK - creates prcealarm object and saves it
(oxpricealarm::save()). Sends pricealarm notification mail
to shop owner.
@return bool false on error | entailment |
public function createInstance($information, $metaModel)
{
return new File(
$metaModel,
$information,
$this->connection,
$this->tableManipulator,
$this->toolboxFile,
$this->stringUtil,
$this->validator,
$this->fileRepository,
$this->config
);
} | {@inheritDoc} | entailment |
private function ensureOrderColumnExists()
{
$attributes = $this
->connection
->createQueryBuilder()
->select('metamodel.tableName', 'attribute.colname')
->from('tl_metamodel_attribute', 'attribute')
->leftJoin('attribute', 'tl_metamodel', 'metamodel', 'metamodel.id=attribute.pid')
->where('attribute.type=:type')
->setParameter('type', 'file')
->andWhere('attribute.file_multiple=:multiple')
->setParameter('multiple', '1')
->execute();
while ($row = $attributes->fetch(\PDO::FETCH_OBJ)) {
if ($this->fieldExists($row->colname . '__sort', $row->tableName)) {
continue;
}
$this
->connection
->exec(
\sprintf(
'ALTER TABLE %1$s ADD COLUMN %2$s__sort %3$s',
$row->tableName,
$row->colname,
'blob NULL'
)
);
}
} | Ensure that the order column exists.
@return void | entailment |
private function fieldExists($tableName, $columnName): bool
{
if (!\array_key_exists($tableName, $this->schemaCache)) {
$this->schemaCache[$tableName] = $this->connection->getSchemaManager()->listTableColumns($tableName);
}
return isset($this->schemaCache[$tableName][$columnName]);
} | Test if a column exists in a table.
@param string $tableName Table name.
@param string $columnName Column name.
@return bool | entailment |
public function setDataFor($arrValues)
{
foreach ($arrValues as $id => $value) {
$this->connection->update(
$this->quoteReservedWord($this->getMetaModel()->getTableName()),
[$this->quoteReservedWord($this->getColName()) => $value ?: $this->serializeData([])],
[$this->quoteReservedWord('id') => $id]
);
}
} | {@inheritDoc} | entailment |
private function quoteReservedWord(string $word): string
{
if (null === $this->platformReservedWord) {
try {
$this->platformReservedWord = $this->connection->getDatabasePlatform()->getReservedKeywordsList();
} catch (DBALException $exception) {
// Add the not support key word list, if the platform has not a list of keywords.
$this->platformReservedWord = new NotSupportedKeywordList();
}
}
if (false === $this->platformReservedWord->isKeyword($word)) {
return $word;
}
return $this->connection->quoteIdentifier($word);
} | Quote the reserved platform key word.
@param string $word The key word.
@return string | entailment |
public function removeOption(GetPropertyOptionsEvent $event)
{
$environment = $event->getEnvironment();
if (('attr_id' !== $event->getPropertyName())
|| ('tl_metamodel_filtersetting' !== $environment->getDataDefinition()->getName())
) {
return;
}
$options = $event->getOptions();
foreach ($options as $key => $name) {
$sortKey = $key . '__sort';
if (\array_key_exists($sortKey, $options) && ('[file]' === \substr($name, -\strlen('[file]')))) {
unset($options[$sortKey]);
}
}
$event->setOptions($options);
} | Remove the internal sort attribute from the option list.
@param GetPropertyOptionsEvent $event The event.
@return void | entailment |
public function handleUpdateAttribute(PostPersistModelEvent $event)
{
$model = $event->getModel();
if (('file' !== $model->getProperty('type'))
|| (!$model->getProperty('file_multiple'))
|| ('tl_metamodel_attribute' !== $event->getEnvironment()->getDataDefinition()->getName())
) {
return;
}
$metaModelsName = $this->getFactory()->translateIdToMetaModelName($model->getProperty('pid'));
$metaModel = $this->getFactory()->getMetaModel($metaModelsName);
$attributeName = $model->getProperty('colname') . '__sort';
$tableColumns = $this->connection->getSchemaManager()->listTableColumns($metaModel->getTableName());
if (\array_key_exists($attributeName, $tableColumns)) {
return;
}
$this->tableManipulator->createColumn($metaModel->getTableName(), $attributeName, 'blob NULL');
} | Handle the update of the file attribute, if switch on for file multiple.
@param PostPersistModelEvent $event The event.
@return void
@throws \Exception If column not exist in the table. | entailment |
public function buildQueryString($args = array()) {
$args = array_merge($args, array("token" => $this->token));
$query = "";
if (isset($args)) {
while (list($key, $val) = each($args)) {
if ( strlen($query) > 0 ) {
$query .= "&";
} else {
$query .= "?";
}
$query .= $key . '=' . $val;
}
}
return $query;
} | /*
Build query string from $args | entailment |
public function request($args) {
$c = curl_init();
curl_setopt($c, CURLOPT_TIMEOUT, 4);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_USERAGENT, 'groupmeClient/0.1');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, $args['method']);
$curlurl = $this->url . $args['url'] . $this->buildQueryString($args['query']);
curl_setopt($c, CURLOPT_URL, $curlurl );
if($args['method'] == "POST"){
if ( isset($args['payload']) ) {
$payload = "";
if ( isset($args['payload']['file']) ) {
$payload = $args['payload'];
}
else {
$payload = json_encode($args['payload']);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
}
curl_setopt($c, CURLOPT_POSTFIELDS, $payload );
}
}
$info = curl_getinfo($c);
$response = curl_exec($c);
curl_close($c);
return $response;
} | /*
Overhead function that all requests utilize | entailment |
public function version()
{
$this->sendCommand('version');
$res = fgets($this->conn, 4096);
$this->checkForError($res);
return trim($res);
} | Get the version of Gearman running.
@return string
@see MHlavac\Gearman\Manager::sendCommand()
@see MHlavac\Gearman\Manager::checkForError() | entailment |
public function shutdown($graceful = false)
{
$cmd = ($graceful) ? 'shutdown graceful' : 'shutdown';
$this->sendCommand($cmd);
$res = fgets($this->conn, 4096);
$this->checkForError($res);
$this->shutdown = (trim($res) == 'OK');
return $this->shutdown;
} | Shut down Gearman.
@param bool $graceful Whether it should be a graceful shutdown
@return bool
@see MHlavac\Gearman\Manager::sendCommand()
@see MHlavac\Gearman\Manager::checkForError()
@see MHlavac\Gearman\Manager::$shutdown | entailment |
public function workers()
{
$this->sendCommand('workers');
$res = $this->recvCommand();
$workers = array();
$tmp = explode("\n", $res);
foreach ($tmp as $t) {
if (!Connection::stringLength($t)) {
continue;
}
$info = explode(' : ', $t);
list($fd, $ip, $id) = explode(' ', $info[0]);
$abilities = isset($info[1]) ? trim($info[1]) : '';
$workers[] = array(
'fd' => $fd,
'ip' => $ip,
'id' => $id,
'abilities' => empty($abilities) ? array() : explode(' ', $abilities),
);
}
return $workers;
} | Get worker status and info.
Returns the file descriptor, IP address, client ID and the abilities
that the worker has announced.
@throws \MHlavac\Gearman\Exception
@return array A list of workers connected to the server | entailment |
public function setMaxQueueSize($function, $size)
{
if (!is_numeric($size)) {
throw new Exception('Queue size must be numeric');
}
if (preg_match('/[^a-z0-9_]/i', $function)) {
throw new Exception('Invalid function name');
}
$this->sendCommand('maxqueue ' . $function . ' ' . $size);
$res = fgets($this->conn, 4096);
$this->checkForError($res);
return (trim($res) == 'OK');
} | Set maximum queue size for a function.
For a given function of job, the maximum queue size is adjusted to be
max_queue_size jobs long. A negative value indicates unlimited queue
size.
If the max_queue_size value is not supplied then it is unset (and the
default maximum queue size will apply to this function).
@param string $function Name of function to set queue size for
@param int $size New size of queue
@throws \MHlavac\Gearman\Exception
@return bool | entailment |
public function status()
{
$this->sendCommand('status');
$res = $this->recvCommand();
$status = array();
$tmp = explode("\n", $res);
foreach ($tmp as $t) {
if (!Connection::stringLength($t)) {
continue;
}
list($func, $inQueue, $jobsRunning, $capable) = explode("\t", $t);
$status[$func] = array(
'in_queue' => $inQueue,
'jobs_running' => $jobsRunning,
'capable_workers' => $capable,
);
}
return $status;
} | Get queue/worker status by function.
This function queries for queue status. The array returned is keyed by
the function (job) name and has how many jobs are in the queue, how
many jobs are running and how many workers are capable of performing
that job.
@throws \MHlavac\Gearman\Exception
@return array An array keyed by function name | entailment |
protected function sendCommand($cmd)
{
if ($this->shutdown) {
throw new Exception('This server has been shut down');
}
fwrite($this->conn,
$cmd . "\r\n",
Connection::stringLength($cmd . "\r\n"));
} | Send a command.
@param string $cmd The command to send
@throws \MHlavac\Gearman\Exception | entailment |
protected function recvCommand()
{
$ret = '';
while (true) {
$data = fgets($this->conn, 4096);
$this->checkForError($data);
if ($data == ".\n") {
break;
}
$ret .= $data;
}
return $ret;
} | Receive a response.
For most commands Gearman returns a bunch of lines and ends the
transmission of data with a single line of ".\n". This command reads
in everything until ".\n". If the command being sent is NOT ended with
".\n" DO NOT use this command.
@throws \MHlavac\Gearman\Exception
@return string | entailment |
protected function checkForError($data)
{
$data = trim($data);
if (preg_match('/^ERR/', $data)) {
list(, $code, $msg) = explode(' ', $data);
$this->errorCode = urlencode($code);
$this->errorMessage = $message;
throw new Exception($this->errorMessage, $this->errorCode);
}
} | Check for an error.
Gearman returns errors in the format of 'ERR code_here Message+here'.
This method checks returned values from the server for this error format
and will throw the appropriate exception.
@param string $data The returned data to check for an error
@throws \MHlavac\Gearman\Exception | entailment |
public function pictures($url){
$file = $url;
$path = parse_url($url);
if ($path['scheme'] == "http" || $path['scheme'] == "https") {
$file = tempnam(sys_get_temp_dir(), "gm_");
file_put_contents($file, file_get_contents($url));
}
$file = "@" . $file;
$params = array(
'url' => "/pictures",
'method' => 'POST',
'payload' => array("file" => $file),
'query' => array()
);
$response = $this->request($params);
if ($file != $url){
unlink(substr($file, 1));
}
return $response;
} | pictures: Uploads a picture to the GroupMe Image servvice and returns the URL.
@param $url URL to image
@return string $response from GroupMe API | entailment |
public function register()
{
$facade = new Payment();
$this->app->instance('\Payment', $facade);
$this->app->instance(PaymentFacade::class, $facade);
} | Bind two classes
@return void | entailment |
public function addInformation(CollectMetaModelAttributeInformationEvent $event)
{
if (!\count($information = $event->getAttributeInformation())) {
return;
}
if (!\count($fileInformation = $this->collectFileInformation($information))) {
return;
}
$event->setAttributeInformation($this->updateInformation($fileInformation, $information));
} | Add the information.
@param CollectMetaModelAttributeInformationEvent $event The event.
@return void | entailment |
private function updateInformation(array $inputInformation, array $updateInformation)
{
foreach ($inputInformation as $name => $information) {
$columnName = $information['colname'] . '__sort';
$position = \array_flip(\array_keys($updateInformation))[$name];
$updateInformation = \array_merge(
\array_slice($updateInformation, 0, ($position + 1)),
[
$columnName => [
'colname' => $columnName,
'type' => 'filesort'
]
],
\array_slice($updateInformation, ($position ? $position - 1 : $position + 1))
);
}
return $updateInformation;
} | Update the information.
@param array $inputInformation The input information, who add to the update information.
@param array $updateInformation The update information, who becomes update from the input information.
@return array | entailment |
public function setContent($content)
{
if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
throw new \UnexpectedValueException(sprintf('The Response content must be a string or object implementing __toString(), "%s" given.', gettype($content)));
}
$this->content = (string) $content;
return $this;
} | Sets the response content.
Valid types are strings, numbers, null, and objects that implement a __toString() method.
@param mixed $content Content that can be cast to string
@return Response
@throws \UnexpectedValueException | entailment |
public function dispatch(ServerRequestInterface $request, callable $default)
{
$handler = new Handler($this->middleware, $default);
return $handler->handle($request);
} | Dispatch the middleware stack.
@param ServerRequestInterface $request
@param callable $default to call when no middleware is available
@return ResponseInterface | entailment |
public function render()
{
$result = '<form method="' . $this->getMethod() . '" action="' . $this->getAction() . '">' . "\r\n";
$result .= $this->renderFields();
$result .= '</form>' . "\r\n";
return $result;
} | Render form
@return string | entailment |
public function renderFields()
{
$result = '';
foreach ($this->fields as $field => $value) {
$result .= '<input type="hidden" name="' . $field . '" value="' . $value . '"/>' . "\r\n";
}
return $result;
} | Render fields
@return string | entailment |
final protected function getValueFromParam(string $param)
{
if (preg_match(self::$regEx['match'], $param)) {
$arg = preg_filter(self::$regEx['filter'], '', $param);
if (preg_match(self::$regEx['config'], $arg)) {
return $this->getValueFromConfig($arg);
} elseif (preg_match(self::$regEx['array'], $arg)) {
return $this->getValueFromArray($arg);
} else {
return Fixtures::get($arg);
}
} else {
return $param;
}
} | Parse param and replace {{.*}} by its Fixtures::get() value if exists
@param string $param
@return \mixed|null Returns parameter's value if exists, else parameter's name | entailment |
final protected function getValueFromConfig(string $param)
{
$value = null;
$config = self::$suiteConfig;
preg_match_all(self::$regEx['config'], $param, $args, PREG_PATTERN_ORDER);
foreach ($args[1] as $arg) {
if (array_key_exists($arg, $config)) {
$value = $config[$arg];
if (is_array($value)) {
$config = $value;
} else {
break;
}
}
}
return $value;
} | Retrieve param value from current suite config
@param string $param
@return \mixed|null Returns parameter's value if exists, else null | entailment |
final protected function getValueFromArray(string $param)
{
$value = null;
preg_match_all(self::$regEx['array'], $param, $args);
$array = Fixtures::get($args['var'][0]);
if (array_key_exists($args['key'][0], $array)) {
$value = $array[$args['key'][0]];
}
return $value;
} | Retrieve param value from array in Fixtures
@param string $param
@return \mixed|null Returns parameter's value if exists, else null | entailment |
final public function beforeStep(\Codeception\Event\StepEvent $e)
{
$step = $e->getStep();
// access to the protected property using reflection
$refArgs = new ReflectionProperty(get_class($step), 'arguments');
// change property accessibility to public
$refArgs->setAccessible(true);
// retrieve 'arguments' value
$args = $refArgs->getValue($step);
foreach ($args as $index => $arg) {
if (is_string($arg)) {
// case if arg is a string
// e.g. I see "{{param}}"
$args[$index] = $this->getValueFromParam($arg);
} elseif (is_a($arg, '\Behat\Gherkin\Node\TableNode')) {
// case if arg is a table
// e.g. I see :
// | paramater |
// | {{param}} |
$table = [];
foreach ($arg->getRows() as $i => $row) {
foreach ($row as $j => $cell) {
$table[$i][$j] = $this->getValueFromParam($cell);
}
}
$args[$index] = new TableNode($table);
}
}
// set new arguments value
$refArgs->setValue($step, $args);
} | Parse scenario's step before execution
@param \Codeception\Event\StepEvent $e
@return void | entailment |
public function buildAttribute(BuildAttributeEvent $event)
{
$attribute = $event->getAttribute();
if (!($attribute instanceof File) || !$attribute->get('file_multiple')) {
return;
}
$container = $event->getContainer();
$properties = $container->getPropertiesDefinition();
$name = $attribute->getColName();
$nameSort = \sprintf('%s__sort', $name);
if ($properties->hasProperty($nameSort)) {
$this->addAttributeToDefinition($container, $name);
$properties->getProperty($name . '__sort')->setWidgetType('fileTreeOrder');
return;
}
$properties->addProperty($property = new DefaultProperty($name . '__sort'));
$property->setWidgetType('fileTreeOrder');
$this->addAttributeToDefinition($container, $name);
} | This builds the dc-general property information for the virtual file order attribute.
@param BuildAttributeEvent $event The event being processed.
@return void | entailment |
private function addAttributeToDefinition(ContainerInterface $container, $name)
{
if (!$container->hasDefinition('metamodels.file-attributes')) {
$container->setDefinition('metamodels.file-attributes', new AttributeFileDefinition());
}
$container->getDefinition('metamodels.file-attributes')->add($name);
} | Add attribute to MetaModels file attributes definition.
@param ContainerInterface $container The metamodel data definition.
@param string $name The attribute name.
@return void | entailment |
public function getJsonObject()
{
// array_filter() ensures that empty values are filtered out
// array_values() ensures encoding to array rather than object
$this->sslRoutingRestrictedUrls = array_values(array_filter($this->sslRoutingRestrictedUrls));
$this->maintenanceModeAuthorizedIps = array_values(array_filter($this->maintenanceModeAuthorizedIps));
return json_encode(get_object_vars($this));
} | Returns all properties and their values in JSON format
@return string | entailment |
public function createInstance($information, $metaModel)
{
$columnName = ($information['colname'] ?? null);
$tableColumns = $this->connection->getSchemaManager()->listTableColumns($metaModel->getTableName());
if (!$columnName || !\array_key_exists($columnName, $tableColumns)) {
return null;
}
return new FileOrder($metaModel, $information, $this->connection);
} | {@inheritDoc} | entailment |
function it_generates_the_expected_request_when_looking_up_notification(){
//---------------------------------
// Test Setup
$id = self::SAMPLE_ID;
$this->httpClient->sendRequest( Argument::type('Psr\Http\Message\RequestInterface') )->willReturn(
new Response(
200,
['Content-type' => 'application/json'],
json_encode(['notification_id' => $id])
)
);
//---------------------------------
// Perform action
$this->getNotification( $id );
//---------------------------------
// Check result
// Check the expected Request was sent.
$this->httpClient->sendRequest( Argument::that(function( $v ) use ($id) {
// Check a request was sent.
if( !( $v instanceof RequestInterface ) ){
return false;
}
// With the correct URL
if( $v->getUri() != self::BASE_URL . sprintf( Client::PATH_NOTIFICATION_LOOKUP, $id ) ){
return false;
}
// Include the correct token header
if( $v->getHeader('Authorization') != [ 'Bearer '.self::TEST_JWT_TOKEN ] ){
return false;
}
// And correct Content-type
if( $v->getHeader('Content-type') != [ 'application/json' ] ){
return false;
}
return true;
}))->shouldHaveBeenCalled();
} | Lookups (GETs) with expected success | entailment |
function it_generates_the_expected_request_when_sending_sms(){
//---------------------------------
// Test Setup
$payload = [
'phone_number' => '+447834000000',
'template_id'=> 118,
'personalisation' => [
'name'=>'Fred'
]
];
$this->httpClient->sendRequest( Argument::type('Psr\Http\Message\RequestInterface') )->willReturn(
new Response(
201,
[ 'Content-type' => 'application/json' ],
json_encode([ 'notification_id' => 'xxx' ])
)
);
//---------------------------------
// Perform action
$this->sendSms( $payload['phone_number'], $payload['template_id'], $payload['personalisation'] );
//---------------------------------
// Check result
$this->httpClient->sendRequest( Argument::that(function( $v ) use ($payload) {
// Check a request was sent.
if( !( $v instanceof RequestInterface ) ){
return false;
}
// With the correct URL
if( $v->getUri() != self::BASE_URL . Client::PATH_NOTIFICATION_SEND_SMS ){
return false;
}
// Include the correct token header
if( $v->getHeader('Authorization') != [ 'Bearer '.self::TEST_JWT_TOKEN ] ){
return false;
}
// And correct Content-type
if( $v->getHeader('Content-type') != [ 'application/json' ] ){
return false;
}
// With the expected body.
if( json_decode( $v->getBody(), true ) != $payload ){
return false;
}
return true;
}))->shouldHaveBeenCalled();
} | Sending (POSTs) with expected success | entailment |
function it_receives_null_when_the_api_returns_404(){
//---------------------------------
// Test Setup
$code = 404;
$this->httpClient->sendRequest( Argument::type('Psr\Http\Message\RequestInterface') )->willReturn(
new Response(
$code,
['Content-type' => 'application/json']
)
);
//---------------------------------
// Perform action
$response = $this->getNotification( '35836a9e-5a97-4d99-8309-0c5a2c3dbc72' );
//---------------------------------
// Check result
$response->shouldBeNull();
} | Actions with expected errors | entailment |
function it_generates_the_expected_request_when_looking_up_a_template(){
//---------------------------------
// Test Setup
$id = self::SAMPLE_ID;
$this->httpClient->sendRequest( Argument::type('Psr\Http\Message\RequestInterface') )->willReturn(
new Response(
200,
['Content-type' => 'application/json'],
'{}'
)
);
//---------------------------------
// Perform action
$this->getTemplate( $id );
//---------------------------------
// Check result
// Check the expected Request was sent.
$this->httpClient->sendRequest( Argument::that(function( $v ) use ($id) {
return $v->getUri() == self::BASE_URL . sprintf( Client::PATH_TEMPLATE_LOOKUP, $id );
}))->shouldHaveBeenCalled();
} | Template lookups (GETs) with expected success | entailment |
function it_generates_the_expected_request_when_previewing_a_template(){
//---------------------------------
// Test Setup
$id = self::SAMPLE_ID;
$body = [
'personalisation' => [
'name'=>'Fred'
]
];
$this->httpClient->sendRequest( Argument::type('Psr\Http\Message\RequestInterface') )->willReturn(
new Response(
201,
[ 'Content-type' => 'application/json' ],
'{}'
)
);
//---------------------------------
// Perform action
$this->previewTemplate( $id, $body['personalisation']);
//---------------------------------
// Check result
$this->httpClient->sendRequest( Argument::that(function( $v ) use ($id, $body) {
// With the correct URL
if( $v->getUri() != self::BASE_URL . sprintf( Client::PATH_TEMPLATE_PREVIEW, $id ) ){
return false;
}
// With the expected body.
if( json_decode( $v->getBody(), true ) != $body ){
return false;
}
return true;
}))->shouldHaveBeenCalled();
} | Sending (POSTs) with expected success | entailment |
public function afterUserLogin(UserEvent $event)
{
$settings = DefaultDashboard::$plugin->getSettings();
// For the moment, only check on CP requests
if (!Craft::$app->getRequest()->isCpRequest) {
DefaultDashboard::log("Not a CP request");
return;
}
$currentUser = $event->identity;
$defaultUser = Craft::$app->users->getUserById($settings->userDashboard);
if (!$defaultUser) {
DefaultDashboard::error("Default User not found for ID: $settings->userDashboard");
return;
}
// Proceed if we've got a setting for the default user, and its not that user logging in
if ($currentUser->id == $defaultUser->id) {
DefaultDashboard::log("Skip setting dashboard - this is the default user");
return;
}
$currentUserWidgets = $this->_getUserWidgets($currentUser->id);
$defaultUserWidgets = $this->_getUserWidgets($defaultUser->id);
DefaultDashboard::log("Current User ID: " . $currentUser->id);
DefaultDashboard::log("Default User ID: " . $defaultUser->id);
DefaultDashboard::log("Current User Widget: " . json_encode($this->_widgets($currentUserWidgets)));
DefaultDashboard::log("Default User Widget: " . json_encode($this->_widgets($defaultUserWidgets)));
// If this user has no widgets, create them and finish - or, if we're forcing override
if (!$currentUserWidgets || $settings->override) {
// To prevent massive re-creating of widgets each login, check if default vs current is different
if ($this->_compareWidgets($currentUserWidgets, $defaultUserWidgets)) {
DefaultDashboard::log("Users widgets are the same");
return;
}
// Remove any existing widgets for the user
$this->_deleteUserWidgets($currentUser->id);
// Update the logged in users widgets
$this->_setUserWidgets($currentUser, $defaultUserWidgets);
// Update the user with their dashboard-set flag so the default widgets aren't added
Craft::$app->getDb()->createCommand()
->update('{{%users}}', ['hasDashboard' => true], ['id' => $currentUser->id])
->execute();
}
} | ========================================================================= | entailment |
public function actionGenerate()
{
$access = mb_strtolower(StringHelper::randomString(32));
$this->line($access, Console::FG_GREEN);
return ExitCode::OK;
} | Generate a new access token for dynamic IP authorization | entailment |
protected function makeCurrentDriver($name)
{
$this->currentDriver = \App::make($this->getDriver($name), [
'config' => config('payment.' . $name),
]);
return $this;
} | Build driver
@param string $name
@return $this | entailment |
public function getPaymentForm($orderId,
$paymentId,
$amount,
$currency = self::CURRENCY_RUR,
$paymentType = self::PAYMENT_TYPE_CARD,
$successReturnUrl = '',
$failReturnUrl = '',
$description = '',
$extraParams = [],
$receipt = null)
{
return $this->getCurrentDriver()->getPaymentForm($orderId,
$paymentId,
$amount,
$currency,
$paymentType,
$successReturnUrl,
$failReturnUrl,
$description,
$extraParams,
$receipt);
} | Generate payment form
@param int $orderId
@param int $paymentId
@param float $amount
@param string $currency
@param string $paymentType
@param string $successReturnUrl
@param string $failReturnUrl
@param string $description
@param array $extraParams
@param Arrayable $receipt
@return Form | entailment |
public static function connect($host = 'localhost', $timeout = 2000)
{
if (!count(self::$magic)) {
foreach (self::$commands as $cmd => $i) {
self::$magic[$i[0]] = array($cmd, $i[1]);
}
}
$err = '';
$errno = 0;
$port = self::DEFAULT_PORT;
if (strpos($host, ':')) {
list($host, $port) = explode(':', $host);
}
$start = microtime(true);
do {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$socket_connected = @socket_connect($socket, $host, $port);
if ($socket_connected) {
socket_set_nonblock($socket);
socket_set_option($socket, SOL_TCP, 1, 1);
}
$timeLeft = ((microtime(true) - $start) * 1000);
} while (!$socket_connected && $timeLeft < $timeout);
if (!$socket_connected) {
$errno = socket_last_error($socket);
$errstr = socket_strerror($errno);
throw new CouldNotConnectException(
"Can't connect to server ($errno: $errstr)"
);
}
self::$waiting[(int) $socket] = array();
return $socket;
} | Connect to Gearman.
Opens the socket to the Gearman Job server. It throws an exception if
a socket error occurs. Also populates MHlavac\Gearman\Connection::$magic.
@param string $host e.g. 127.0.0.1 or 127.0.0.1:7003
@param int $timeout Timeout in milliseconds
@throws \MHlavac\Gearman\Exception when it can't connect to server
@return resource A connection to a Gearman server
@see MHlavac\Gearman\Connection::$waiting
@see MHlavac\Gearman\Connection::$magic
@see MHlavac\Gearman\Connection::$commands | entailment |
public static function send($socket, $command, array $params = array())
{
if (!isset(self::$commands[$command])) {
throw new Exception('Invalid command: ' . $command);
}
$data = array();
foreach (self::$commands[$command][1] as $field) {
if (isset($params[$field])) {
$data[] = $params[$field];
}
}
$d = implode("\x00", $data);
$cmd = "\0REQ" . pack(
'NN',
self::$commands[$command][0],
self::stringLength($d)
) . $d;
$cmdLength = self::stringLength($cmd);
$written = 0;
$error = false;
do {
$check = @socket_write($socket,
self::subString($cmd, $written, $cmdLength),
$cmdLength);
if ($check === false) {
if (socket_last_error($socket) == SOCKET_EAGAIN or
socket_last_error($socket) == SOCKET_EWOULDBLOCK or
socket_last_error($socket) == SOCKET_EINPROGRESS) {
// skip this is okay
} else {
$error = true;
break;
}
}
$written += (int) $check;
} while ($written < $cmdLength);
if ($error === true) {
$errno = socket_last_error($socket);
$errstr = socket_strerror($errno);
throw new Exception(
"Could not write command to socket ($errno: $errstr)"
);
}
} | Send a command to Gearman.
This is the command that takes the string version of the command you
wish to run (e.g. 'can_do', 'grab_job', etc.) along with an array of
parameters (in key value pairings) and packs it all up to send across
the socket.
@param resource $socket The socket to send the command to
@param string $command Command to send (e.g. 'can_do')
@param array $params Params to send
@see MHlavac\Gearman\Connection::$commands, MHlavac\Gearman\Connection::$socket
@throws \MHlavac\Gearman\Exception on invalid command or unable to write
@return bool | entailment |
public static function read($socket)
{
$header = '';
do {
$buf = socket_read($socket, 12 - self::stringLength($header));
$header .= $buf;
} while ($buf !== false &&
$buf !== '' && self::stringLength($header) < 12);
if ($buf === '') {
throw new Exception('Connection was reset');
}
if (self::stringLength($header) == 0) {
return array();
}
$resp = @unpack('a4magic/Ntype/Nlen', $header);
if (!count($resp) == 3) {
throw new Exception('Received an invalid response');
}
if (!isset(self::$magic[$resp['type']])) {
throw new Exception(
'Invalid response magic returned: ' . $resp['type']
);
}
$return = array();
if ($resp['len'] > 0) {
$data = '';
while (self::stringLength($data) < $resp['len']) {
$data .= socket_read($socket, $resp['len'] - self::stringLength($data));
}
$d = explode("\x00", $data);
foreach (self::$magic[$resp['type']][1] as $i => $a) {
$return[$a] = $d[$i];
}
}
$function = self::$magic[$resp['type']][0];
if ($function == 'error') {
if (!self::stringLength($return['err_text'])) {
$return['err_text'] = 'Unknown error; see error code.';
}
throw new Exception(
$return['err_text'], $return['err_code']
);
}
return array('function' => self::$magic[$resp['type']][0],
'type' => $resp['type'],
'data' => $return, );
} | Read command from Gearman.
@param resource $socket The socket to read from
@see MHlavac\Gearman\Connection::$magic
@throws \MHlavac\Gearman\Exception connection issues or invalid responses
@return array Result read back from Gearman | entailment |
public static function blockingRead($socket, $timeout = 500.0)
{
static $cmds = array();
$tv_sec = floor(($timeout % 1000));
$tv_usec = ($timeout * 1000);
$start = microtime(true);
while (count($cmds) == 0) {
if (((microtime(true) - $start) * 1000) > $timeout) {
throw new Exception('Blocking read timed out');
}
$write = null;
$except = null;
$read = array($socket);
socket_select($read, $write, $except, $tv_sec, $tv_usec);
foreach ($read as $s) {
$cmds[] = self::read($s);
}
}
return array_shift($cmds);
} | Blocking socket read.
@param resource $socket The socket to read from
@param float $timeout The timeout for the read
@throws \MHlavac\Gearman\Exception on timeouts
@return array | entailment |
public static function isConnected($conn)
{
return (is_null($conn) !== true &&
is_resource($conn) === true &&
strtolower(get_resource_type($conn)) == 'socket');
} | Are we connected?
@param resource $conn The connection/socket to check
@return bool False if we aren't connected | entailment |
public static function stringLength($value)
{
if (is_null(self::$multiByteSupport)) {
self::$multiByteSupport = intval(ini_get('mbstring.func_overload'));
}
if (self::$multiByteSupport & 2) {
return mb_strlen($value, '8bit');
} else {
return strlen($value);
}
} | Determine if we should use mb_strlen or stock strlen.
@param string $value The string value to check
@return int Size of string
@see MHlavac\Gearman\Connection::$multiByteSupport | entailment |
public static function subString($str, $start, $length)
{
if (is_null(self::$multiByteSupport)) {
self::$multiByteSupport = intval(ini_get('mbstring.func_overload'));
}
if (self::$multiByteSupport & 2) {
return mb_substr($str, $start, $length, '8bit');
} else {
return substr($str, $start, $length);
}
} | Multibyte substr() implementation.
@param string $str The string to substr()
@param int $start The first position used
@param int $length The maximum length of the returned string
@return string Portion of $str specified by $start and $length
@see MHlavac\Gearman\Connection::$multiByteSupport
@link http://us3.php.net/mb_substr
@link http://us3.php.net/substr | entailment |
public function calculate(PriceableInterface $subject, array $context = [])
{
if (null === $type = $subject->getPricingCalculator()) {
throw new \InvalidArgumentException('Cannot calculate the price for PriceableInterface instance without calculator defined.');
}
/** @var CalculatorInterface $calculator */
$calculator = $this->registry->get($type);
return $calculator->calculate($subject, $subject->getPricingConfiguration(), $context);
} | {@inheritdoc} | entailment |
public function handleSslRouting()
{
if ($this->settings->sslRoutingEnabled && !Craft::$app->getRequest()->getIsConsoleRequest())
{
$requestedUrl = Craft::$app->request->getUrl();
$restrictedUrls = $this->settings->sslRoutingRestrictedUrls;
if (!Craft::$app->request->isSecureConnection)
{
foreach ($restrictedUrls as $restrictedUrl)
{
// Parse dynamic variables like /{cpTrigger}
if (stripos($restrictedUrl, '{') !== false)
{
$restrictedUrl = Craft::$app->view->renderObjectTemplate(
$restrictedUrl,
$this->getDynamicParams()
);
}
$restrictedUrl = '/'.ltrim($restrictedUrl, '/');
if (stripos($requestedUrl, $restrictedUrl) === 0)
{
$this->forceSsl();
}
}
return true;
}
}
return false;
} | Forces SSL based on restricted URLs
The environment settings take priority over those defined in the control panel
@return bool
@throws ErrorException
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | entailment |
protected function getDynamicParams()
{
if (is_null($this->dynamicParams))
{
$this->dynamicParams = [
'siteUrl' => UrlHelper::siteUrl(),
'cpTrigger' => Craft::$app->config->general->cpTrigger,
'actionTrigger' => Craft::$app->config->general->actionTrigger,
];
}
return $this->dynamicParams;
} | Returns a list of dynamic parameters and their values that can be used in restricted area settings
@return array
@throws \yii\base\Exception | entailment |
protected function forceSsl()
{
// Define and trim base URL
$baseUrl = trim($this->settings->sslRoutingBaseUrl);
// Parse dynamic params in SSL routing URL
if (mb_stripos($baseUrl, '{') !== false)
{
$baseUrl = Craft::$app->view->renderObjectTemplate(
$this->settings->sslRoutingBaseUrl,
$this->getDynamicParams()
);
}
// Protect against invalid base URL
if (empty($baseUrl) || $baseUrl == '/')
{
$baseUrl = trim(Craft::$app->request->hostInfo);
}
// Define and trim URI to append to the base URL
$requestUri = trim(Craft::$app->request->getUrl());
// Base URL should now be set to 'http://domain.ext' or 'http://domain.ext/'
// Request URI can could be empty or '/page?key=val'
// Define the final URL formed by the host portion and the URI portion
$url = sprintf('%s%s', rtrim($baseUrl, '/'), $requestUri);
// Ensure https is used
$url = str_replace('http:', 'https:', $url);
if (!filter_var($url, FILTER_VALIDATE_URL))
{
throw new ErrorException(
Craft::t('patrol', '{url} is not a valid URL', ['url' => $url])
);
}
Craft::$app->response->redirect(
$url,
$this->settings->redirectStatusCode
);
} | Redirects to the HTTPS version of the requested URL
@throws ErrorException
@throws \yii\base\Exception
@throws \yii\base\InvalidConfigException | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.