sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function register()
{
$this->app->singleton('memcache', function($app)
{
$memcache = new MemcacheConnector;
$servers = $this->app['config']['cache.stores.memcached.servers'];
return $memcache->connect($servers);
});
$this->app->singleton('memcache.store', function($app)
{
$prefix = $this->app['config']['cache.prefix'];
return new Repository(new MemcacheStore($app['memcache'], $prefix));
});
$this->app->singleton('memcache.driver', function($app)
{
$minutes = $this->app['config']['session.lifetime'];
return new MemcacheHandler($app['memcache.store'], $minutes);
});
} | Register the service provider.
@return void | entailment |
public function boot()
{
/** @var \Illuminate\Contracts\Config\Repository $config */
$config = $this->app['config'];
// if the cache driver is set to use the memcache driver
if ($config['cache.default'] == 'memcache') {
// set the config to use same servers as memcached
$config->set('cache.stores.memcache.driver', 'memcache');
$servers = $config['cache.stores.memcached.servers'];
$config->set('cache.stores.memcache.servers', $servers);
// extend the cache manager
$this->extendCache($this->app);
}
// if the session driver is set to memcached
if ($config['session.driver'] == 'memcache') {
// extend the session manager
$this->extendSession($this->app);
}
} | Boot the service provider.
@return void | entailment |
public function extendCache(Application $app)
{
$app->resolving('cache', function(CacheManager $cache) {
$cache->extend('memcache', function ($app) {
return $app['memcache.store'];
});
});
} | Add the memcache driver to the cache manager.
@param \Illuminate\Contracts\Foundation\Application $app | entailment |
public function extendSession(Application $app)
{
$app->resolving('session', function(SessionManager $session) {
$session->extend('memcache', function ($app) {
return $app['memcache.driver'];
});
});
} | Add the memcache driver to the session manager.
@param \Illuminate\Contracts\Foundation\Application $app | entailment |
public function recognizeErrorResponseHandler($exception, $inspector, Run $run)
{
$app = $this->application;
$handlerClass = PrettyPageHandler::class;
if ($app->isCli() || false === $app->getConfig(ApplicationInterface::KEY_ERROR, ApplicationInterface::DEFAULT_ERROR)) {
$handlerClass = PlainTextHandler::class;
}
if ($app instanceof Application) {
if ($app->isSoapRequest() || $app->isXmlRequest()) {
$handlerClass = XmlResponseHandler::class;
} elseif ($app->isAjaxRequest() || $app->isJsonRequest()) {
$handlerClass = JsonResponseHandler::class;
}
}
/** @var HandlerInterface $handler */
$handler = new $handlerClass;
$handler->setException($exception);
$handler->setInspector($inspector);
$handler->setRun($run);
return $handler->handle();
} | Recognize response handler for error by content type and environment.
Cli is always handled as plaintext!
@param $exception
@param $inspector
@param Run $run
@return int|null | entailment |
public function notifySystemWithError($exception)
{
$app = $this->application;
// log all errors
$app->getLogger()->error($exception->getMessage());
$applicationEvent = $app->getApplicationEvent();
$applicationEvent->setName(ApplicationInterface::EVENT_SYSTEM_ERROR);
$app->emit($applicationEvent, $exception);
return Handler::DONE;
} | Notify system after error occurs
@param \Exception|\Throwable $exception
@return int | entailment |
public function getTranslation($language = null)
{
$language = $language ?: $this->getLanguage();
$translations = $this->getTranslateRelations();
if (isset($translations[$language])) {
return $translations[$language];
}
$sourceLanguage = $this->getSourceLanguage();
$attributes = isset($translations[$sourceLanguage]) ?
ArrayHelper::toArray($translations[$sourceLanguage]) : [];
$translations[$language] = $this->createTranslation($language, $attributes);
$this->setTranslateRelations($translations);
return $translations[$language];
} | Returns the translation model for the specified language.
@param string|null $language
@return ActiveRecord | entailment |
public function hasMethod($name)
{
return parent::hasMethod($name) ||
is_object($this->getTranslation()) && $this->getTranslation()->hasMethod($name);
} | Returns a value indicating whether a method is defined.
The default implementation is a call to php function `method_exists()`.
You may override this method when you implemented the php magic method `__call()`.
@param string $name the method name
@return boolean whether the method is defined | entailment |
public function getHasTranslate()
{
$relations = $this->getRelation();
$select = array_keys($relations->link);
$select[] = $this->languageAttribute;
return $relations
->select($select)
->indexBy($this->languageAttribute)
->asArray();
} | This read only relations designed for method $this->hasTranslate()
@return \yii\db\ActiveQuery | entailment |
public function boot()
{
/** @var Application\AbstractApplication $app */
$app = $this->getContainer()->get(ApplicationInterface::class);
$errorHandler = new Run(new ApplicationSystemFacade($app));
$handlerService = new HandlerService($app);
$errorHandler->pushHandler([$handlerService, 'recognizeErrorResponseHandler']);
$errorHandler->pushHandler([$handlerService, 'notifySystemWithError']);
$errorHandler->register();
$service = new Application\Services\WhoopsService($errorHandler, $app);
$this->getContainer()->share(Application\Services\WhoopsService::class, $service);
} | Method will be invoked on registration of a service provider implementing
this interface. Provides ability for eager loading of Service Providers.
@return void | entailment |
public function register()
{
$this->app->bind('stack', function () {
return new StackMiddleware($this->app);
});
$this->app->alias('stack', 'Barryvdh\StackMiddleware\StackMiddleware');
} | Register any application services.
@return void | entailment |
public function cleanAddress($address)
{
$response = $this->query($this->prepareUri('clean/address'), [$address]);
$result = $this->populate(new Address, $response);
if (!$result instanceof Address) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Address::class);
}
return $result;
} | Cleans address.
@param string $address
@return Address
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanPhone($phone)
{
$response = $this->query($this->prepareUri('clean/phone'), [$phone]);
$result = $this->populate(new Phone, $response);
if (!$result instanceof Phone) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Phone::class);
}
return $result;
} | Cleans phone.
@param string $phone
@return Phone
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanPassport($passport)
{
$response = $this->query($this->prepareUri('clean/passport'), [$passport]);
$result = $this->populate(new Passport(), $response);
if (!$result instanceof Passport) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Passport::class);
}
return $result;
} | Cleans passport.
@param string $passport
@return Passport
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanName($name)
{
$response = $this->query($this->prepareUri('clean/name'), [$name]);
$result = $this->populate(new Name(), $response);
if (!$result instanceof Name) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Name::class);
}
return $result;
} | Cleans name.
@param string $name
@return Name
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanEmail($email)
{
$response = $this->query($this->prepareUri('clean/email'), [$email]);
$result = $this->populate(new Email, $response);
if (!$result instanceof Email) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Email::class);
}
return $result;
} | Cleans email.
@param string $email
@return Email
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanDate($date)
{
$response = $this->query($this->prepareUri('clean/birthdate'), [$date]);
$result = $this->populate(new Date, $response);
if (!$result instanceof Date) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Date::class);
}
return $result;
} | Cleans date.
@param string $date
@return Date
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function cleanVehicle($vehicle)
{
$response = $this->query($this->prepareUri('clean/vehicle'), [$vehicle]);
$result = $this->populate(new Vehicle, $response);
if (!$result instanceof Vehicle) {
throw new RuntimeException('Unexpected populate result: ' . get_class($result). '. Expected: ' . Vehicle::class);
}
return $result;
} | Cleans vehicle.
@param string $vehicle
@return Vehicle
@throws RuntimeException
@throws InvalidArgumentException | entailment |
public function getBalance()
{
$response = $this->query($this->prepareUri('profile/balance'), [], self::METHOD_GET);
return (double) $response;
} | Gets balance.
@return float
@throws RuntimeException
@throws InvalidArgumentException | entailment |
protected function query($uri, array $params = [], $method = self::METHOD_POST)
{
$request = new Request($method, $uri, [
'Content-Type' => 'application/json',
'Authorization' => 'Token ' . $this->token,
'X-Secret' => $this->secret,
], 0 < count($params) ? json_encode($params) : null);
$response = $this->httpClient->send($request, $this->httpOptions);
$result = json_decode($response->getBody(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Error parsing response: ' . json_last_error_msg());
}
if (empty($result)) {
throw new RuntimeException('Empty result');
}
return array_shift($result);
} | Requests API.
@param string $uri
@param array $params
@param string $method
@return array
@throws RuntimeException
@throws InvalidArgumentException | entailment |
protected function populate(AbstractResponse $object, array $data)
{
$reflect = new ReflectionClass($object);
$properties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($properties as $property) {
if (array_key_exists($property->name, $data)) {
$object->{$property->name} = $this->getValueByAnnotatedType($property, $data[$property->name]);
}
}
return $object;
} | Populates object with data.
@param AbstractResponse $object
@param array $data
@return AbstractResponse | entailment |
protected function getValueByAnnotatedType(ReflectionProperty $property, $value)
{
$comment = $property->getDocComment();
if (preg_match('/@var (.+?)(\|null)? /', $comment, $matches)) {
switch ($matches[1]) {
case 'integer':
case 'int':
$value = (int) $value;
break;
case 'float':
$value = (float) $value;
break;
}
}
return $value;
} | Guesses and converts property type by phpdoc comment.
@param ReflectionProperty $property
@param mixed $value
@return mixed | entailment |
public function isExpired()
{
$createdSeconds = strtotime($this->Created);
$validForSeconds = (int) $this->ValidForDays * 24 * 60 * 60;
$nowSeconds = DBDatetime::now()->getTimestamp();
return ($createdSeconds + $validForSeconds) <= $nowSeconds;
} | Determines whether the token is still valid (from days since it was created).
@return bool | entailment |
public function getLemmas($word, $partOfSpeech = null) {
if($partOfSpeech !== null && !isset(self::$partsOfSpeech[$partOfSpeech])) {
$posAsString = implode(' or ', array_keys(self::$partsOfSpeech));
throw new InvalidArgumentException("partsOfSpeech must be {$posAsString}.");
}
$wordEntity = new Word($word);
if($partOfSpeech !== null) {
$pos = $this->getPos($partOfSpeech);
$lemmas = $this->getBaseForm($wordEntity, $pos);
if(!$lemmas) {
$lemmas[] = new Lemma($word, $partOfSpeech);
}
} else {
$lemmas = [];
/** @var PartOfSpeech $pos */
foreach(self::$partsOfSpeech as $pos) {
$lemmas = array_merge($lemmas, $this->getBaseForm($wordEntity, $pos));
}
if(!$lemmas) {
/** @var PartOfSpeech $pos */
foreach(self::$partsOfSpeech as $pos) {
if(isset($pos->getWordsList()[$word])) {
$lemmas[] = new Lemma($word, $pos->getPartOfSpeechAsString());
}
}
}
if(!$lemmas) {
$lemmas[] = new Lemma($word);
}
}
return array_unique($lemmas, SORT_REGULAR);
} | Lemmatize a word
@param string $word
@param string|null $partOfSpeech
@return Lemma[] | entailment |
private function getBaseForm(Word $word, $pos) {
$lemmas = [];
if($lemma = $pos->getIrregularBase($word)) {
$lemmas[] = $lemma;
}
return array_merge($lemmas, $pos->getRegularBases($word));
} | @param Word $word
@param PartOfSpeech $pos
@return Lemma[] | entailment |
public function getOnlyLemmas($word, $partOfSpeech = null) {
$lemmas = $this->getLemmas($word, $partOfSpeech);
$result = [];
foreach($lemmas as $lemma) {
if(!in_array($lemma->getLemma(), $result)) {
$result[] = $lemma->getLemma();
}
}
return $result;
} | @param $word
@param null $partOfSpeech
@return string[] | entailment |
public function preview(HTTPRequest $request)
{
// Ensure this URL doesn't get picked up by HTTP caches
HTTPCacheControlMiddleware::singleton()->disableCache();
$key = $request->param('Key');
$token = $request->param('Token');
try {
$session = $this->getRequest()->getSession();
} catch (BadMethodCallException $e) {
// Create a new session
$session = $this->getRequest()
->setSession(Injector::inst()->create(Session::class, []))
->getSession();
}
/** @var ShareToken $shareToken */
$shareToken = ShareToken::get()->filter('Token', $token)->first();
if (!$shareToken) {
return $this->errorPage();
}
/** @var SiteTree|ShareDraftContentSiteTreeExtension $page */
$page = Versioned::get_by_stage(SiteTree::class, Versioned::DRAFT)
->byID($shareToken->PageID);
$latest = Versioned::get_latest_version(SiteTree::class, $shareToken->PageID);
$controller = $this->getControllerFor($page);
if (!$shareToken->isExpired() && $page->generateKey($shareToken->Token) === $key) {
Requirements::css('silverstripe/sharedraftcontent: client/dist/styles/bundle-frontend.css');
// Temporarily un-secure the draft site and switch to draft
$oldSecured = $this->getIsDraftSecured($session);
$oldMode = Versioned::get_reading_mode();
// Process page inside an unsecured draft container
try {
$this->setIsDraftSecured($session, false);
Versioned::set_stage('Stage');
// Hack to get around ContentController::init() redirecting on home page
$_FILES = array(array());
// Create mock request; Simplify request to single top level request
$pageRequest = new HTTPRequest('GET', $page->URLSegment);
$pageRequest->match('$URLSegment//$Action/$ID/$OtherID', true);
$pageRequest->setSession($session);
$rendered = $controller->handleRequest($pageRequest);
// Render draft heading
$data = new ArrayData(array(
'Page' => $page,
'Latest' => $latest,
));
$include = (string) $data->renderWith('Includes/TopBar');
} finally {
$this->setIsDraftSecured($session, $oldSecured);
Versioned::set_reading_mode($oldMode);
}
return str_replace('</body>', $include . '</body>', (string) $rendered->getBody());
} else {
return $this->errorPage();
}
} | @param HTTPRequest $request
@return string|DBHTMLText | entailment |
protected function setIsDraftSecured(Session $session, $secured)
{
// Versioned >=1.2
if (method_exists(Versioned::class, 'set_draft_site_secured')) {
Versioned::set_draft_site_secured($secured);
}
// Set session variable anyway
$session->set('unsecuredDraftSite', !$secured);
} | Set draft site security
@param Session $session
@param bool $secured True if draft site should be secured | entailment |
public static function count(Array $body)
{
$instance = new static;
$params = $instance->basicElasticParams();
$params['body'] = $body;
$response = $instance->getElasticClient()->count($params);
return intval($response['count']);
} | Returns match count
@param array $body
@return integer | entailment |
public static function search(Array $body)
{
$instance = new static;
$params = $instance->basicElasticParams();
$params['body'] = $body;
$response = $instance->getElasticClient()->search($params);
return new ElasticCollection($response, $instance);
} | Builds an arbitrary query.
@param array $body
@return ElasticCollection | entailment |
public static function fuzzy($field, $value, $fuzziness = 'AUTO')
{
$body = array(
'query' => array(
'fuzzy' => array(
$field => array(
'value' => $value,
'fuzziness' => $fuzziness
)
)
),
'size' => 1000
);
return static::search($body);
} | Builds a fuzzy query.
@param string $field
@param string $value
@param string $fuzziness
@return ElasticCollection | entailment |
public static function geoshape($field, Array $coordinates, $type = 'envelope')
{
$body = array(
'query' => array(
'geo_shape' => array(
$field => array(
'shape' => array(
'type' => $type,
'coordinates' => $coordinates
)
)
)
),
'size' => 1000
);
return static::search($body);
} | Builds a geoshape query.
@param string $field
@param array $coordinates
@param string $type
@return ElasticCollection | entailment |
public static function moreLikeThis(Array $fields, Array $ids, $minTermFreq = 1, $percentTermsToMatch = 0.5, $minWordLength = 3)
{
$body = array(
'query' => array(
'more_like_this' => array(
'fields' => $fields,
'ids' => $ids,
'min_term_freq' => $minTermFreq,
'percent_terms_to_match' => $percentTermsToMatch,
'min_word_length' => $minWordLength,
)
),
'size' => 1000
);
return static::search($body);
} | Builds a more_like_this query.
@param array $fields
@param array $ids
@param int $minTermFreq
@param float $percentTermsToMatch
@param int $minWordLength
@return ElasticCollection | entailment |
public static function getMapping()
{
$instance = new static;
$params = $instance->basicElasticParams();
return $instance->getElasticClient()->indices()->getMapping($params);
} | Gets mappings.
@return array | entailment |
public static function putMapping()
{
$instance = new static;
$mapping = $instance->basicElasticParams();
$params = array(
'_source' => array('enabled' => true),
'properties' => $instance->getMappingProperties()
);
$mapping['body'][$instance->getTypeName()] = $params;
return $instance->getElasticClient()->indices()->putMapping($mapping);
} | Puts mappings.
@return array | entailment |
public static function deleteMapping()
{
$instance = new static;
$params = $instance->basicElasticParams();
return $instance->getElasticClient()->indices()->deleteMapping($params);
} | Deletes mappings.
@return array | entailment |
public function index()
{
$params = $this->basicElasticParams(true);
$params['body'] = $this->documentFields();
return $this->getElasticClient()->index($params);
} | Indexes the model in Elasticsearch.
@return array | entailment |
public function updateIndex(Array $fields = array())
{
// Use the specified fields for
// the update.
if ($fields) {
$body = $fields;
}
// Or get the model's modified fields.
elseif ($this->isDirty()) {
$body = $this->getDirty();
}
else {
return true;
}
foreach ($body as $field => $value) {
if ($value instanceof Carbon) {
$body[$field] = $value->toDateTimeString();
}
}
$params = $this->basicElasticParams(true);
$params['body']['doc'] = $body;
try {
return $this->getElasticClient()->update($params);
}
catch (Missing404Exception $e) {
return false;
}
} | Updates the model's index.
@param array $fields
@return array|bool | entailment |
public function removeIndex()
{
try {
return $this->getElasticClient()->delete($this->basicElasticParams(true));
}
catch (Missing404Exception $e) {
return false;
}
} | Removes the model's index.
@return array|bool | entailment |
public function save(Array $options = array())
{
if (Config::get('bouncy::config.auto_index')) {
$params = $this->basicElasticParams(true);
// When creating a model, Eloquent still
// uses the save() method. In this case,
// the field still doesn't have an id, so
// it is saved first, and then indexed.
if (! isset($params['id'])) {
$saved = parent::save($options);
$this->index();
return $saved;
}
// When updating fails, it means that the
// index doesn't exist, so it is created.
if (! $this->updateIndex()) {
$this->index();
}
}
return parent::save($options);
} | Runs indexing functions before calling
Eloquent's save() method.
@param array $options
@return mixed | entailment |
public function highlight($field)
{
if (isset($this->highlighted[$field])) {
return $this->highlighted[$field];
}
return false;
} | Returns a highlighted field.
@param string $field
@return mixed | entailment |
public function newFromElasticResults(Array $hit)
{
$instance = $this->newInstance(array(), true);
$attributes = $hit['_source'];
$instance->isDocument = true;
if (isset($hit['_score'])) {
$instance->documentScore = $hit['_score'];
}
if (isset($hit['_version'])) {
$instance->documentVersion = $hit['_version'];
}
if (isset($hit['highlight'])) {
foreach ($hit['highlight'] as $field => $value) {
$instance->highlighted[$field] = $value[0];
}
}
$instance->setRawAttributes($attributes, true);
return $instance;
} | Fills a model's attributes with Elasticsearch
result data.
@param array $hit
@return mixed | entailment |
protected function basicElasticParams($withId = false)
{
$params = array(
'index' => $this->getIndex(),
'type' => $this->getTypeName()
);
if ($withId and $this->getKey()) {
$params['id'] = $this->getKey();
}
return $params;
} | Sets the basic Elasticsearch parameters.
@param bool $withId
@return array | entailment |
public static function toObservable(callable $factory)
{
$observableFactory = function () use ($factory) {
return Promise::toObservable($factory());
};
return Observable::defer($observableFactory);
} | Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
@param callable $factory
@return \Rx\Observable\AnonymousObservable | entailment |
public function addSlimPlugins(RouterInterface $router, $uri)
{
$smartyPlugins = new SmartyPlugins($router, $uri);
$this->smarty->registerPlugin('function', 'path_for', [$smartyPlugins, 'pathFor']);
$this->smarty->registerPlugin('function', 'base_url', [$smartyPlugins, 'baseUrl']);
} | Method to add the Slim plugins to Smarty
@param RouterInterface $router
@param string|\Slim\Http\Uri $uri
@deprecated Deprecated since version 1.1.0. Use registerPlugin instead. See README for more info. | entailment |
public function registerPlugin($type, $tag, $callback, $cacheable = true, $cache_attr = null)
{
$this->smarty->registerPlugin($type, $tag, $callback, $cacheable, $cache_attr);
} | Proxy method to register a plugin to Smarty
@param string $type plugin type
@param string $tag name of template tag
@param callable $callback PHP callback to register
@param boolean $cacheable if true (default) this function is cachable
@param array $cache_attr caching attributes if any
@return self
@throws SmartyException when the plugin tag is invalid | entailment |
public function fetch($template, $data = [])
{
$data = array_merge($this->defaultVariables, $data);
$this->smarty->assign($data);
return $this->smarty->fetch($template);
} | Fetch rendered template
@param string $template Template pathname relative to templates directory
@param array $data Associative array of template variables
@return string | entailment |
public static function fromObservable(ObservableInterface $observable, Deferred $deferred = null)
{
$d = $deferred ?: new Deferred();
$value = null;
$observable->subscribe(new CallbackObserver(
function ($v) use (&$value) {
$value = $v;
},
function ($error) use ($d) {
$d->reject($error);
},
function () use ($d, &$value) {
$d->resolve($value);
}
));
return $d->promise();
} | Converts an existing observable sequence to React Promise
@param PromisorInterface|null $deferred
@return \React\Promise\Promise | entailment |
public static function toObservable(PromiseInterface $promise)
{
return Observable::defer(
function () use ($promise) {
$subject = new AsyncSubject();
$promise->then(
function ($value) use ($subject) {
$subject->onNext($value);
$subject->onCompleted();
},
[$subject, "onError"]
);
return $subject;
}
);
} | Converts a Promise to an Observable sequence
@param \React\Promise\PromiseInterface $promise
@return \Rx\Observable\AnonymousObservable | entailment |
protected function consumeParagraph($lines, $current)
{
// consume until newline
$content = [];
for ($i = $current, $count = count($lines); $i < $count; $i++) {
$line = $lines[$i];
if (!empty($line) && ltrim($line) !== '' &&
!($line[0] === "\t" || $line[0] === " " && strncmp($line, ' ', 4) === 0) &&
!$this->identifyHeadline($line, $lines, $i))
{
$content[] = $line;
} else {
break;
}
}
$block = [
'paragraph',
'content' => $this->parseInline(implode("\n", $content)),
];
return [$block, --$i];
} | Consume lines for a paragraph
Allow headlines and code to break paragraphs | entailment |
private function parseInlineHtml($text)
{
if (strpos($text, '>') !== false) {
// convert a name markers to \labels
if (preg_match('~^<((a|span)) (name|id)="(.*?)">.*?</\1>~i', $text, $matches)) {
return [
['label', 'name' => str_replace('#', '::', $this->labelPrefix . $matches[4])],
strlen($matches[0])
];
}
}
return [['text', '<'], 1];
} | Parses <a name="..."></a> tags as reference labels | entailment |
protected function parseEscape($text)
{
if (isset($text[1]) && in_array($text[1], $this->escapeCharacters)) {
if ($text[1] === '\\') {
return [['backslash'], 2];
}
return [['text', $text[1]], 2];
}
return [['text', $text[0]], 1];
} | Parses escaped special characters.
This allow a backslash to be interpreted as LaTeX
@marker \ | entailment |
protected function escapeLatex($string)
{
if ($this->_escaper === null) {
$this->_escaper = new TextToLatex();
}
return $this->_escaper->convert($string);
} | Escape special LaTeX characters | entailment |
protected function renderText($text)
{
$output = str_replace(" \n", "\\\\\n", $this->escapeLatex($text[1]));
// support No-Break Space in LaTeX
$output = preg_replace("/\x{00a0}/u", '~', $output);
// support Narrow No-Break Space spaces in LaTeX
// http://unicode-table.com/en/202F/
// http://tex.stackexchange.com/questions/76132/how-to-typeset-a-small-non-breaking-space
$output = preg_replace("/\x{202f}/u", '\nobreak\hspace{.16667em plus .08333em}', $output);
return $output;
} | @inheritdocs
Parses a newline indicated by two spaces on the end of a markdown line. | entailment |
public static function start(callable $action, SchedulerInterface $scheduler = null)
{
$scheduler = $scheduler ?: new ImmediateScheduler();
$subject = new AsyncSubject();
$scheduler->schedule(function () use ($subject, $action) {
$result = null;
try {
$result = call_user_func($action);
} catch (\Exception $e) {
$subject->onError($e);
return;
}
$subject->onNext($result);
$subject->onCompleted();
});
return $subject->asObservable();
} | Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an
observable sequence.
@param callable $action
@param SchedulerInterface $scheduler
@return AnonymousObservable | entailment |
public function lift(callable $operatorFactory)
{
return new AnonymousObservable(function (ObserverInterface $observer, SchedulerInterface $schedule) use ($operatorFactory) {
$operator = $operatorFactory();
return $operator($this, $observer, $schedule);
});
} | Lifts a function to the current Observable and returns a new Observable that when subscribed to will pass
the values of the current Observable through the Operator function.
@param callable $operatorFactory
@return AnonymousObservable | entailment |
public function distinctUntilChanged(callable $keySelector = null, callable $comparer = null)
{
return $this->lift(function () use ($keySelector, $comparer) {
return new DistinctUntilChangedOperator($keySelector, $comparer);
});
} | Returns an observable sequence that contains only distinct contiguous elements according to the keySelector
and the comparer.
@param callable $keySelector
@param callable $comparer
@return \Rx\Observable\AnonymousObservable | entailment |
public function scan(callable $accumulator, $seed = null)
{
return $this->lift(function () use ($accumulator, $seed) {
return new ScanOperator($accumulator, $seed);
});
} | Applies an accumulator function over an observable sequence and returns each intermediate result.
The optional seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see Observable.aggregate.
@param $accumulator
@param null $seed
@return AnonymousObservable | entailment |
public function multicast(Subject $subject, $selector = null, SchedulerInterface $scheduler = null)
{
return $selector ?
new MulticastObservable($this, function () use ($subject) {
return $subject;
}, $selector) :
new ConnectableObservable($this, $subject, $scheduler);
} | Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence
within a selector function. Each subscription to the resulting sequence causes a separate multicast invocation,
exposing the sequence resulting from the selector function's invocation. For specializations with fixed subject
types, see Publish, PublishLast, and Replay.
@param \Rx\Subject\Subject $subject
@param null $selector
@param SchedulerInterface $scheduler
@return ConnectableObservable|MulticastObservable | entailment |
public function replay(callable $selector = null, $bufferSize = null, $windowSize = null, SchedulerInterface $scheduler = null)
{
return $this->multicast(new ReplaySubject($bufferSize, $windowSize, $scheduler), $selector);
} | Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence
that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time
length for the replay buffer.
This operator is a specialization of Multicast using a ReplaySubject.
@param callable|null $selector
@param integer|null $bufferSize
@param integer|null $windowSize
@param \Rx\SchedulerInterface|null $scheduler
@return \Rx\Observable\ConnectableObservable|\Rx\Observable\MulticastObservable | entailment |
public function zip(array $observables, callable $selector = null)
{
return $this->lift(function () use ($observables, $selector) {
return new ZipOperator($observables, $selector);
});
} | Merges the specified observable sequences into one observable sequence by using the selector
function whenever all of the observable sequences have produced an element at a corresponding index. If the
result selector function is omitted, a list with the elements of the observable sequences at corresponding
indexes will be yielded.
@param array $observables
@param callable $selector
@return \Rx\Observable\AnonymousObservable | entailment |
public function delay($delay, $scheduler = null)
{
return $this->lift(function () use ($delay, $scheduler) {
return new DelayOperator($delay, $scheduler);
});
} | Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
@param $delay
@param SchedulerInterface|null $scheduler
@return AnonymousObservable | entailment |
public function getIrregularBase(Word $word) {
if($base = $this->findIrregularBaseBehavior->getIrregularBase($word)) {
return new Lemma($base, $this->getPartOfSpeechAsString());
}
return null;
} | @param Word $word
@return null|Lemma | entailment |
public function getRegularBases(Word $word) {
$lemmas = [];
$bases = $this->findRegularBaseBehavior->getRegularBases($word);
foreach($bases as $base) {
$lemmas[] = new Lemma($base, $this->getPartOfSpeechAsString());
}
return $lemmas;
} | @param Word $word
@return Lemma[] | entailment |
public function index()
{
if ($this->isEmpty()) {
return false;
}
$params = array();
foreach ($this->all() as $item) {
$params['body'][] = array(
'index' => array(
'_index' => $item->getIndex(),
'_type' => $item->getTypeName(),
'_id' => $item->getKey()
)
);
$params['body'][] = $item->documentFields();
}
return $this->getElasticClient()->bulk($params);
} | Indexes all the results from the
collection.
@return array | entailment |
public function isDoubleConsonant($suffix) {
$length = strlen($this->word) - strlen($suffix);
return $length > 2
&& Helper::isVowel($this->word[$length - 3])
&& !Helper::isVowel($this->word[$length - 2])
&& $this->word[$length - 2] === $this->word[$length - 1];
} | @param string $suffix
@return bool | entailment |
protected function getMorphologicalSubstitutionBases(Word $word) {
$bases = [];
foreach($this->getMorphologicalSubstitutions() as list($morpho, $origin)) {
if($word->isEndsWith($morpho)) {
$bases[] = substr($word->asString(), 0, -strlen($morpho)) . $origin;
}
}
return $bases;
} | @param Word $word
@return string[] | entailment |
protected function filterValidBases(array $bases) {
$result = [];
foreach($bases as $base) {
if($this->isValidBase($base)) {
$result[] = $base;
}
}
return $result;
} | @param string[] $bases
@return string[] | entailment |
protected function isValidBase($base) {
return strlen($base) > 1 && isset($this->partOfSpeech->getWordsList()[$base]) && $this->partOfSpeech->getWordsList()[$base] === $base;
} | @param string $base
@return bool | entailment |
public function paginate($perPage = 15)
{
$paginator = Paginator::make($this->items, count($this->items), $perPage);
$start = ($paginator->getFactory()->getCurrentPage() - 1) * $perPage;
$sliced = array_slice($this->items, $start, $perPage);
return Paginator::make($sliced, count($this->items), $perPage);
} | Paginates the Elasticsearch results.
@param int $perPage
@return mixed | entailment |
public function limit($limit = null)
{
if ($limit) {
if ($limit < 0) {
$this->items = array_slice($this->items, $limit, abs($limit));
}
else {
$this->items = array_slice($this->items, 0, $limit);
}
}
return $this;
} | Limits the number of results.
@param int|null $limit
@return ElasticCollection | entailment |
protected function elasticToModel()
{
$items = array();
foreach ($this->response['hits']['hits'] as $hit) {
$items[] = $this->instance->newFromElasticResults($hit);
}
return $items;
} | Builds a list of models from Elasticsearch
results.
@return array | entailment |
public function shards($key = null)
{
$shards = $this->response['_shards'];
if ($key and isset($shards[$key])) {
return $shards[$key];
}
return $shards;
} | Shards information.
@param null|string $key
@return array|string | entailment |
protected function renderText($text)
{
if ($this->enableNewlines) {
return preg_replace("/( \n|\n)/", "\\\\\\\\\n", $this->escapeLatex($text[1]));
} else {
return parent::renderText($text);
}
} | @inheritdocs
Parses a newline indicated by two spaces on the end of a markdown line. | entailment |
public function process($rawHtml, $name = '', $context = [], $environment = null)
{
try {
$html5 = new HTML5();
$document = $html5->loadHTML($rawHtml);
/** @var ExtractorExtension $extractorExtension */
$extractorExtension = $environment->getExtension(ExtractorExtension::class);
foreach ($document->getElementsByTagName('link') as $linkTag) {
/** @var DOMElement $linkTag */
if ($linkTag->getAttribute('rel') == 'stylesheet') {
$tokenisedStylesheet = explode('?', $linkTag->getAttribute('href'));
$stylesheet = reset($tokenisedStylesheet);
if ($content = $this->fileCache->fetch($stylesheet)) {
$extractorExtension->addBaseRules($content);
continue;
}
if (($content = @file_get_contents($stylesheet)) !== false) {
$this->fileCache->save($stylesheet, $content);
$extractorExtension->addBaseRules($content);
continue;
}
if (($content = @file_get_contents($_SERVER['DOCUMENT_ROOT'] . $stylesheet)) !== false) {
$this->fileCache->save($stylesheet, $content);
$extractorExtension->addBaseRules($content);
continue;
}
}
}
} catch (\Exception $exception) {
error_log($exception->getMessage());
return $rawHtml;
}
try {
$criticalCss = $extractorExtension->buildCriticalCssFromSnippets();
if (strlen($criticalCss) == 0) {
return $rawHtml;
}
} catch (Twig_Error_Runtime $tew) {
error_log($tew->getMessage());
return $rawHtml;
}
try {
$headStyle = new DOMElement('style', $criticalCss);
$document->getElementsByTagName('head')->item(0)->appendChild($headStyle);
return $html5->saveHTML($document);
} catch (\Exception $exception) {
error_log($exception->getMessage());
return $rawHtml;
}
} | @param string $rawHtml
@param string $name Template name
@param array $context The context used to render the template
@param Twig_Environment|null $environment The twig environment used, useful for accessing
@return string processedHtml | entailment |
public function createSender()
{
$stream = @stream_socket_server('udp://0.0.0.0:0', $errno, $errstr, STREAM_SERVER_BIND);
if ($stream === false) {
throw new RuntimeException('Unable to create sending socket: ' . $errstr, $errno);
}
return new DatagramSocket($this->loop, $stream);
} | Creates a socket capable of sending outgoing multicast datagrams and receiving
incoming unicast responses. It returns a [`SocketInterface`](#socketinterface) instance.
```php
$socket = $factory->createSender();
// send a multicast message to everybody listening on the given address
$socket->send('hello?', '224.10.20.30:4050');
// report incoming unicast replies
$socket->on('message', function ($data, $address) {
echo 'received ' . strlen($data) . ' bytes from ' . $address . PHP_EOL;
});
```
This method works on PHP versions as old as PHP 5.3 (and up), as its socket API has always been
[level 1 multicast conformant](https://www.tldp.org/HOWTO/Multicast-HOWTO-2.html#ss2.2).
@return \React\Datagram\SocketInterface
@throws RuntimeException | entailment |
public function createReceiver($address)
{
if (!defined('MCAST_JOIN_GROUP')) {
throw new BadMethodCallException('MCAST_JOIN_GROUP not defined (requires PHP 5.4+)');
}
if (!function_exists('socket_import_stream')) {
throw new BadMethodCallException('Function socket_import_stream missing (requires ext-sockets and PHP 5.4+)');
}
$parts = parse_url('udp://' . $address);
$stream = @stream_socket_server('udp://0.0.0.0:' . $parts['port'], $errno, $errstr, STREAM_SERVER_BIND);
if ($stream === false) {
throw new RuntimeException('Unable to create receiving socket: ' . $errstr, $errno);
}
$socket = socket_import_stream($stream);
if ($stream === false) {
throw new RuntimeException('Unable to access underlying socket resource');
}
// allow multiple processes to bind to the same address
$ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
if ($ret === false) {
throw new RuntimeException('Unable to enable SO_REUSEADDR');
}
// join multicast group and bind to port
$ret = socket_set_option(
$socket,
IPPROTO_IP,
MCAST_JOIN_GROUP,
array('group' => $parts['host'], 'interface' => 0)
);
if ($ret === false) {
throw new RuntimeException('Unable to join multicast group');
}
return new DatagramSocket($this->loop, $stream);
} | Creates a socket capable of receiving incoming multicast datagrams and sending
outgoing unicast or multicast datagrams. It returns a [`SocketInterface`](#socketinterface) instance.
```php
$socket = $factory->createReceiver('224.10.20.30:4050');
// report incoming multicast messages
$socket->on('message', function ($data, $remote) use ($socket) {
echo 'Sending back ' . strlen($data) . ' bytes to ' . $remote . PHP_EOL;
// send a unicast reply to the remote
$socket->send($data, $remote);
});
```
This method requires PHP 5.4 (or up) and `ext-sockets`.
Otherwise, it will throw a `BadMethodCallException`.
This is a requirement because receiving multicast datagrams requires a
[level 2 multicast conformant](https://www.tldp.org/HOWTO/Multicast-HOWTO-2.html#ss2.2)
socket API.
The required multicast socket options and constants have been added with
[PHP 5.4](http://php.net/manual/en/migration54.global-constants.php) (and up).
These options are only available to the low level socket API (ext-sockets), not
to the newer stream based networking API.
Internally, this library uses a workaround to create stream based sockets
and then sets the required socket options on its underlying low level socket
resource.
This is done because ReactPHP is built around the general purpose stream based API
and has only somewhat limited support for the low level socket API.
@param string $address
@return \React\Datagram\SocketInterface
@throws BadMethodCallException
@throws RuntimeException | entailment |
function initialize()
{
$a = func_get_args();
Debugger::log(__CLASS__ . ": " . __METHOD__ . "; args: " . print_r($a, true));
} | Initializes driver | entailment |
function addFile(FileUpload $file)
{
$a = func_get_args();
Debugger::log(__CLASS__ . ": " . __METHOD__ . "; args: " . print_r($a, true));
} | Adds file to queue
@param FileUpload $file | entailment |
protected function doRequest($request)
{
$slimRequest = $this->convertRequest($request);
$container = $this->app->getContainer();
/* @var $slimResponse ResponseInterface */
$slimResponse = $container->get('response');
// reset body stream
$slimResponse = $slimResponse->withBody(new Stream(fopen('php://temp', 'w+')));
$slimResponse = $this->app->process($slimRequest, $slimResponse);
return new BrowserKitResponse(
(string) $slimResponse->getBody(),
$slimResponse->getStatusCode(),
$slimResponse->getHeaders()
);
} | Makes a request.
@param BrowserKitRequest $request An origin request instance
@return BrowserKitResponse An origin response instance | entailment |
private function convertRequest(BrowserKitRequest $request)
{
$environment = Environment::mock($request->getServer());
$uri = Uri::createFromString($request->getUri());
$headers = Headers::createFromEnvironment($environment);
$cookies = Cookies::parseHeader($headers->get('Cookie', []));
$container = $this->app->getContainer();
/* @var $slimRequest ServerRequestInterface */
$slimRequest = $container->get('request');
$slimRequest = $slimRequest->withMethod($request->getMethod())
->withUri($uri)
->withUploadedFiles($this->convertFiles($request->getFiles()))
->withCookieParams($cookies);
foreach ($headers->keys() as $key) {
$slimRequest = $slimRequest->withHeader($key, $headers->get($key));
}
if ($request->getContent() !== null) {
$body = new RequestBody();
$body->write($request->getContent());
$slimRequest = $slimRequest
->withBody($body);
}
$parsed = [];
if ($request->getMethod() !== 'GET') {
$parsed = $request->getParameters();
}
// make sure we do not overwrite a request with a parsed body
if (!$slimRequest->getParsedBody()) {
$slimRequest = $slimRequest
->withParsedBody($parsed);
}
return $slimRequest;
} | Convert to PSR-7's ServerRequestInterface.
@param BrowserKitRequest $request
@return ServerRequestInterface | entailment |
function getQueue($token)
{
$a = func_get_args();
Debugger::log(__CLASS__ . ": " . __METHOD__ . "; args: " . print_r($a, true));
$q = new Queue();
$q->setQueueID($token);
$q->setQueuesModel($this);
return $q;
} | Gets queue
@param string $token
@return Queue | entailment |
public function handle(Throwable $e) : void
{
$this->honeybadger->notify($e);
call_user_func($this->previousHandler, $e);
} | @param \Throwable $e
@return void
@throws \Honeybadger\Exceptions\ServiceException | entailment |
public function ensureSymlinkExists($sourcePath, $symlinkPath)
{
if (!is_link($symlinkPath)) {
$this->ensureDirectoryExists(dirname($symlinkPath));
return symlink($sourcePath, $symlinkPath);
}
return false;
} | Create a symlink
@param string $sourcePath
@param string $symlinkPath
@return bool | entailment |
public function removeSymlink($symlinkPath)
{
if (is_link($symlinkPath)) {
if (!$this->unlink($symlinkPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to remove the symlink : ' . $symlinkPath);
// @codeCoverageIgnoreEnd
}
return true;
}
return false;
} | @param string $symlinkPath
@return bool
@throws \RuntimeException | entailment |
public function removeEmptyDirectory($directoryPath)
{
if (is_dir($directoryPath) && $this->isDirEmpty($directoryPath)) {
if (!$this->removeDirectory($directoryPath)) {
// @codeCoverageIgnoreStart
throw new \RuntimeException('Unable to remove the directory : ' . $directoryPath);
// @codeCoverageIgnoreEnd
}
return true;
}
return false;
} | @param string $directoryPath
@return bool
@throws \RuntimeException | entailment |
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
$this->packageDataManager->setPackageInstallationSource($initial);
$this->packageDataManager->setPackageInstallationSource($target);
// The package need only a code update because the version (branch), only the commit changed
if ($this->getInstallPath($initial) === $this->getInstallPath($target)) {
$this->createPackageVendorSymlink($target);
parent::update($repo, $initial, $target);
} else {
// If the initial package sources folder exists, uninstall it
$this->composer->getInstallationManager()->uninstall($repo, new UninstallOperation($initial));
// Install the target package
$this->composer->getInstallationManager()->install($repo, new InstallOperation($target));
}
} | {@inheritdoc} | entailment |
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if ($this->isSourceDirUnused($package) && $this->io->askConfirmation(
"The package version <info>" . $package->getPrettyName() . "</info> "
. "(<fg=yellow>" . $package->getPrettyVersion() . "</fg=yellow>) seems to be unused."
. PHP_EOL
. 'Do you want to <fg=red>delete the source folder</fg=red> ? [y/n] (default: no) : ',
false
)) {
$this->packageDataManager->setPackageInstallationSource($package);
parent::uninstall($repo, $package);
} else {
$this->binaryInstaller->removeBinaries($package);
$repo->removePackage($package);
}
$this->packageDataManager->removePackageUsage($package);
$this->removePackageVendorSymlink($package);
} | @param InstalledRepositoryInterface $repo
@param PackageInterface $package
@throws FilesystemException | entailment |
protected function isSourceDirUnused(PackageInterface $package)
{
$usageData = $this->packageDataManager->getPackageUsage($package);
return sizeof($usageData) <= 1;
} | Detect if other project use the dependency by using the "packages.json" file
@param PackageInterface $package
@return bool | entailment |
protected function getSymlinkSourcePath(PackageInterface $package)
{
if (null != $this->config->getSymlinkBasePath()) {
$targetDir = $package->getTargetDir();
$sourcePath =
$this->config->getSymlinkBasePath()
. '/' . $package->getPrettyName()
. '/' . $package->getPrettyVersion()
. ($targetDir ? '/' . $targetDir : '')
;
} else {
$sourcePath = $this->getInstallPath($package);
}
return $sourcePath;
} | @param PackageInterface $package
@return string | entailment |
protected function removePackageVendorSymlink(PackageInterface $package)
{
if (
$this->config->isSymlinkEnabled()
&& $this->filesystem->removeSymlink($this->getPackageVendorSymlink($package))
) {
$this->io->write(array(
' - Deleting symlink for <info>' . $package->getPrettyName() . '</info> '
. '(<fg=yellow>' . $package->getPrettyVersion() . '</fg=yellow>)',
''
));
$symlinkParentDirectory = dirname($this->getPackageVendorSymlink($package));
$this->filesystem->removeEmptyDirectory($symlinkParentDirectory);
}
} | @param PackageInterface $package
@throws FilesystemException | entailment |
function processFile($token, $file)
{
// Why not in one condition?
// @see http://forum.nettephp.com/cs/viewtopic.php?pid=29556#p29556
if (!$file instanceof FileUpload) {
return false;
}
/* @var $validateCallback Callback */
$validateCallback = MultipleFileUpload::$validateFileCallback;
/* @var $isValid bool */
$isValid = $validateCallback->invoke($file);
if ($isValid) {
MultipleFileUpload::getQueuesModel()
->getQueue($token)
->addFile($file);
}
return $isValid;
} | Process single file
@param string $token
@param FileUpload $file
@return bool | entailment |
public function isSharedPackage(PackageInterface $package)
{
$prettyName = $package->getPrettyName();
// Avoid putting this package into dependencies folder, because on the first installation the package won't be
// installed in dependencies folder but in the vendor folder.
// So I prefer keeping this behavior for further installs.
if (SharedPackageInstaller::PACKAGE_PRETTY_NAME === $prettyName) {
return false;
}
if ($this->areAllShared || SharedPackageInstaller::PACKAGE_TYPE === $package->getType()) {
return true;
}
foreach ($this->packageCallbacks as $equalityCallback) {
if ($equalityCallback($prettyName)) {
return true;
}
}
return false;
} | @param PackageInterface $package
@return bool | entailment |
protected function createCallbacks(array $packageList)
{
$callbacks = array();
foreach ($packageList as $packageName) {
// Has wild card (*)
if (false !== strpos($packageName, '*')) {
$pattern = str_replace('*', '[a-zA-Z0-9-_]+', str_replace('/', '\/', $packageName));
$callbacks[] = function ($packagePrettyName) use ($pattern) {
return 1 === preg_match('/' . $pattern . '/', $packagePrettyName);
};
// Raw package name
} else {
$callbacks[] = function ($packagePrettyName) use ($packageName) {
return $packageName === $packagePrettyName;
};
}
}
return $callbacks;
} | @param array $packageList
@return array | entailment |
public function getInstallPath(PackageInterface $package)
{
if ($this->solver->isSharedPackage($package)) {
return $this->symlinkInstaller->getInstallPath($package);
}
return $this->defaultInstaller->getInstallPath($package);
} | Returns the installation path of a package
@param PackageInterface $package
@return string | entailment |
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
// If both packages are not shared
if (!$this->solver->isSharedPackage($initial) && !$this->solver->isSharedPackage($target)) {
$this->defaultInstaller->update($repo, $initial, $target);
} else {
if (!$repo->hasPackage($initial)) {
throw new \InvalidArgumentException('Package is not installed : ' . $initial->getPrettyName());
}
$this->symlinkInstaller->update($repo, $initial, $target);
}
} | {@inheritdoc} | entailment |
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if ($this->solver->isSharedPackage($package)) {
if (!$repo->hasPackage($package)) {
throw new \InvalidArgumentException('Package is not installed : ' . $package->getPrettyName());
}
$this->symlinkInstaller->uninstall($repo, $package);
} else {
$this->defaultInstaller->uninstall($repo, $package);
}
} | @param InstalledRepositoryInterface $repo
@param PackageInterface $package
@throws FilesystemException | entailment |
public function notification(array $notification) : array
{
try {
$response = $this->client->post(
'notices',
['body' => json_encode($notification)]
);
} catch (Exception $e) {
throw ServiceException::generic();
}
if ($response->getStatusCode() !== Response::HTTP_CREATED) {
throw (new ServiceExceptionFactory($response))->make();
}
return (string) $response->getBody()
? json_decode($response->getBody(), true)
: [];
} | @param array $notification
@return array
@throws \Honeybadger\Exceptions\ServiceException | entailment |
public function checkin(string $key) : void
{
try {
$response = $this->client->head(sprintf('check_in/%s', $key));
} catch (Exception $e) {
throw ServiceException::generic();
}
if ($response->getStatusCode() !== Response::HTTP_OK) {
throw (new ServiceExceptionFactory($response))->make();
}
} | @param string $key
@return void
@throws \Honeybadger\Exceptions\ServiceException | entailment |
private function exception() : void
{
if ($this->response->getStatusCode() === Response::HTTP_FORBIDDEN) {
throw ServiceException::invalidApiKey();
}
if ($this->response->getStatusCode() === Response::HTTP_UNPROCESSABLE_ENTITY) {
throw ServiceException::invalidPayload();
}
if ($this->response->getStatusCode() === Response::HTTP_TOO_MANY_REQUESTS) {
throw ServiceException::rateLimit();
}
if ($this->response->getStatusCode() === Response::HTTP_INTERNAL_SERVER_ERROR) {
throw ServiceException::serverError();
}
throw ServiceException::generic();
} | @return void
@throws \Honeybadger\Exceptions\ServiceException | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.