sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function get($method, $params = [], $headers = []) { return $this->makeRequest($method, self::METHOD_GET, $params, $headers); }
Get an object or list. @param string $method The API method to call, e.g. '/users/' @param array $params An array of arguments to pass to the method. @param array $headers Array of custom headers to be passed @return array Object of json decoded API response.
entailment
public function post($method, $params = [], $headers = []) { return $this->makeRequest($method, self::METHOD_POST, $params, $headers); }
Post to an endpoint. @param string $method The API method to call, e.g. '/shifts/publish/' @param array $params An array of data used to create the object. @param array $headers Array of custom headers to be passed @return array Object of json decoded API response.
entailment
public function update($method, $params = [], $headers = []) { return $this->makeRequest($method, self::METHOD_PUT, $params, $headers); }
Update an object. Must include the ID. @param string $method The API method to call, e.g. '/users/1' @param array $params An array of data to update the object. Only changed fields needed. @param array $headers Array of custom headers to be passed @return array Object of json decoded API response.
entailment
public function delete($method, $params = [], $headers = []) { return $this->makeRequest($method, self::METHOD_DELETE, $params, $headers); }
Delete an object. Must include the ID. @param string $method The API method to call, e.g. '/users/1' @param array $params An array of arguments to pass to the method. @param array $headers Array of custom headers to be passed @return array Object of json decoded API response.
entailment
private function makeRequest($method, $request, $params = [], $headers = []) { $url = $this->getEndpoint() . '/' . $method; if ($params && ($request == self::METHOD_GET || $request == self::METHOD_DELETE)) { $url .= '?' . http_build_query($params); } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, 'WhenIWork-PHP/' . static::VERSION); $headers += $this->getHeaders(); $headers['Content-Type'] = 'application/json'; if ($this->api_token) { $headers['W-Token'] = $this->api_token; } $headers_data = []; foreach ($headers as $k => $v) { $headers_data[] = $k . ': ' . $v; } curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_data); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($request)); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl); if (in_array($request, [self::METHOD_POST, self::METHOD_PUT, self::METHOD_PATCH])) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params)); } $result = curl_exec($ch); curl_close($ch); return $result ? json_decode($result) : false; }
Performs the underlying HTTP request. Exciting stuff happening here. Not really. @param string $method The API method to be called @param string $request The type of request @param array $params Assoc array of parameters to be passed @param array $headers Assoc array of custom headers to be passed @return array Assoc array of decoded result
entailment
public static function login($key, $email, $password) { $params = [ "username" => $email, "password" => $password, ]; $headers = [ 'W-Key' => $key ]; $login = new static(); $response = $login->makeRequest("login", self::METHOD_POST, $params, $headers); return $response; }
Login helper using developer key and credentials to get back a login response @param $key Developer API key @param $email Email of the user logging in @param $password Password of the user @return
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $remoteFilename = 'http://get.insight.sensiolabs.com/insight.phar'; $localFilename = $_SERVER['argv'][0]; $tempFilename = basename($localFilename, '.phar').'-temp.phar'; try { copy($remoteFilename, $tempFilename); if (md5_file($localFilename) == md5_file($tempFilename)) { $output->writeln('<info>insight is already up to date.</info>'); unlink($tempFilename); return; } chmod($tempFilename, 0777 & ~umask()); // test the phar validity $phar = new \Phar($tempFilename); // free the variable to unlock the file unset($phar); rename($tempFilename, $localFilename); $output->writeln('<info>insight updated.</info>'); } catch (\Exception $e) { if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { throw $e; } unlink($tempFilename); $output->writeln('<error>The download is corrupt ('.$e->getMessage().').</error>'); $output->writeln('<error>Please re-run the self-update command to try again.</error>'); } }
{@inheritdoc}
entailment
private function loadConfig() { /** @var \Illuminate\Config\Repository $config */ $config = $this->app['config']; if ($config->get('optimus.components') === null) { $config->set('optimus.components', require __DIR__ . '/config/optimus.components.php'); } }
Load configuration
entailment
public function map(Router $router) { $config = $this->app['config']['optimus.components']; $middleware = $config['protection_middleware']; $highLevelParts = array_map(function ($namespace) { return glob(sprintf('%s%s*', $namespace, DIRECTORY_SEPARATOR), GLOB_ONLYDIR); }, $config['namespaces']); foreach ($highLevelParts as $part => $partComponents) { foreach ($partComponents as $componentRoot) { $component = substr($componentRoot, strrpos($componentRoot, DIRECTORY_SEPARATOR) + 1); $namespace = sprintf( '%s\\%s\\Controllers', $part, $component ); $fileNames = [ 'routes' => true, 'routes_protected' => true, 'routes_public' => false, ]; foreach ($fileNames as $fileName => $protected) { $path = sprintf('%s/%s.php', $componentRoot, $fileName); if (!file_exists($path)) { continue; } $router->group([ 'middleware' => $protected ? $middleware : [], 'namespace' => $namespace, ], function ($router) use ($path) { require $path; }); } } } }
Define the routes for the application. @param \Illuminate\Routing\Router $router @return void
entailment
protected function loadPath($path, $locale, $group) { $result = []; foreach ($this->paths as $path) { $result = array_merge($result, parent::loadPath($path, $locale, $group)); } return $result; }
Load a locale from a given path. @param string $path @param string $locale @param string $group @return array
entailment
public function asset(string $group, ?array $asset = null): string { if (! isset($asset)) { return ''; } $asset['source'] = $this->getAssetSourceUrl($asset['source']); $html = $this->html->{$group}($asset['source'], $asset['attributes']); return $html->toHtml(); }
Get the HTML link to a registered asset. @param string $group @param array|null $asset @return string
entailment
protected function isLocalPath(string $path): bool { if (Str::startsWith($path, ['https://', 'http://', '//'])) { return false; } return \filter_var($path, FILTER_VALIDATE_URL) === false; }
Determine if path is local. @param string $path @return bool
entailment
protected function getAssetSourceUrl(string $source): string { // If the source is not a complete URL, we will go ahead and prepend // the asset's path to the source provided with the asset. This will // ensure that we attach the correct path to the asset. if (! $this->isLocalPath($file = $this->path.'/'.\ltrim($source, '/'))) { return $file; } return $this->getAssetSourceUrlWithModifiedTime($source, $file); }
Get asset source URL. @param string $source @return string
entailment
protected function getAssetSourceUrlWithModifiedTime(string $source, string $file): string { if ($this->isLocalPath($source) && $this->useVersioning) { // We can only append mtime to locally defined path since we need // to extract the file. if (! empty($modified = $this->files->lastModified($file))) { $source = $source."?{$modified}"; } } return $source; }
Get asset source URL with Modified time. @param string $source @param string $file @return string
entailment
protected function dependencyIsValid( string $asset, string $dependency, array $original, array $assets ): bool { // Determine if asset and dependency is circular. $isCircular = function ($asset, $dependency, $assets) { return isset($assets[$dependency]) && \in_array($asset, $assets[$dependency]['dependencies']); }; if (! isset($original[$dependency])) { return false; } elseif ($dependency === $asset) { throw new RuntimeException("Asset [$asset] is dependent on itself."); } elseif ($isCircular($asset, $dependency, $assets)) { throw new RuntimeException("Assets [$asset] and [$dependency] have a circular dependency."); } return true; }
Verify that an asset's dependency is valid. A dependency is considered valid if it exists, is not a circular reference, and is not a reference to the owning asset itself. If the dependency doesn't exist, no error or warning will be given. For the other cases, an exception is thrown. @param string $asset @param string $dependency @param array $original @param array $assets @throws \RuntimeException @return bool
entailment
public function getProjects($page = 1) { $request = $this->client->createRequest('GET', '/api/projects'); $url = $request->getUrl(true); $url->getQuery()->set('page', (int) $page); $request->setUrl($url); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Projects', 'xml' ); }
@param int $page @return Projects
entailment
public function getProject($uuid) { $request = $this->client->createRequest('GET', sprintf('/api/projects/%s', $uuid)); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Project', 'xml' ); }
@param string $uuid @return Project
entailment
public function updateProject(Project $project) { $request = $this->client->createRequest('PUT', sprintf('/api/projects/%s', $project->getUuid()), null, array('insight_project' => $project->toArray())); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Project', 'xml' ); }
@param Project $project @return Project
entailment
public function createProject(Project $project) { $request = $this->client->createRequest('POST', '/api/projects', null, array('insight_project' => $project->toArray())); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Project', 'xml' ); }
@param Project $project @return Project
entailment
public function getAnalyses($projectUuid) { $request = $this->client->createRequest('GET', sprintf('/api/projects/%s/analyses', $projectUuid)); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Analyses', 'xml' ); }
@param string $projectUuid @return Analyses
entailment
public function getAnalysis($projectUuid, $analysesNumber) { $request = $this->client->createRequest('GET', sprintf('/api/projects/%s/analyses/%s', $projectUuid, $analysesNumber)); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Analysis', 'xml' ); }
@param string $projectUuid @param int $analysesNumber @return Analysis
entailment
public function analyze($projectUuid, $reference = null, $branch = null) { $request = $this->client->createRequest( 'POST', sprintf('/api/projects/%s/analyses', $projectUuid), array(), $branch ? array('reference' => $reference, 'branch' => $branch) : array('reference' => $reference) ); return $this->serializer->deserialize( (string) $this->send($request)->getBody(), 'SensioLabs\Insight\Sdk\Model\Analysis', 'xml' ); }
@param string $projectUuid @param string|null $reference A git reference. It can be a commit sha, a tag name or a branch name @param string|null $branch Current analysis branch, used by SymfonyInsight to distinguish between the main branch and PRs @return Analysis
entailment
public function call($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array(), $classToUnserialize = null) { $request = $this->client->createRequest($method, $uri, $headers, $body, $options); if ($classToUnserialize) { return $this->serializer->deserialize( (string) $this->send($request)->getBody(), $classToUnserialize, 'xml' ); } return $this->send($request); }
Use this method to call a specific API resource.
entailment
public static function mock($namespace, $name) { $delegateBuilder = new MockDelegateFunctionBuilder(); $delegateBuilder->build($name); $mockeryMock = Mockery::mock($delegateBuilder->getFullyQualifiedClassName()); $mockeryMock->makePartial()->shouldReceive(MockDelegateFunctionBuilder::METHOD); $builder = new MockBuilder(); $builder->setNamespace($namespace) ->setName($name) ->setFunctionProvider($mockeryMock); $mock = $builder->build(); $mock->enable(); $disabler = new MockDisabler($mock); Mockery::getContainer()->rememberMock($disabler); return new ExpectationProxy($mockeryMock); }
Builds a function mock. Disable this mock after the test with Mockery::close(). @param string $namespace The function namespace. @param string $name The function name. @return Expectation The mockery expectation. @SuppressWarnings(PHPMD)
entailment
public static function define($namespace, $name) { $builder = new MockBuilder(); $builder->setNamespace($namespace) ->setName($name) ->setFunction(function () { }) ->build() ->define(); }
Defines the mocked function in the given namespace. In most cases you don't have to call this method. {@link mock()} is doing this for you. But if the mock is defined after the first call in the tested class, the tested class doesn't resolve to the mock. This is documented in Bug #68541. You therefore have to define the namespaced function before the first call. Defining the function has no side effects. If the function was already defined this method does nothing. @see mock() @link https://bugs.php.net/bug.php?id=68541 Bug #68541 @param string $namespace The function namespace. @param string $name The function name.
entailment
public function container(string $container = 'default'): Asset { if (! isset($this->containers[$container])) { $this->containers[$container] = new Asset($container, $this->dispatcher); } return $this->containers[$container]; }
Get an asset container instance. <code> // Get the default asset container $container = Orchestra\Asset::container(); // Get a named asset container $container = Orchestra\Asset::container('footer'); </code> @param string $container @return \Orchestra\Asset\Asset
entailment
protected function registerAsset(): void { $this->app->singleton('orchestra.asset', function (Application $app) { return new Factory($app->make('orchestra.asset.dispatcher')); }); }
Register the service provider. @return void
entailment
protected function registerDispatcher(): void { $this->app->singleton('orchestra.asset.dispatcher', function (Application $app) { return new Dispatcher( $app->make('files'), $app->make('html'), $app->make('orchestra.asset.resolver'), $app->publicPath() ); }); }
Register the service provider. @return void
entailment
public function text($name, $options = []) { $requiredClass = (isset($options['required']) && $options['required'] == true) ? 'required ' : ''; $hasError = $this->errorBag->has($this->formatArrayName($name)); $hasErrorClass = $hasError ? 'has-error' : ''; $htmlForm = '<div class="form-group '.$requiredClass.$hasErrorClass.'">'; $htmlForm .= $this->setFormFieldLabel($name, $options); if (isset($options['addon'])) { $htmlForm .= '<div class="input-group">'; } if (isset($options['addon']['before'])) { $htmlForm .= '<span class="input-group-prepend"><div class="input-group-text">'.$options['addon']['before'].'</div></span>'; } $type = isset($options['type']) ? $options['type'] : 'text'; $value = isset($options['value']) ? $options['value'] : null; $fieldAttributes = $this->getFieldAttributes($options); if (isset($options['placeholder'])) { $fieldAttributes += ['placeholder' => $options['placeholder']]; } if ($hasError) { $fieldAttributes['class'] .= ' is-invalid'; } $htmlForm .= FormFacade::input($type, $name, $value, $fieldAttributes); if (isset($options['addon']['after'])) { $htmlForm .= '<span class="input-group-append"><div class="input-group-text">'.$options['addon']['after'].'</div></span>'; } if (isset($options['addon'])) { $htmlForm .= '</div>'; } $htmlForm .= $this->getInfoTextLine($options); $htmlForm .= $this->errorBag->first($this->formatArrayName($name), '<span class="invalid-feedback" role="alert">:message</span>'); $htmlForm .= '</div>'; return $htmlForm; }
Text input field that wrapped with form-group bootstrap div. @param string $name The text field name and id attribute. @param array $options Additional attribute for the text input. @return string Generated text input form field.
entailment
public function select($name, $selectOptions, $options = []) { $requiredClass = (isset($options['required']) && $options['required'] == true) ? 'required ' : ''; $hasError = $this->errorBag->has($this->formatArrayName($name)); $hasErrorClass = $hasError ? 'has-error' : ''; $htmlForm = '<div class="form-group '.$requiredClass.$hasErrorClass.'">'; if (isset($options['placeholder'])) { if ($options['placeholder'] != false) { $placeholder = ['' => '-- '.$options['placeholder'].' --']; } else { $placeholder = []; } } else { if (isset($options['label'])) { $placeholder = ['' => '-- Select '.$options['label'].' --']; } else { $placeholder = ['' => '-- Select '.$this->formatFieldLabel($name).' --']; } } $value = isset($options['value']) ? $options['value'] : null; $fieldAttributes = $this->getFieldAttributes($options); if (isset($options['multiple']) && $options['multiple'] == true) { $fieldAttributes = array_merge($fieldAttributes, ['multiple', 'name' => $name.'[]']); } if ($hasError) { $fieldAttributes['class'] .= ' is-invalid'; } if ($selectOptions instanceof Collection) { $selectOptions = !empty($placeholder) ? $selectOptions->prepend($placeholder[''], '') : $selectOptions; } else { $selectOptions = $placeholder + $selectOptions; } $htmlForm .= $this->setFormFieldLabel($name, $options); $htmlForm .= FormFacade::select($name, $selectOptions, $value, $fieldAttributes); $htmlForm .= $this->getInfoTextLine($options); $htmlForm .= $this->errorBag->first($this->formatArrayName($name), '<span class="invalid-feedback" role="alert">:message</span>'); $htmlForm .= '</div>'; return $htmlForm; }
Select/dropdown field wrapped with form-group bootstrap div. @param [type] $name Select field name. @param array|Collection $selectOptions Select options. @param array $options Select input attributes. @return string Generated select input form field.
entailment
public function multiSelect($name, $selectOptions, $options = []) { $options['multiple'] = true; $options['placeholder'] = false; return $this->select($name, $selectOptions, $options); }
Multi-select/dropdown field wrapped with form-group bootstrap div. @param string $name Select field name which will become array input. @param array|Collection $selectOptions Select options. @param array $options Select input attributes. @return string Generated multi-select input form field.
entailment
public function radios($name, $radioOptions, $options = []) { $requiredClass = (isset($options['required']) && $options['required'] == true) ? 'required ' : ''; $hasError = $this->errorBag->has($this->formatArrayName($name)); $hasErrorClass = $hasError ? 'has-error' : ''; $htmlForm = '<div class="form-group '.$requiredClass.$hasErrorClass.'">'; $htmlForm .= $this->setFormFieldLabel($name, $options); $htmlForm .= '<div>'; foreach ($radioOptions as $key => $option) { $value = null; $fieldParams = ['id' => $name.'_'.$key, 'class' => 'form-check-input']; if (isset($options['value']) && $options['value'] == $key) { $value = true; } if (isset($options['v-model'])) { $fieldParams += ['v-model' => $options['v-model']]; } if (isset($options['required']) && $options['required'] == true) { $fieldParams += ['required' => true]; } if ($hasError) { $fieldParams['class'] .= ' is-invalid'; } $listStyle = isset($options['list_style']) ? $options['list_style'] : 'form-check-inline'; $htmlForm .= '<div class="form-check '.$listStyle.'">'; $htmlForm .= FormFacade::radio($name, $key, $value, $fieldParams); $htmlForm .= '<label for="'.$name.'_'.$key.'" class="form-check-label">'.$option.'</label>'; $htmlForm .= '</div>'; } $htmlForm .= '</div>'; $htmlForm .= $this->getInfoTextLine($options); $htmlForm .= $this->errorBag->first($this->formatArrayName($name), '<span class="small text-danger" role="alert">:message</span>'); $htmlForm .= '</div>'; return $htmlForm; }
Radio field wrapped with form-group bootstrap div. @param string $name Radio field name. @param array|Collection $radioOptions Radio options. @param array $options Radio input attributes. @return string Generated radio input form field.
entailment
public function checkboxes($name, array $checkboxOptions, $options = []) { $requiredClass = (isset($options['required']) && $options['required'] == true) ? 'required ' : ''; $hasError = $this->errorBag->has($name); $hasErrorClass = $hasError ? 'has-error' : ''; $htmlForm = '<div class="form-group '.$requiredClass.$hasErrorClass.'">'; $htmlForm .= $this->setFormFieldLabel($name, $options); $htmlForm .= '<div>'; if (isset($options['value'])) { $value = $options['value']; if (is_array($options['value'])) { $value = new Collection($options['value']); } } else { $value = new Collection(); } foreach ($checkboxOptions as $key => $option) { $fieldParams = ['id' => $name.'_'.$key, 'class' => 'form-check-input']; if (isset($options['v-model'])) { $fieldParams += ['v-model' => $options['v-model']]; } if ($hasError) { $fieldParams['class'] .= ' is-invalid'; } $listStyle = isset($options['list_style']) ? $options['list_style'] : 'form-check-inline'; $htmlForm .= '<div class="form-check '.$listStyle.'">'; $htmlForm .= FormFacade::checkbox($name.'[]', $key, $value->contains($key), $fieldParams); $htmlForm .= '<label for="'.$name.'_'.$key.'" class="form-check-label">'.$option.'</label>'; $htmlForm .= '</div>'; } $htmlForm .= '</div>'; $htmlForm .= $this->getInfoTextLine($options); $htmlForm .= $this->errorBag->first($this->formatArrayName($name), '<span class="small text-danger" role="alert">:message</span>'); $htmlForm .= '</div>'; return $htmlForm; }
Multi checkbox with array input, wrapped with bootstrap form-group div. @param string $name Name of checkbox field which become an array input. @param array $checkboxOptions Checkbox options. @param array $options Checkbox input attributes. @return string Generated multi-checkboxes input.
entailment
public function textDisplay($name, $value, $options = []) { $label = isset($options['label']) ? $options['label'] : $this->formatFieldLabel($name); $requiredClass = ''; if (isset($options['required']) && $options['required'] == true) { $requiredClass .= ' required '; } $fieldId = isset($options['id']) ? 'id="'.$options['id'].'" ' : ''; $htmlForm = '<div class="form-group'.$requiredClass.'">'; $htmlForm .= FormFacade::label($name, $label, ['class' => 'form-label']); $htmlForm .= '<div class="form-control" '.$fieldId.'readonly>'.$value.'</div>'; $htmlForm .= '</div>'; return $htmlForm; }
Display a text on the form as disabled input. @param string $name The disabled text field name. @param string $value The field value (displayed text). @param array $options The attributes for the disabled text field. @return string Generated disabled text field.
entailment
public function formButton($form_params = [], $button_label = 'x', $button_options = [], $hiddenFields = []) { $form_params['method'] = isset($form_params['method']) ? $form_params['method'] : 'post'; $form_params['class'] = isset($form_params['class']) ? $form_params['class'] : ''; $form_params['style'] = isset($form_params['style']) ? $form_params['style'] : 'display:inline'; if (isset($form_params['onsubmit']) && $form_params['onsubmit'] != false) { $form_params['onsubmit'] = 'return confirm("'.$form_params['onsubmit'].'")'; } $htmlForm = FormFacade::open($form_params); if (!empty($hiddenFields)) { foreach ($hiddenFields as $k => $v) { $htmlForm .= FormFacade::hidden($k, $v); } } $btnOptions = ''; foreach ($button_options as $key => $value) { $btnOptions .= $key.'="'.$value.'" '; } $htmlForm .= '<button '.$btnOptions.'type="submit">'.$button_label.'</button>'; $htmlForm .= FormFacade::close(); return $htmlForm; }
One form which only have "one button" and "hidden fields". This is suitable for, e.g. set status, delete button, or any other "one-click-action" button. @param array $form_params The form attribtues. @param string $button_label The button text or label. @param array $button_options The button attributes. @param array $hiddenFields Additional hidden fields. @return string Generated form button.
entailment
public function delete($form_params = [], $button_label = 'x', $button_options = [], $hiddenFields = []) { $form_params['method'] = 'delete'; $form_params['class'] = isset($form_params['class']) ? $form_params['class'] : 'del-form pull-right float-right'; if (isset($form_params['onsubmit'])) { if ($form_params['onsubmit'] != false) { $form_params['onsubmit'] = $form_params['onsubmit']; } } else { $form_params['onsubmit'] = 'Are you sure to delete this?'; } if (!isset($button_options['title'])) { $button_options['title'] = 'Delete this item'; } return $this->formButton($form_params, $button_label, $button_options, $hiddenFields); }
A form button that dedicated for submitting a delete request. @param array $form_params The form attribtues. @param string $button_label The delete button text or label. @param array $button_options The button attributes. @param array $hiddenFields Additional hidden fields. @return string Generated delete form button.
entailment
public function price($name, $options = []) { $options['addon'] = ['before' => isset($options['currency']) ? $options['currency'] : 'Rp']; $options['class'] = isset($options['class']) ? $options['class'].' text-right' : 'text-right'; return $this->text($name, $options); }
Price input field that wrapped with form-group bootstrap div. @param string $name The price field name and id attribute. @param array $options Additional attribute for the price input. @return string Generated price input form field.
entailment
private function setFormFieldLabel($name, $options) { if (isset($options['label']) && $options['label'] != false) { $label = isset($options['label']) ? $options['label'] : $this->formatFieldLabel($name); return FormFacade::label($name, $label, ['class' => 'form-label']).'&nbsp;'; } elseif (!isset($options['label'])) { return FormFacade::label($name, $this->formatFieldLabel($name), ['class' => 'form-label']).'&nbsp;'; } }
Set the form field label. @param string $name The field name. @param array $options The field attributes. @return string Generated form field label.
entailment
private function getFieldAttributes(array $options) { $fieldAttributes = ['class' => 'form-control']; if (isset($options['class'])) { $fieldAttributes['class'] .= ' '.$options['class']; } if (isset($options['id'])) { $fieldAttributes += ['id' => $options['id']]; } if (isset($options['readonly']) && $options['readonly'] == true) { $fieldAttributes += ['readonly']; } if (isset($options['disabled']) && $options['disabled'] == true) { $fieldAttributes += ['disabled']; } if (isset($options['required']) && $options['required'] == true) { $fieldAttributes += ['required']; } if (isset($options['min'])) { $fieldAttributes += ['min' => $options['min']]; } if (isset($options['max'])) { $fieldAttributes += ['max' => $options['max']]; } if (isset($options['step'])) { $fieldAttributes += ['step' => $options['step']]; } if (isset($options['style'])) { $fieldAttributes += ['style' => $options['style']]; } return $fieldAttributes; }
Get field attributes based on given option. @param array $options Additional form field attributes. @return array Array of attributes for the field.
entailment
private function getInfoTextLine($options) { $htmlForm = ''; if (isset($options['info'])) { $class = isset($options['info']['class']) ? $options['info']['class'] : 'info'; $htmlForm .= '<p class="text-'.$class.' small">'.$options['info']['text'].'</p>'; } return $htmlForm; }
Get the info text line for input field. @param array $options Additional field attributes. @return string Info text line.
entailment
public function add( $name, string $source, $dependencies = [], $attributes = [], $replaces = [] ) { $type = (\pathinfo($source, PATHINFO_EXTENSION) == 'css') ? 'style' : 'script'; return $this->$type($name, $source, $dependencies, $attributes, $replaces); }
Add an asset to the container. The extension of the asset source will be used to determine the type of asset being registered (CSS or JavaScript). When using a non-standard extension, the style/script methods may be used to register assets. <code> // Add an asset to the container Orchestra\Asset::container()->add('jquery', 'js/jquery.js'); // Add an asset that has dependencies on other assets Orchestra\Asset::add('jquery', 'js/jquery.js', 'jquery-ui'); // Add an asset that should have attributes applied to its tags Orchestra\Asset::add('jquery', 'js/jquery.js', null, array('defer')); </code> @param string|array $name @param string $source @param string|array $dependencies @param string|array $attributes @param string|array $replaces @return $this
entailment
public function script( $name, string $source, $dependencies = [], $attributes = [], $replaces = [] ) { $this->register('script', $name, $source, $dependencies, $attributes, $replaces); return $this; }
Add a JavaScript file to the registered assets. @param string|array $name @param string $source @param string|array $dependencies @param string|array $attributes @param string|array $replaces @return $this
entailment
protected function register( string $type, $name, string $source, $dependencies, $attributes, $replaces ): void { $dependencies = (array) $dependencies; $attributes = (array) $attributes; $replaces = (array) $replaces; if (\is_array($name)) { $replaces = \array_merge($name, $replaces); $name = '*'; } $this->assets[$type][$name] = [ 'source' => $source, 'dependencies' => $dependencies, 'attributes' => $attributes, 'replaces' => $replaces, ]; }
Add an asset to the array of registered assets. @param string $type @param string|array $name @param string $source @param string|array $dependencies @param string|array $attributes @param string|array $replaces @return void
entailment
protected function registerLoader() { $config = $this->app['config']['optimus.components']; $paths = Utilities::findNamespaceResources( $config['namespaces'], $config['language_folder_name'], $config['resource_namespace'] ); $this->app->singleton('translation.loader', function ($app) use ($paths) { return new DistributedFileLoader($app['files'], $paths); }); }
Register the translation line loader. @return void
entailment
protected function prepareRules() { $contentLength = mb_strlen($this->content); while ($this->char_index <= $contentLength) { $this->step(); } foreach ($this->rules as $userAgent => $directive) { foreach ($directive as $directiveName => $directiveValue) { if (is_array($directiveValue)) { $this->rules[$userAgent][$directiveName] = array_values(array_unique($directiveValue)); } } } }
Parse rules @return void
entailment
protected function step() { switch ($this->state) { case self::STATE_ZERO_POINT: $this->zeroPoint(); break; case self::STATE_READ_DIRECTIVE: $this->readDirective(); break; case self::STATE_SKIP_SPACE: $this->skipSpace(); break; case self::STATE_SKIP_LINE: $this->skipLine(); break; case self::STATE_READ_VALUE: $this->readValue(); break; } }
Machine step @return void
entailment
protected function zeroPoint() { if ($this->shouldSwitchToZeroPoint()) { $this->switchState(self::STATE_READ_DIRECTIVE); } elseif ($this->newLine()) { // unknown directive - skip it $this->current_word = ''; $this->increment(); } else { $this->increment(); } return $this; }
Process state ZERO_POINT @return RobotsTxtParser
entailment
protected static function directiveArray() { return array( self::DIRECTIVE_ALLOW, self::DIRECTIVE_DISALLOW, self::DIRECTIVE_HOST, self::DIRECTIVE_USERAGENT, self::DIRECTIVE_SITEMAP, self::DIRECTIVE_CRAWL_DELAY, self::DIRECTIVE_CACHE_DELAY, self::DIRECTIVE_CLEAN_PARAM ); }
Directive array @return string[]
entailment
protected function increment() { $this->current_char = mb_substr($this->content, $this->char_index, 1); $this->current_word .= $this->current_char; $this->current_word = ltrim($this->current_word); $this->char_index++; }
Move to the following step @return void
entailment
protected function readDirective() { $this->previous_directive = $this->current_directive; $this->current_directive = mb_strtolower(trim($this->current_word)); $this->increment(); if ($this->lineSeparator()) { $this->current_word = ''; $this->switchState(self::STATE_READ_VALUE); } else { if ($this->space()) { $this->switchState(self::STATE_SKIP_SPACE); } if ($this->sharp()) { $this->switchState(self::STATE_SKIP_LINE); } } return $this; }
Read directive @return RobotsTxtParser
entailment
protected function readValue() { if ($this->newLine()) { $this->addValueToDirective(); } elseif ($this->sharp()) { $this->current_word = mb_substr($this->current_word, 0, -1); $this->addValueToDirective(); } else { $this->increment(); } return $this; }
Read value @return RobotsTxtParser
entailment
private function addValueToDirective() { $this->convert('trim'); switch ($this->current_directive) { case self::DIRECTIVE_USERAGENT: $this->setCurrentUserAgent(); break; case self::DIRECTIVE_CACHE_DELAY: case self::DIRECTIVE_CRAWL_DELAY: $this->convert('floatval'); $this->addRule(false); break; case self::DIRECTIVE_HOST: $this->addHost(); break; case self::DIRECTIVE_SITEMAP: $this->addSitemap(); break; case self::DIRECTIVE_CLEAN_PARAM: $this->addCleanParam(); break; case self::DIRECTIVE_ALLOW: case self::DIRECTIVE_DISALLOW: $this->addRule(); break; } // clean-up $this->current_word = ''; $this->switchState(self::STATE_ZERO_POINT); }
Add value to directive @return void
entailment
private function setCurrentUserAgent() { $ua = mb_strtolower(trim($this->current_word)); if ($this->previous_directive !== self::DIRECTIVE_USERAGENT) { $this->current_UserAgent = []; } $this->current_UserAgent[] = $ua; // create empty array if not there yet if (empty($this->rules[$ua])) { $this->rules[$ua] = []; } }
Set current user agent, for internal usage only @return void
entailment
private function addRule($append = true) { if (empty($this->current_word)) { return; } foreach ($this->current_UserAgent as $ua) { if ($append === true) { $this->rules[$ua][$this->current_directive][] = $this->current_word; continue; } $this->rules[$ua][$this->current_directive] = $this->current_word; } }
Add group-member rule @param bool $append @return void
entailment
private function addHost() { $parsed = parse_url($this->encode_url($this->current_word)); if (isset($this->host) || $parsed === false) { return; } $host = isset($parsed['host']) ? $parsed['host'] : $parsed['path']; if (!$this->isValidHostName($host)) { return; } elseif (isset($parsed['scheme']) && !$this->isValidScheme($parsed['scheme'])) { return; } $scheme = isset($parsed['scheme']) ? $parsed['scheme'] . '://' : ''; $port = isset($parsed['port']) ? ':' . $parsed['port'] : ''; if ($this->current_word == $scheme . $host . $port) { $this->host = $this->current_word; } }
Add Host @return void
entailment
protected static function encode_url($url) { $reserved = array( ':' => '!%3A!ui', '/' => '!%2F!ui', '?' => '!%3F!ui', '#' => '!%23!ui', '[' => '!%5B!ui', ']' => '!%5D!ui', '@' => '!%40!ui', '!' => '!%21!ui', '$' => '!%24!ui', '&' => '!%26!ui', "'" => '!%27!ui', '(' => '!%28!ui', ')' => '!%29!ui', '*' => '!%2A!ui', '+' => '!%2B!ui', ',' => '!%2C!ui', ';' => '!%3B!ui', '=' => '!%3D!ui', '%' => '!%25!ui' ); $url = preg_replace(array_values($reserved), array_keys($reserved), rawurlencode($url)); return $url; }
URL encoder according to RFC 3986 Returns a string containing the encoded URL with disallowed characters converted to their percentage encodings. @link http://publicmind.in/blog/url-encoding/ @param string $url @return string string
entailment
private static function isValidHostName($host) { return (preg_match('/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i', $host) // valid chars check && preg_match('/^.{1,253}$/', $host) // overall length check && preg_match('/^[^\.]{1,63}(\.[^\.]{1,63})*$/', $host) // length of each label && !filter_var($host, FILTER_VALIDATE_IP)); // is not an IP address }
Validate host name @link http://stackoverflow.com/questions/1755144/how-to-validate-domain-name-in-php @param string $host @return bool
entailment
private function addSitemap() { $parsed = $this->parseURL($this->encode_url($this->current_word)); if ($parsed !== false) { $this->sitemap[] = $this->current_word; $this->sitemap = array_unique($this->sitemap); } }
Add Sitemap @return void
entailment
protected function parseURL($url) { $parsed = parse_url($url); if ($parsed === false) { return false; } elseif (!isset($parsed['scheme']) || !$this->isValidScheme($parsed['scheme'])) { return false; } else { if (!isset($parsed['host']) || !$this->isValidHostName($parsed['host'])) { return false; } else { if (!isset($parsed['port'])) { $parsed['port'] = getservbyname($parsed['scheme'], 'tcp'); if (!is_int($parsed['port'])) { return false; } } } } $parsed['custom'] = (isset($parsed['path']) ? $parsed['path'] : '/') . (isset($parsed['query']) ? '?' . $parsed['query'] : ''); return $parsed; }
Parse URL @param string $url @return array|false
entailment
private function addCleanParam() { $cleanParam = $this->explodeCleanParamRule($this->current_word); foreach ($cleanParam['param'] as $param) { $this->cleanparam[$cleanParam['path']][] = $param; $this->cleanparam[$cleanParam['path']] = array_unique($this->cleanparam[$cleanParam['path']]); } }
Add Clean-Param record @return void
entailment
private function explodeCleanParamRule($rule) { // strip multi-spaces $rule = preg_replace('/\s+/S', ' ', $rule); // split into parameter and path $array = explode(' ', $rule, 2); $cleanParam = array(); // strip any invalid characters from path prefix $cleanParam['path'] = isset($array[1]) ? $this->encode_url(preg_replace('/[^A-Za-z0-9\.-\/\*\_]/', '', $array[1])) : '/*'; $param = explode('&', $array[0]); foreach ($param as $key) { $cleanParam['param'][] = trim($key); } return $cleanParam; }
Explode Clean-Param rule @param string $rule @return array
entailment
public function setHttpStatusCode($code) { $code = intval($code); if (!is_int($code) || $code < 100 || $code > 599 ) { trigger_error('Invalid HTTP status code, not taken into account.', E_USER_WARNING); return false; } $this->httpStatusCode = $code; return true; }
Set the HTTP status code @param int $code @return bool
entailment
public function isAllowed($url, $userAgent = null) { if ($userAgent !== null) { $this->setUserAgent($userAgent); } $url = $this->encode_url($url); return $this->checkRules(self::DIRECTIVE_ALLOW, $this->getPath($url), $this->userAgentMatch); }
Check url wrapper @param string $url - url to check @param string|null $userAgent - which robot to check for @return bool
entailment
public function setUserAgent($userAgent) { $this->userAgent = $userAgent; $uaParser = new \vipnytt\UserAgentParser($this->userAgent); $this->userAgentMatch = $uaParser->getMostSpecific(array_keys($this->rules)); if (!$this->userAgentMatch) { $this->userAgentMatch = '*'; } }
Set UserAgent @param string $userAgent @return void
entailment
protected function checkRules($rule, $path, $userAgent) { // check for disallowed http status code if ($this->checkHttpStatusCodeRule()) { return ($rule === self::DIRECTIVE_DISALLOW); } // Check each directive for rules, allowed by default $result = ($rule === self::DIRECTIVE_ALLOW); foreach (array(self::DIRECTIVE_DISALLOW, self::DIRECTIVE_ALLOW) as $directive) { if (isset($this->rules[$userAgent][$directive])) { foreach ($this->rules[$userAgent][$directive] as $robotRule) { // check rule if ($this->checkRuleSwitch($robotRule, $path)) { // rule match $result = ($rule === $directive); } } } } return $result; }
Check rules @param string $rule - rule to check @param string $path - path to check @param string $userAgent - which robot to check for @return bool
entailment
private function checkHttpStatusCodeRule() { if (isset($this->httpStatusCode) && $this->httpStatusCode >= 500 && $this->httpStatusCode <= 599 ) { $this->log[] = 'Disallowed by HTTP status code 5xx'; return true; } return false; }
Check HTTP status code rule @return bool
entailment
protected function checkRuleSwitch($rule, $path) { switch ($this->isInlineDirective($rule)) { case self::DIRECTIVE_CLEAN_PARAM: if ($this->checkCleanParamRule($this->stripInlineDirective($rule), $path)) { return true; } break; case self::DIRECTIVE_HOST; if ($this->checkHostRule($this->stripInlineDirective($rule))) { return true; } break; default: if ($this->checkBasicRule($rule, $path)) { return true; } } return false; }
Check rule switch @param string $rule - rule to check @param string $path - path to check @return bool
entailment
protected function isInlineDirective($rule) { foreach ($this->directiveArray() as $directive) { if (0 === strpos(mb_strtolower($rule), $directive . ':')) { return $directive; } } return false; }
Check if the rule contains a inline directive @param string $rule @return string|false
entailment
private function checkCleanParamRule($rule, $path) { $cleanParam = $this->explodeCleanParamRule($rule); // check if path prefix matches the path of the url we're checking if (!$this->checkBasicRule($cleanParam['path'], $path)) { return false; } foreach ($cleanParam['param'] as $param) { if (!strpos($path, "?$param=") && !strpos($path, "&$param=") ) { return false; } } $this->log[] = 'Rule match: ' . self::DIRECTIVE_CLEAN_PARAM . ' directive'; return true; }
Check Clean-Param rule @param string $rule @param string $path @return bool
entailment
private function checkBasicRule($rule, $path) { $rule = $this->prepareRegexRule($this->encode_url($rule)); // change @ to \@ $escaped = strtr($rule, array('@' => '\@')); // match result if (preg_match('@' . $escaped . '@', $path)) { $this->log[] = 'Rule match: Path'; return true; } return false; }
Check basic rule @param string $rule @param string $path @return bool
entailment
protected function prepareRegexRule($value) { $escape = ['$' => '\$', '?' => '\?', '.' => '\.', '*' => '.*']; foreach ($escape as $search => $replace) { $value = str_replace($search, $replace, $value); } if (mb_strlen($value) > 2 && mb_substr($value, -2) == '\$') { $value = substr($value, 0, -2) . '$'; } if (mb_strrpos($value, '/') == (mb_strlen($value) - 1) || mb_strrpos($value, '=') == (mb_strlen($value) - 1) || mb_strrpos($value, '?') == (mb_strlen($value) - 1) ) { $value .= '.*'; } if (substr($value, 0, 2) != '.*') { $value = '^' . $value; } return $value; }
Convert robots.txt rules to php regex @param string $value @return string
entailment
protected function stripInlineDirective($rule) { $directive = $this->isInlineDirective($rule); if ($directive !== false) { $rule = trim(str_ireplace($directive . ':', '', $rule)); } return $rule; }
Strip inline directive prefix @param string $rule @return string
entailment
private function checkHostRule($rule) { if (!isset($this->url)) { $error_msg = 'Inline host directive detected. URL not set, result may be inaccurate.'; $this->log[] = $error_msg; trigger_error("robots.txt: $error_msg", E_USER_NOTICE); return false; } $url = $this->parseURL($this->url); $host = trim(str_ireplace(self::DIRECTIVE_HOST . ':', '', mb_strtolower($rule))); if (in_array( $host, array( $url['host'], $url['host'] . ':' . $url['port'], $url['scheme'] . '://' . $url['host'], $url['scheme'] . '://' . $url['host'] . ':' . $url['port'] ) )) { $this->log[] = 'Rule match: ' . self::DIRECTIVE_HOST . ' directive'; return true; } return false; }
Check Host rule @param string $rule @return bool
entailment
private function getPath($url) { $url = trim($url); $parsed = $this->parseURL($url); if ($parsed !== false) { $this->url = $url; return $parsed['custom']; } return $url; }
Get path @param string $url @return string
entailment
public function isDisallowed($url, $userAgent = null) { if ($userAgent !== null) { $this->setUserAgent($userAgent); } $url = $this->encode_url($url); return $this->checkRules(self::DIRECTIVE_DISALLOW, $this->getPath($url), $this->userAgentMatch); }
Check url wrapper @param string $url - url to check @param string|null $userAgent - which robot to check for @return bool
entailment
public function getDelay($userAgent = null, $type = 'crawl-delay') { if ($userAgent !== null) { $this->setUserAgent($userAgent); } switch (mb_strtolower($type)) { case 'cache': case 'cache-delay': // non-standard directive $directive = self::DIRECTIVE_CACHE_DELAY; break; default: $directive = self::DIRECTIVE_CRAWL_DELAY; } if (isset($this->rules[$this->userAgentMatch][$directive])) { // return delay for requested directive return $this->rules[$this->userAgentMatch][$directive]; } elseif (isset($this->rules[$this->userAgentMatch][self::DIRECTIVE_CRAWL_DELAY])) { $this->log[] = "$directive directive (unofficial): Not found, fallback to " . self::DIRECTIVE_CRAWL_DELAY . ' directive'; return $this->rules[$this->userAgentMatch][self::DIRECTIVE_CRAWL_DELAY]; } $this->log[] = "$directive directive: Not found"; return 0; }
Get delay @param string|null $userAgent - which robot to check for @param string $type - in case of non-standard directive @return int|float
entailment
public function getCleanParam() { if (empty($this->cleanparam)) { $this->log[] = self::DIRECTIVE_CLEAN_PARAM . ' directive: Not found'; } return $this->cleanparam; }
Get Clean-Param @return array
entailment
public function render($eol = "\r\n") { $input = $this->getRules(); krsort($input); $output = []; foreach ($input as $userAgent => $rules) { $output[] = 'User-agent: ' . $userAgent; foreach ($rules as $directive => $value) { // Not multibyte $directive = ucfirst($directive); if (is_array($value)) { // Shorter paths later usort($value, function ($a, $b) { return mb_strlen($a) < mb_strlen($b); }); foreach ($value as $subValue) { $output[] = $directive . ': ' . $subValue; } } else { $output[] = $directive . ': ' . $value; } } $output[] = ''; } $host = $this->getHost(); if ($host !== null) { $output[] = 'Host: ' . $host; } $sitemaps = $this->getSitemaps(); foreach ($sitemaps as $sitemap) { $output[] = 'Sitemap: ' . $sitemap; } $output[] = ''; return implode($eol, $output); }
Render @param string $eol @return string
entailment
public function getRules($userAgent = null) { // return all rules if ($userAgent === null) { return $this->rules; } $this->setUserAgent($userAgent); if (isset($this->rules[$this->userAgentMatch])) { return $this->rules[$this->userAgentMatch]; } $this->log[] = 'Rules not found for the given User-Agent'; return array(); }
Get rules based on user agent @param string|null $userAgent @return array
entailment
public function getSitemaps() { if (empty($this->sitemap)) { $this->log[] = self::DIRECTIVE_SITEMAP . ' directive: No sitemaps found'; } return $this->sitemap; }
Get sitemaps wrapper @return array
entailment
public function importProducts ($arrProducts = array()) { // Sanity check - for older versions of PHP if (!is_array($arrProducts)) throw new \Exception('Functia primeste ca parametru un array cu datele fiecarui produs grupate intr-un sub-array'); // Set method and action $method = 'import'; $action = 'importer'; // Set data $data = array('products' => $arrProducts); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Insereaza/Actualizeaza un array de produse. Fiecare produs are un array de date relevante. (https://github.com/celdotro/marketplace/wiki/Import-produse) [EN] Insert/Update an array of products. Each product has an array of relevant data. (https://github.com/celdotro/marketplace/wiki/Import-products) @param array $arrProducts @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function addValuesToCharacteristic ($categID, $charactID, $charactValues) { // Sanity check - for older versions of PHP if (!isset($categID)) throw new \Exception('Specificati categoria'); if (!isset($charactID)) throw new \Exception('Specificati ID-ul caracteristicii'); if (!isset($charactValues) || empty($charactValues)) throw new \Exception('Specificati valorile caracteristicii'); // Set method and action $method = 'products'; $action = 'addValuesToCharacteristic'; // Set data $data = array( 'categID' => $categID, 'charactID' => $charactID, 'charactValues' => $charactValues ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Adauga noi valori in lista unei caracteristici (https://github.com/celdotro/marketplace/wiki/Adauga-noi-valori-unei-caracteristici) [EN] Add new values to a characteristic's list (https://github.com/celdotro/marketplace/wiki/Add-new-values-to-a-characteristic) @param $categID @param $charactID @param $charactValues @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function addOfferToExistingProduct($products_model, $stoc, $pret, $overridePrice){ // Sanity check - for older versions of PHP if (!isset($products_model)) throw new \Exception('Specificati un model de produs'); if (!isset($stoc)) throw new \Exception('Specificati stocul'); if (!isset($pret)) throw new \Exception('Specificati pretul'); // Set method and action $method = 'products'; $action = 'addOfferToExistingProduct'; // Set data $data = array( 'products_model' => $products_model, 'stoc' => $stoc, 'pret' => $pret, 'overridePrice' => $overridePrice ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Adauga o noua oferta unui produs existent (https://github.com/celdotro/marketplace/wiki/Adauga-o-noua-oferta-unui-produs-existent) [EN] Add another offer to an existing product (https://github.com/celdotro/marketplace/wiki/Add-offer-to-existing-product) @param $products_model @param $stoc @param $pret @param $overridePrice @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function newCampaign($name, $dateStart, $dateEnd){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); if(!isset($dateStart) || strtotime($dateStart) === false) throw new \Exception('Specificati o data de start valida'); if(!isset($dateEnd) || strtotime($dateEnd) === false) throw new \Exception('Specficati o data de sfarsit valida'); if(strtotime($dateStart) > strtotime($dateEnd)) throw new \Exception('Data de inceput trebuie sa fie mai mica sau egala cu data de sfarsit'); // Set method and action $method = 'campaign'; $action = 'newCampaign'; // Set data $data = array( 'numecampanie' => $name, 'datastart' => $dateStart, 'dataend' => $dateEnd ); // Send request and retrieve response $result = Dispatcher::send($method, $action, array('newCampaignData' => json_encode($data))); return $result; }
[RO] Creaza o noua campanie si ii seteaza numele, data de inceput si data de sfarsit (https://github.com/celdotro/marketplace/wiki/Adaugare-campanie) [EN] Creates a new campaign and sets its name, start date and end date (https://github.com/celdotro/marketplace/wiki/Add-Campaign) @param $name @param $dateStart @param $dateEnd @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function saveCouponsCampaign($name, $description, $discountType, $value, $minOrder, $totalUtilize, $userUtilize, $dateStart, $dateEnd, $domainRestriction, $productRestrictions){ // Sanity check if(!isset($name) || $name == '') throw new \Exception('Specificati numele campaniei'); if(!isset($dateStart) || strtotime($dateStart) === false) throw new \Exception('Specificati o data de start valida'); if(!isset($dateEnd) || strtotime($dateEnd) === false) throw new \Exception('Specficati o data de sfarsit valida'); if(strtotime($dateStart) > strtotime($dateEnd)) throw new \Exception('Data de inceput trebuie sa fie mai mica sau egala cu data de sfarsit'); // Set method and action $method = 'coupons'; $action = 'saveCouponsCampaign'; // Set data $data = array( 'name' => $name, 'description' => $description, 'discountType' => $discountType, 'value' => $value, 'minOrder' => $minOrder, 'totalUtilize' => $totalUtilize, 'userUtilize' => $userUtilize, 'dateStart' => $dateStart, 'dateEnd' => $dateEnd, 'domainRestriction' => $domainRestriction, 'productRestrictions' => $productRestrictions ); // Send request and retrieve response $result = Dispatcher::send($method, $action, $data); return $result; }
[RO] Adaugare campanie cupoane noua (https://github.com/celdotro/marketplace/wiki/Adaugare-Campanie-Cupoane-Noua) [EN] Add new coupon campaign (https://github.com/celdotro/marketplace/wiki/Add-New-Coupon-Campaign) @param $name @param $description @param $discountType @param $value @param $minOrder @param $totalUtilize @param $userUtilize @param $dateStart @param $dateEnd @param $domainRestriction @param $productRestrictions @return mixed @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function setOperators(array $operators): self { foreach ($operators as $operator) { $this->validateOperator($operator); } $this->operators = $operators; return $this; }
@param string[] $operators @return FilterOperators @throws \InvalidArgumentException
entailment
public function addOperator(string $operator): self { $this->validateOperator($operator); if (!in_array($operator, $this->operators)) { $this->operators[] = $operator; } return $this; }
@param string $operator @return FilterOperators @throws \InvalidArgumentException
entailment
public function removeOperator(string $operator): self { $this->validateOperator($operator); if (false !== ($key = array_search($operator, $this->operators))) { unset($this->operators[$key]); } return $this; }
@param string $operator @return FilterOperators @throws \InvalidArgumentException
entailment
private function validateOperator(string $operator) { if (!in_array($operator, self::VALID_OPERATORS)) { throw new \InvalidArgumentException(sprintf( '%s is not a valid operator' ), $operator); } }
@param string @throws \InvalidArgumentException
entailment
public function connect($options) { switch($this->getOauthVersion()) { case 2: return $this->connectOauth2($options); break; case 1: return $this->connectOauth1($options); break; default: throw new \Exception("Couldn't handle connect for this provider because OAuth version is unknown."); } }
OAuth Connect
entailment
public function connectOauth2($options) { $token = false; // source oauth provider $oauthProvider = $this->getProvider(); // error if(\Craft\craft()->request->getParam('error')) { throw new \Exception("An error occured: ".\Craft\craft()->request->getParam('error')); } $state = \Craft\craft()->request->getParam('state'); $code = \Craft\craft()->request->getParam('code'); $oauth2state = \Craft\craft()->httpSession->get('oauth2state'); if (is_null($code)) { $authorizationOptions = $options['authorizationOptions']; if(count($options['scope']) > 0) { $authorizationOptions['scope'] = $options['scope']; } $authorizationUrl = $oauthProvider->getAuthorizationUrl($authorizationOptions); $state = $oauthProvider->getState(); \Craft\craft()->httpSession->add('oauth2state', $state); OauthPlugin::log('OAuth 2.0 Connect - Redirect to the authorization URL'."\r\n". "authorizationUrl: ".$authorizationUrl."\r\n". "oauth2state: ".\Craft\craft()->httpSession->get('oauth2state') , LogLevel::Info); \Craft\craft()->request->redirect($authorizationUrl); } elseif (!$state || $state !== $oauth2state) { OauthPlugin::log('OAuth 2.0 Connect - Invalid State'."\r\n".print_r([ 'state' => $state, 'oauth2state' => $oauth2state, ], true), LogLevel::Info); \Craft\craft()->httpSession->remove('oauth2state'); throw new \Exception("Invalid state"); } else { OauthPlugin::log('OAuth 2.0 Connect - Authorization code retrieved: '.$code, LogLevel::Info); $token = $oauthProvider->getAccessToken('authorization_code', [ 'code' => $code ]); OauthPlugin::log("OAuth 2.0 Connect - Get Access Token\r\n". "Access token: \r\n". print_r($token, true) , LogLevel::Info); } return $token; }
Connect OAuth 2.0
entailment
public function connectOauth1($options) { $token = false; // source oauth provider $oauthProvider = $this->getProvider(); // denied if(\Craft\craft()->request->getParam('denied')) { throw new \Exception("An error occured: ".\Craft\craft()->request->getParam('denied')); } $user = \Craft\craft()->request->getParam('user'); $oauth_token = \Craft\craft()->request->getParam('oauth_token'); $oauth_verifier = \Craft\craft()->request->getParam('oauth_verifier'); $denied = \Craft\craft()->request->getParam('denied'); if ($oauth_token && $oauth_verifier) { $temporaryCredentials = unserialize(\Craft\craft()->httpSession->get('temporary_credentials')); $token = $oauthProvider->getTokenCredentials($temporaryCredentials, $oauth_token, $oauth_verifier); \Craft\craft()->httpSession->add('token_credentials', serialize($token)); OauthPlugin::log('OAuth 1.0 Connect - Get token credentials'."\r\n".print_r([ 'temporaryCredentials' => $temporaryCredentials, 'oauth_token' => $oauth_token, 'oauth_verifier' => $oauth_verifier, 'token' => $token, ], true), LogLevel::Info); } elseif ($denied) { $errorMsg = "Client access denied by user"; OauthPlugin::log('OAuth 1.0 Connect - '.$errorMsg, LogLevel::Info); throw new \Exception($errorMsg); } else { $temporaryCredentials = $oauthProvider->getTemporaryCredentials(); \Craft\craft()->httpSession->add('temporary_credentials', serialize($temporaryCredentials)); $authorizationUrl = $oauthProvider->getAuthorizationUrl($temporaryCredentials); \Craft\craft()->request->redirect($authorizationUrl); OauthPlugin::log('OAuth 1.0 Connect - Redirect to the authorization URL'."\r\n".print_r([ 'temporaryCredentials' => $temporaryCredentials, 'authorizationUrl' => $authorizationUrl, ], true), LogLevel::Info); } return $token; }
Connect OAuth 1.0
entailment
public function getRemoteResourceOwner($token) { $provider = $this->getProvider(); $realToken = OauthHelper::getRealToken($token); switch($this->getOauthVersion()) { case 1: return $provider->getUserDetails($realToken); break; case 2: return $provider->getResourceOwner($realToken); break; } }
Returns the remote resource owner. @param $token @return mixed
entailment
public function getResourceOwner($token) { $remoteResourceOwner = $this->getRemoteResourceOwner($token); $resourceOwner = new Oauth_ResourceOwnerModel; $resourceOwner->remoteId = $remoteResourceOwner->getId(); // email if(method_exists($remoteResourceOwner, 'getEmail')) { $resourceOwner->email = $remoteResourceOwner->getEmail(); } // name if(method_exists($remoteResourceOwner, 'getName')) { $resourceOwner->name = $remoteResourceOwner->getName(); } elseif(method_exists($remoteResourceOwner, 'getFirstName') && method_exists($remoteResourceOwner, 'getLastName')) { $resourceOwner->name = trim($remoteResourceOwner->getFirstName()." ".$remoteResourceOwner->getLastName()); } elseif(method_exists($remoteResourceOwner, 'getFirstName')) { $resourceOwner->name = $remoteResourceOwner->getFirstName(); } elseif(method_exists($remoteResourceOwner, 'getLasttName')) { $resourceOwner->name = $remoteResourceOwner->getLasttName(); } return $resourceOwner; }
Returns the resource owner. @param $token @return Oauth_ResourceOwnerModel
entailment
protected function fetchProviderData($url, array $headers = []) { $client = $this->getProvider()->getHttpClient(); $client->setBaseUrl($url); if ($headers) { $client->setDefaultOption('headers', $headers); } $request = $client->get()->send(); $response = $request->getBody(); return $response; }
Fetch provider data @param $url @param array $headers @return mixed
entailment
public function getRedirectUri() { // Force `addTrailingSlashesToUrls` to `false` while we generate the redirectUri $addTrailingSlashesToUrls = \Craft\craft()->config->get('addTrailingSlashesToUrls'); \Craft\craft()->config->set('addTrailingSlashesToUrls', false); $redirectUri = \Craft\UrlHelper::getActionUrl('oauth/connect'); // Set `addTrailingSlashesToUrls` back to its original value \Craft\craft()->config->set('addTrailingSlashesToUrls', $addTrailingSlashesToUrls); // We don't want the CP trigger showing in the action URL. $redirectUri = str_replace(\Craft\craft()->config->get('cpTrigger').'/', '', $redirectUri); OauthPlugin::log('Redirect URI: '. $redirectUri, LogLevel::Info); return $redirectUri; }
Returns the redirect URI @return array|string
entailment
public function getProvider() { if (!isset($this->provider)) { $this->provider = $this->createProvider(); } return $this->provider; }
Get Provider
entailment
public static function handle($resourceName, $response, $statusCode) { switch ($statusCode) { case Response::HTTP_UNAUTHORIZED: return new PaystackUnauthorizedException($response, $statusCode); case Response::HTTP_NOT_FOUND: return new PaystackNotFoundException($response, $statusCode); case Response::HTTP_BAD_REQUEST: return new PaystackValidationException($response, $statusCode); case Response::HTTP_GATEWAY_TIMEOUT: return new PaystackInternalServerError($response, $statusCode); case Response::HTTP_INTERNAL_SERVER_ERROR: // @todo: when this happens, send email with details to paystack. return new PaystackInternalServerError('Internal Server Error.', $statusCode); default: return new \Exception('Unknown Error Occurred.', $statusCode); } }
Handles errors encountered and returns the kind of exception they are. @param $resourceName @param $response @param $statusCode @return \Exception|PaystackNotFoundException|PaystackUnauthorizedException|PaystackValidationException
entailment
public function safeUp() { // move current token table to old if (craft()->db->tableExists('oauth_tokens')) { $this->renameTable('oauth_tokens', 'oauth_old_tokens'); } // create new token table if (!craft()->db->tableExists('oauth_tokens', true)) { $this->createTable('oauth_tokens', array( 'providerHandle' => array('required' => true), 'pluginHandle' => array('required' => true), 'encodedToken' => array('column' => 'text'), ), null, true); } return true; }
Any migration code in here is wrapped inside of a transaction. @return bool
entailment
protected function defaultListeners() { $this->addListener('parser.crawler.before', new TagsInScriptListener()); $this->addListener('parser.crawler.after', new ExcludeBlocksListener(), 1); $this->addListener('parser.crawler.after', new DomTextListener()); $this->addListener('parser.crawler.after', new DomButtonListener()); $this->addListener('parser.crawler.after', new DomIframeSrcListener()); $this->addListener('parser.crawler.after', new DomImgListener()); $this->addListener('parser.crawler.after', new DomInputDataListener()); $this->addListener('parser.crawler.after', new DomInputRadioListener()); $this->addListener('parser.crawler.after', new DomLinkListener()); $this->addListener('parser.crawler.after', new DomMetaContentListener()); $this->addListener('parser.crawler.after', new DomPlaceholderListener()); $this->addListener('parser.crawler.after', new DomSpanListener()); $this->addListener('parser.crawler.after', new DomTableDataListener()); $this->addListener('parser.translated', new DomReplaceListener()); $this->addListener('parser.render', new CleanHtmlEntitiesListener()); $this->addListener('parser.render', new TagsInScriptListener(false)); }
Add default listeners
entailment