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();
... | 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 ... | 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_POS... | 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($remoteFilena... | {@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);
... | 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($f... | 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... | 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]) &... | 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 str... | 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->sen... | @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(),
... | @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\Sd... | @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',
... | @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\... | @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('re... | @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(
... | 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(MockDelegateFunctio... | 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 t... | 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'),
... | 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="for... | 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 ... | 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 ... | 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 cla... | 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 ';
}
... | 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_pa... | 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.
@par... | 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']))... | 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... | 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']).' ';
... | 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... | 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>';
}
re... | 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('jq... | 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($n... | 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... | 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) {
... | 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:
... | 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 {
... | 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::DIRECTI... | 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(sel... | 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();
}... | 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_D... | 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
... | 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;
... | 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)) {
... | 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',
... | 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 ea... | 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->i... | 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[$cleanPara... | 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
$cleanPa... | 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->ht... | 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 === sel... | 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;
... | 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 ($cleanPara... | 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';... | 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) == '\$') {
... | 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;
}
... | 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
$... | 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
... | 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];
}... | 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 = 'impo... | [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 $... | 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 (!isse... | [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 $charactValue... | 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 (!i... | [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 $over... | 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... | [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 $... | 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(!isse... | [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
... | 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:
... | 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->getPara... | 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->getPa... | 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;
... | 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'))
... | 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();
$re... | 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 = \Cr... | 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 PaystackNotFound... | 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))
... | 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.... | Add default listeners | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.