sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function handle()
{
$extension = $this->argument('extension');
if (empty($extension) || !array_has(Admin::$extensions, $extension)) {
$extension = $this->choice('Please choose a extension to import', array_keys(Admin::$extensions));
}
$className = array_get(Admin::$extensions, $extension);
if (!class_exists($className) || !method_exists($className, 'import')) {
$this->error("Invalid Extension [$className]");
return;
}
call_user_func([$className, 'import'], $this);
$this->info("Extension [$className] imported");
} | Execute the console command. | entailment |
public function getInMethod(string $method): array
{
if (isset($this->methodIndex[$method])) {
return $this->methodIndex[$method];
}
return [];
} | @param string $method
@return Tombstone[] | entailment |
public static function fromHeader(string $string)
{ /* : ?self */
$parts = \array_map("trim", \explode(";", $string));
$nameValue = \explode("=", \array_shift($parts), 2);
if (\count($nameValue) !== 2) {
return null;
}
list($name, $value) = $nameValue;
$name = \trim($name);
$value = \trim($value, " \t\n\r\0\x0B\"");
if ($name === "") {
return null;
}
// httpOnly must default to false for parsing
$meta = CookieAttributes::empty();
foreach ($parts as $part) {
$pieces = \array_map('trim', \explode('=', $part, 2));
$key = \strtolower($pieces[0]);
if (1 === \count($pieces)) {
switch ($key) {
case 'secure':
$meta = $meta->withSecure();
break;
case 'httponly':
$meta = $meta->withHttpOnly();
break;
}
} else {
switch ($key) {
case 'expires':
$time = \DateTime::createFromFormat('D, j M Y G:i:s T', $pieces[1]);
if ($time === false) {
break; // break is correct, see https://tools.ietf.org/html/rfc6265#section-5.2.1
}
$meta = $meta->withExpiry($time);
break;
case 'max-age':
$maxAge = \trim($pieces[1]);
// This also allows +1.42, but avoids a more complicated manual check
if (!\is_numeric($maxAge)) {
break; // break is correct, see https://tools.ietf.org/html/rfc6265#section-5.2.2
}
$meta = $meta->withMaxAge($maxAge);
break;
case 'path':
$meta = $meta->withPath($pieces[1]);
break;
case 'domain':
$meta = $meta->withDomain($pieces[1]);
break;
}
}
}
try {
return new self($name, $value, $meta);
} catch (InvalidCookieException $e) {
return null;
}
} | Parses a cookie from a 'set-cookie' header.
@param string $string Valid 'set-cookie' header line.
@return self|null Returns a `ResponseCookie` instance on success and `null` on failure. | entailment |
public function fire()
{
// Assets
Assets::withChain([
new Location($this->token), new Names($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Bookmarks
Bookmarks::withChain([
new Folders($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Calendar
Events::withChain([
new Detail($this->token), new Attendees($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Character
Info::dispatch($this->token)->onQueue($this->queue);
AgentsResearch::dispatch($this->token)->onQueue($this->queue);
Blueprints::dispatch($this->token)->onQueue($this->queue);
CorporationHistory::dispatch($this->token)->onQueue($this->queue);
Fatigue::dispatch($this->token)->onQueue($this->queue);
Medals::dispatch($this->token)->onQueue($this->queue);
Notifications::dispatch($this->token)->onQueue($this->queue);
Roles::dispatch($this->token)->onQueue($this->queue);
Standings::dispatch($this->token)->onQueue($this->queue);
Stats::dispatch($this->token)->onQueue($this->queue);
Titles::dispatch($this->token)->onQueue($this->queue);
// Clones
Clones::withChain([
new Implants($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Contacts
Contacts::withChain([
new ContactLabels($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Contracts
Contracts::withChain([
new Items($this->token), new Bids($this->token),
])->dispatch($this->token)->onQueue($this->queue);
// Fittings
Fittings::dispatch($this->token)->onQueue($this->queue);
// Industry
Jobs::dispatch($this->token)->onQueue($this->queue);
Mining::dispatch($this->token)->onQueue($this->queue);
// Killmails
Recent::withChain([
new KillmailDetail($this->token), ]
)->dispatch($this->token)->onQueue($this->queue);
// Location
Location::dispatch($this->token)->onQueue($this->queue);
Online::dispatch($this->token)->onQueue($this->queue);
Ship::dispatch($this->token)->onQueue($this->queue);
// Mail
Headers::withChain([
new Bodies($this->token), new Labels($this->token),
])->dispatch($this->token)->onQueue($this->queue);
MailingLists::dispatch($this->token)->onQueue($this->queue);
// Market
Orders::dispatch($this->token)->onQueue($this->queue);
// Planetary Interactions
Planets::withChain([
new PlanetDetail($this->token), ]
)->dispatch($this->token)->onQueue($this->queue);
// Skills
Attributes::dispatch($this->token)->onQueue($this->queue);
Queue::dispatch($this->token)->onQueue($this->queue);
Skills::dispatch($this->token)->onQueue($this->queue);
// Structures
Structures::dispatch($this->token)->onQueue($this->queue);
// Wallet
Balance::dispatch($this->token)->onQueue($this->queue);
Journal::dispatch($this->token)->onQueue($this->queue);
Transactions::dispatch($this->token)->onQueue($this->queue);
} | Fires the command.
@return mixed|void | entailment |
public function all()
{
$params = [];
foreach ($this->methodRequirements as $key => $config) {
$params[$key] = $this->get($key);
}
return $params;
} | Fetches all required parameters from the current Request body.
@return array | entailment |
public function get($name)
{
if (!$paramConfig = $this->methodRequirements[$name]) {
return;
}
$config = new Credential($name, $paramConfig);
if (true === $config->required && !($this->getRequest()->request->has($name))) {
throw new BadRequestUserException(
$this->formatError($name, false, 'The parameter must be set')
);
}
$param = $this->getRequest()->request->get($name);
if (false === $config->nullable && !$param) {
throw new BadRequestUserException(
$this->formatError($name, $param, 'The parameter cannot be null')
);
}
if (($config->default && $param === $config->default
|| ($param === null && true === $config->nullable)
|| (null === $config->requirements))) {
return $param;
}
$this->validateParam($config, $param);
return $param;
} | Fetches a given parameter from the current Request body.
@param string $name The parameter key
@return mixed The parameter value | entailment |
private function validateParam(Credential $config, $param)
{
$name = $config->name;
if (null === $requirements = $config->requirements) {
return;
}
foreach ($requirements as $constraint) {
if (is_scalar($constraint)) {
$constraint = new Regex([
'pattern' => '#^'.$constraint.'$#xsu',
'message' => sprintf('Does not match "%s"', $constraint),
]);
} elseif (is_array($constraint)) {
continue;
}
if ($constraint instanceof UniqueEntity) {
$object = $config->class;
$accessor = PropertyAccess::createPropertyAccessor();
if ($accessor->isWritable($object, $name)) {
$accessor->setValue($object, $name, $param);
} else {
throw new BadRequestUserException(
sprintf('The @UniqueEntity constraint must be used on an existing property. The class "%s" does not have a property "%s"', get_class($object), $name)
);
}
$errors = $this->validator->validate($object, $constraint);
} else {
$errors = $this->validator->validate($param, $constraint);
}
if (0 !== count($errors)) {
$error = $errors[0];
throw new BadRequestUserException(
$this->formatError($name, $error->getInvalidValue(), $error->getMessage())
);
}
}
} | Handle requirements validation.
@param Param $param
@throws BadRequestUserException If the param is not valid
@return Param | entailment |
private function formatError($key, $invalidValue, $errorMessage)
{
return sprintf(
false === $invalidValue
? 'Request parameter %s must be set'
: "Request parameter %s value '%s' violated a requirement (%s)",
$key,
$invalidValue,
$errorMessage
);
} | {@inheritdoc} | entailment |
private function getRequest()
{
if ($this->requestStack instanceof Request) {
$request = $this->requestStack;
} elseif ($this->requestStack instanceof RequestStack) {
$request = $this->requestStack->getCurrentRequest();
}
if ($request !== null) {
return $request;
}
throw new \RuntimeException('There is no current request.');
} | @throws \RuntimeException
@return Request | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
$this->configureProcessProperties($resolver);
$this->configureStartControlProperties($resolver);
$this->configureStopControlProperties($resolver);
$resolver
->setDefined('user')
->setAllowedTypes('user', 'string');
$this->configureLogProperties($resolver);
$this->configureEnvironmentProperty($resolver);
$resolver
->setDefined('directory')
->setAllowedTypes('directory', 'string');
// TODO: octal vs. decimal value
$resolver->setDefined('umask')
->setAllowedTypes('umask', 'int');
$resolver
->setDefined('serverurl')
->setAllowedTypes('serverurl', 'string');
} | {@inheritdoc} | entailment |
private function configureProcessProperties(OptionsResolver $resolver)
{
$resolver
->setRequired('command')
->setAllowedTypes('command', 'string');
$resolver
->setDefined('process_name')
->setAllowedTypes('process_name', 'string');
$resolver->setDefined('numprocs')
->setAllowedTypes('numprocs', 'int');
$resolver->setDefined('numprocs_start')
->setAllowedTypes('numprocs_start', 'int');
$resolver->setDefined('priority')
->setAllowedTypes('priority', 'int');
} | Configures process related properties.
@param OptionsResolver $resolver | entailment |
private function configureStartControlProperties(OptionsResolver $resolver)
{
$resolver->setDefined('autostart')
->setAllowedTypes('autostart', 'bool');
$resolver
->setDefined('autorestart')
->setAllowedTypes('autorestart', ['bool', 'string'])
->setAllowedValues('autorestart', [true, false, 'true', 'false', 'unexpected'])
->setNormalizer('autorestart', function (Options $options, $value) {
return (is_bool($value) or $value === 'unexpected') ? $value : ($value === 'true' ? true : false);
});
$resolver->setDefined('startsecs')
->setAllowedTypes('startsecs', 'int');
$resolver->setDefined('startretries')
->setAllowedTypes('startretries', 'int');
} | Configures start control related properties.
@param OptionsResolver $resolver | entailment |
private function configureStopControlProperties(OptionsResolver $resolver)
{
$resolver->setDefined('exitcodes');
$this->configureArrayProperty('exitcodes', $resolver);
$resolver
->setDefined('stopsignal')
->setAllowedTypes('stopsignal', 'string')
->setAllowedValues('stopsignal', ['TERM', 'HUP', 'INT', 'QUIT', 'KILL', 'USR1', 'USR2']);
$resolver->setDefined('stopwaitsecs')
->setAllowedTypes('stopwaitsecs', 'int');
$resolver->setDefined('stopasgroup')
->setAllowedTypes('stopasgroup', 'bool');
$resolver->setDefined('killasgroup')
->setAllowedTypes('killasgroup', 'bool');
} | Configures stop control related properties.
@param OptionsResolver $resolver | entailment |
private function configureLogProperties(OptionsResolver $resolver)
{
$resolver->setDefined('redirect_stderr')
->setAllowedTypes('redirect_stderr', 'bool');
$this->configureStdoutLogProperties($resolver);
$this->configureStderrLogProperties($resolver);
} | Configures log related properties.
@param OptionsResolver $resolver | entailment |
private function configureStdoutLogProperties(OptionsResolver $resolver)
{
$resolver
->setDefined('stdout_logfile')
->setAllowedTypes('stdout_logfile', 'string');
$resolver->setDefined('stdout_logfile_maxbytes');
$this->configureByteProperty('stdout_logfile_maxbytes', $resolver);
$resolver->setDefined('stdout_logfile_backups')
->setAllowedTypes('stdout_logfile_backups', 'int');
$resolver->setDefined('stdout_capture_maxbytes');
$this->configureByteProperty('stdout_capture_maxbytes', $resolver);
$resolver->setDefined('stdout_events_enabled')
->setAllowedTypes('stdout_events_enabled', 'bool');
$resolver->setDefined('stdout_syslog')
->setAllowedTypes('stdout_syslog', 'bool');
} | Configures stdout log related properties.
@param OptionsResolver $resolver | entailment |
private function configureStderrLogProperties(OptionsResolver $resolver)
{
$resolver
->setDefined('stderr_logfile')
->setAllowedTypes('stderr_logfile', 'string');
$resolver->setDefined('stderr_logfile_maxbytes');
$this->configureByteProperty('stderr_logfile_maxbytes', $resolver);
$resolver->setDefined('stderr_logfile_backups')
->setAllowedTypes('stderr_logfile_backups', 'int');
$resolver->setDefined('stderr_capture_maxbytes');
$this->configureByteProperty('stderr_capture_maxbytes', $resolver);
$resolver->setDefined('stderr_events_enabled')
->setAllowedTypes('stderr_events_enabled', 'bool');
$resolver->setDefined('stderr_syslog')
->setAllowedTypes('stderr_syslog', 'bool');
} | Configures stderr log related properties.
@param OptionsResolver $resolver | entailment |
protected function convertToResource($data)
{
return Holding::make($this->client, $this->bib, $data->holding_id)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Holding | entailment |
public static function fromHeader(string $string): array
{
$cookies = \explode(";", $string);
$result = [];
try {
foreach ($cookies as $cookie) {
$parts = \explode('=', $cookie, 2);
if (2 !== \count($parts)) {
return [];
}
list($name, $value) = $parts;
// We can safely trim quotes, as they're not allowed within cookie values
$result[] = new self(\trim($name), \trim($value, " \t\""));
}
} catch (InvalidCookieException $e) {
return [];
}
return $result;
} | Parses the cookies from a 'cookie' header.
Note: Parsing is aborted if there's an invalid value and no cookies are returned.
@param string $string Valid 'cookie' header line.
@return RequestCookie[] | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
$resolver
->setRequired('files')
->setAllowedTypes('files', ['string', 'array'])
->setNormalizer('files', function (Options $options, $value) {
return is_string($value) ? $value : implode(' ', $value);
});
} | {@inheritdoc} | entailment |
public function withExpiry(\DateTimeInterface $date): self
{
$new = clone $this;
if ($date instanceof \DateTimeImmutable) {
$new->expiry = $date;
} elseif ($date instanceof \DateTime) {
$new->expiry = \DateTimeImmutable::createFromMutable($date);
} else {
$new->expiry = new \DateTimeImmutable("@" . $date->getTimestamp());
}
return $new;
} | Applies the given expiry to the cookie.
@param \DateTimeInterface $date
@return self Cloned instance with the specified operation applied.
@see self::withMaxAge()
@see self::withoutExpiry()
@link https://tools.ietf.org/html/rfc6265#section-5.2.1 | entailment |
public function getSize()
{
if (!$this->stream) {
return null;
}
$stats = fstat($this->stream);
if (isset($stats['size'])) {
return $stats['size'];
}
return null;
} | Get the size of the stream if known.
@return int|null Returns the size in bytes if known, or null if unknown. | entailment |
public function tell()
{
if (!$this->stream) {
throw new RuntimeException('No stream');
}
$position = ftell($this->stream);
if (!$position) {
throw new RuntimeException('Cannot get current position');
}
return $position;
} | Returns the current position of the file read/write pointer
@return int Position of the file pointer
@throws \RuntimeException on error. | entailment |
public function rewind()
{
if (!$this->stream) {
throw new RuntimeException("No stream attached");
}
if (!$this->isSeekable() || rewind($this->stream) === false) {
throw new RuntimeException('Could not rewind stream');
}
} | Seek to the beginning of the stream.
If the stream is not seekable, this method will raise an exception;
otherwise, it will perform a seek(0).
@see seek()
@link http://www.php.net/manual/en/function.fseek.php
@throws \RuntimeException on failure. | entailment |
public function isWritable()
{
if ($this->stream) {
$meta = $this->getMetadata();
$writableModes = ['r+', 'w', 'w+', 'a', 'a+', 'x', 'x+', 'c', 'c+'];
foreach ($writableModes as $mode) {
if (strpos($meta['mode'], $mode) === 0) {
return true;
}
}
}
return false;
} | Returns whether or not the stream is writable.
@return bool | entailment |
public function isReadable()
{
if ($this->stream) {
$meta = $this->getMetadata();
$readableModes = ['r', 'r+', 'w+', 'a+', 'x+', 'c+'];
foreach ($readableModes as $mode) {
if (strpos($meta['mode'], $mode) === 0) {
return true;
}
}
}
return false;
} | Returns whether or not the stream is readable.
@return bool | entailment |
public function getContents()
{
if (!$this->stream) {
throw new RuntimeException("No stream attached");
}
if (!$this->isReadable() || ($contents = stream_get_contents($this->stream)) === false) {
throw new RuntimeException('Could not get contents of stream');
}
return $contents;
} | Returns the remaining contents in a string
@return string
@throws \RuntimeException if unable to read or an error occurs while
reading. | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
$resolver
->setDefined('serverurl')
->setAllowedTypes('serverurl', 'string');
$resolver
->setDefined('username')
->setAllowedTypes('username', 'string');
$resolver
->setDefined('password')
->setAllowedTypes('password', ['string', 'numeric']);
$resolver
->setDefined('prompt')
->setAllowedTypes('prompt', 'string');
$resolver
->setDefined('history_file')
->setAllowedTypes('history_file', 'string');
} | {@inheritdoc} | entailment |
protected function convertToResource($data)
{
return Library::make($this->client, $data->code)
->init($data);
} | Convert a data element to a resource object.
@param $data
@return Library | entailment |
public function addField($name, array $attributes)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$this->addFields[$name] = $attributes;
return $this;
} | Adds a field in the table
@param *string $name Column name
@param *array $attributes Column attributes
@return Eden\Mysql\Alter | entailment |
public function changeField($name, array $attributes)
{
//Argument 1 must be a string
Argument::i()->test(1, 'string');
$this->changeFields[$name] = $attributes;
return $this;
} | Changes attributes of the table given
the field name
@param *string $name Column name
@param *array $attributes Column attributes
@return Eden\Mysql\Alter | entailment |
public function getSEOScoreTips() {
$score_criteria_tips = array(
'pagesubject_defined' => _t('SEO.SEOScoreTipPageSubjectDefined', 'Page subject is not defined for page'),
'pagesubject_in_title' => _t('SEO.SEOScoreTipPageSubjectInTitle', 'Page subject is not in the title of this page'),
'pagesubject_in_firstparagraph' => _t('SEO.SEOScoreTipPageSubjectInFirstParagraph', 'Page subject is not present in the first paragraph of the content of this page'),
'pagesubject_in_url' => _t('SEO.SEOScoreTipPageSubjectInURL', 'Page subject is not present in the URL of this page'),
'pagesubject_in_metadescription' => _t('SEO.SEOScoreTipPageSubjectInMetaDescription', 'Page subject is not present in the meta description of the page'),
'numwords_content_ok' => _t('SEO.SEOScoreTipNumwordsContentOk', 'The content of this page is too short and does not have enough words. Please create content of at least 300 words based on the Page subject.'),
'pagetitle_length_ok' => _t('SEO.SEOScoreTipPageTitleLengthOk', 'The title of the page is not long enough and should have a length of at least 40 characters.'),
'content_has_links' => _t('SEO.SEOScoreTipContentHasLinks', 'The content of this page does not have any (outgoing) links.'),
'page_has_images' => _t('SEO.SEOScoreTipPageHasImages', 'The content of this page does not have any images.'),
'content_has_subtitles' => _t('SEO.SEOScoreTipContentHasSubtitles', 'The content of this page does not have any subtitles'),
'images_have_alt_tags' => _t('SEO.SEOScoreTipImagesHaveAltTags', 'All images on this page do not have alt tags'),
'images_have_title_tags' => _t('SEO.SEOScoreTipImagesHaveTitleTags', 'All images on this page do not have title tags')
);
return $score_criteria_tips;
} | getSEOScoreTips.
Get array of tips translated in current locale
@param none
@return array $score_criteria_tips Associative array with translated tips | entailment |
public function updateCMSFields(FieldList $fields) {
// exclude SEO tab from some pages
$excluded = Config::inst()->get(self::class, 'excluded_page_types');
if ($excluded) {
if (in_array($this->owner->getClassName(), $excluded)) {
return;
}
}
Requirements::css('hubertusanton/silverstripe-seo:css/seo.css');
Requirements::javascript('hubertusanton/silverstripe-seo:javascript/seo.js');
// better do this below in some init method? :
$this->getSEOScoreCalculation();
$this->setSEOScoreTipsUL();
// lets create a new tab on top
$fields->addFieldsToTab('Root.SEO', array(
LiteralField::create('googlesearchsnippetintro', '<h3>' . _t('SEO.SEOGoogleSearchPreviewTitle', 'Preview google search') . '</h3>'),
LiteralField::create('googlesearchsnippet', '<div id="google_search_snippet"></div>'),
LiteralField::create('siteconfigtitle', '<div id="ss_siteconfig_title">' . $this->owner->getSiteConfig()->Title . '</div>'),
));
// move Metadata field from Root.Main to SEO tab for visualising direct impact on search result
$fields->removeFieldFromTab('Root.Main', 'Metadata');
/*$fields->addFieldToTab("Root.SEO", new TabSet('Options',
new Tab('Metadata', _t('SEO.SEOMetaData', 'Meta Data')),
new Tab('HelpAndSEOScore', _t('SEO.SEOHelpAndScore', 'Help and SEO Score'))
));*/
$fields->addFieldsToTab('Root.SEO', array(
TextareaField::create("MetaDescription", $this->owner->fieldLabel('MetaDescription'))
->setRightTitle(
_t(
'SiteTree.METADESCHELP',
"Search engines use this content for displaying search results (although it will not influence their ranking)."
)
)
->addExtraClass('help'),
TextareaField::create("ExtraMeta",$this->owner->fieldLabel('ExtraMeta'))
->setRightTitle(
_t(
'SiteTree.METAEXTRAHELP',
"HTML tags for additional meta information. For example <meta name=\"customName\" content=\"your custom content here\" />"
)
)
->addExtraClass('help')
)
);
$fields->addFieldsToTab('Root.SEO', array(
GoogleSuggestField::create("SEOPageSubject", _t('SEO.SEOPageSubjectTitle', 'Subject of this page (required to view this page SEO score)')),
LiteralField::create('', '<div class="message notice"><p>' .
_t(
'SEO.SEOSaveNotice',
"After making changes save this page to view the updated SEO score"
) . '</p></div>'),
LiteralField::create('ScoreTitle', '<h4 class="seo_score">' . _t('SEO.SEOScore', 'SEO Score') . '</h4>'),
LiteralField::create('Score', $this->getHTMLStars()),
LiteralField::create('ScoreClear', '<div class="score_clear"></div>')
)
);
if ($this->checkPageSubjectDefined()) {
$fields->addFieldsToTab('Root.SEO', array(
LiteralField::create('SimplePageSubjectCheckValues', $this->getHTMLSimplePageSubjectTest())
)
);
}
if ($this->seo_score < 12) {
$fields->addFieldsToTab('Root.SEO', array(
LiteralField::create('ScoreTipsTitle', '<h4 class="seo_score">' . _t('SEO.SEOScoreTips', 'SEO Score Tips') . '</h4>'),
LiteralField::create('ScoreTips', $this->seo_score_tips)
)
);
}
} | updateCMSFields.
Update Silverstripe CMS Fields for SEO Module
@param FieldList
@return none | entailment |
public function getHTMLStars() {
$treshold_score = $this->seo_score - 2 < 0 ? 0 : $this->seo_score - 2;
$num_stars = intval(ceil($treshold_score) / 2);
$num_nostars = 5 - $num_stars;
$html = '<div id="fivestar-widget">';
for ($i = 1; $i <= $num_stars; $i++) {
$html .= '<div class="star on"></div>';
}
if ($treshold_score % 2) {
$html .= '<div class="star on-half"></div>';
$num_nostars--;
}
for ($i = 1; $i <= $num_nostars; $i++) {
$html .= '<div class="star"></div>';
}
$html .= '</div>';
return $html;
} | getHTMLStars.
Get html of stars rating in CMS, maximum score is 12
threshold 2
@param none
@return String $html | entailment |
public function MetaTags(&$tags) {
$siteConfig = SiteConfig::current_site_config();
// facebook OpenGraph
/*
$tags .= '<meta property="og:locale" content="' . i18n::get_locale() . '" />' . "\n";
$tags .= '<meta property="og:title" content="' . $this->owner->Title . '" />' . "\n";
$tags .= '<meta property="og:description" content="' . $this->owner->MetaDescription . '" />' . "\n";
$tags .= '<meta property="og:url" content=" ' . $this->owner->AbsoluteLink() . ' " />' . "\n";
$tags .= '<meta property="og:site_name" content="' . $siteConfig->Title . '" />' . "\n";
$tags .= '<meta property="og:type" content="article" />' . "\n";
*/
//$tags .= '<meta property="og:image" content="" />' . "\n";
if (Config::inst()->get('SeoObjectExtension', 'use_webmaster_tag')) {
$tags .= $siteConfig->GoogleWebmasterMetaTag . "\n";
}
} | /* MetaTags
Hooks into MetaTags SiteTree method and adds MetaTags for
Sharing of this page on Social Media (Facebook / Google+) | entailment |
public function getSEOScoreCalculation() {
$this->score_criteria['pagesubject_defined'] = $this->checkPageSubjectDefined();
$this->score_criteria['pagesubject_in_title'] = $this->checkPageSubjectInTitle();
$this->score_criteria['pagesubject_in_firstparagraph'] = $this->checkPageSubjectInFirstParagraph();
$this->score_criteria['pagesubject_in_url'] = $this->checkPageSubjectInUrl();
$this->score_criteria['pagesubject_in_metadescription'] = $this->checkPageSubjectInMetaDescription();
$this->score_criteria['numwords_content_ok'] = $this->checkNumWordsContent();
$this->score_criteria['pagetitle_length_ok'] = $this->checkPageTitleLength();
$this->score_criteria['content_has_links'] = $this->checkContentHasLinks();
$this->score_criteria['page_has_images'] = $this->checkPageHasImages();
$this->score_criteria['content_has_subtitles'] = $this->checkContentHasSubtitles();
$this->score_criteria['images_have_alt_tags'] = $this->checkImageAltTags();
$this->score_criteria['images_have_title_tags'] = $this->checkImageTitleTags();
$this->seo_score = intval(array_sum($this->score_criteria));
} | getSEOScoreCalculation.
Do SEO score calculation and set class Array score_criteria 12 corresponding assoc values
Also set class Integer seo_score with score 0-12 based on values which are true in score_criteria array
Do SEO score calculation and set class Array score_criteria 11 corresponding assoc values
Also set class Integer seo_score with score 0-12 based on values which are true in score_criteria array
@param none
@return none, set class array score_criteria tips boolean | entailment |
public function setSEOScoreTipsUL() {
$tips = $this->getSEOScoreTips();
$this->seo_score_tips = '<ul id="seo_score_tips">';
foreach ($this->score_criteria as $index => $crit) {
if (!$crit) {
$this->seo_score_tips .= '<li>' . $tips[$index] . '</li>';
}
}
$this->seo_score_tips .= '</ul>';
} | setSEOScoreTipsUL.
Set SEO Score tips ul > li for SEO tips literal field, based on score_criteria
@param none
@return none, set class string seo_score_tips with tips html | entailment |
private function createDOMDocumentFromHTML($html = null) {
if ($html != null) {
libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($html);
libxml_clear_errors();
libxml_use_internal_errors(false);
return $dom;
}
} | checkContentHasSubtitles.
check if page Content has a h2's in it
@param HTMLText $html String
@return DOMDocument Object | entailment |
public function checkPageSubjectInImageAltTags() {
$html = $this->getPageContent();
// for newly created page
if ($html == '') {
return false;
}
$dom = $this->createDOMDocumentFromHTML($html);
$images = $dom->getElementsByTagName('img');
foreach($images as $image){
if($image->hasAttribute('alt') && $image->getAttribute('alt') != ''){
if (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $image->getAttribute('alt'))) {
return true;
}
}
}
return false;
} | checkPageSubjectInImageAlt.
Checks if image alt tags contain page subject
@param none
@return boolean | entailment |
private function checkImageAltTags() {
$html = $this->getPageContent();
// for newly created page
if ($html == '') {
return false;
}
$dom = $this->createDOMDocumentFromHTML($html);
$images = $dom->getElementsByTagName('img');
$imagesWithAltTags = 0;
foreach($images as $image){
if($image->hasAttribute('alt') && $image->getAttribute('alt') != ''){
$imagesWithAltTags++;
}
}
if($imagesWithAltTags == $images->length){
return true;
}
return false;
} | checkImageAltTags.
Checks if images in content have alt tags
@param none
@return boolean | entailment |
private function checkImageTitleTags() {
$html = $this->getPageContent();
// for newly created page
if ($html == '') {
return false;
}
$dom = $this->createDOMDocumentFromHTML($html);
$images = $dom->getElementsByTagName('img');
$imagesWithTitleTags = 0;
foreach($images as $image){
if($image->hasAttribute('title') && $image->getAttribute('title') != ''){
//echo $image->getAttribute('title') . '<br>';
$imagesWithTitleTags++;
}
}
if($imagesWithTitleTags == $images->length){
return true;
}
return false;
} | checkImageTitleTags.
Checks if images in content have title tags
@param none
@return boolean | entailment |
public function checkPageSubjectInTitle() {
if ($this->checkPageSubjectDefined()) {
if (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $this->owner->MetaTitle)) {
return true;
} elseif (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $this->owner->Title)) {
return true;
} else {
return false;
}
}
return false;
} | checkPageSubjectInTitle.
Checks if defined PageSubject is present in the Page Title
@param none
@return boolean | entailment |
public function checkPageSubjectInContent() {
if ($this->checkPageSubjectDefined()) {
if (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $this->getPageContent())) {
return true;
}
else {
return false;
}
}
return false;
} | checkPageSubjectInContent.
Checks if defined PageSubject is present in the Page Content
@param none
@return boolean | entailment |
public function checkPageSubjectInFirstParagraph() {
if ($this->checkPageSubjectDefined()) {
$first_paragraph = $this->owner->dbObject('Content')->FirstParagraph();
if (trim($first_paragraph != '')) {
if (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $first_paragraph)) {
return true;
}
else {
return false;
}
}
}
return false;
} | checkPageSubjectInFirstParagraph.
Checks if defined PageSubject is present in the Page Content's First Paragraph
@param none
@return boolean | entailment |
public function checkPageSubjectInUrl() {
if ($this->checkPageSubjectDefined()) {
$url_segment = $this->owner->URLSegment;
$pagesubject_url_segment = $this->owner->generateURLSegment($this->owner->SEOPageSubject);
if (preg_match('/' . preg_quote($pagesubject_url_segment, '/') . '/i', $url_segment)) {
return true;
}
else {
return false;
}
}
return false;
} | checkPageSubjectInUrl.
Checks if defined PageSubject is present in the Page URLSegment
@param none
@return boolean | entailment |
public function checkPageSubjectInMetaDescription() {
if ($this->checkPageSubjectDefined()) {
if (preg_match('/' . preg_quote($this->owner->SEOPageSubject, '/') . '/i', $this->owner->MetaDescription)) {
return true;
}
else {
return false;
}
}
return false;
} | checkPageSubjectInMetaDescription.
Checks if defined PageSubject is present in the Page MetaDescription
@param none
@return boolean | entailment |
private function checkPageTitleLength() {
$site_title_length = strlen($this->owner->getSiteConfig()->Title);
// 3 is length of divider, this could all be done better ...
return (($this->getNumCharsTitle() + 3 + $site_title_length) >= 40) ? true : false;
} | checkPageTitleLength.
check if length of Title and SiteConfig.Title has a minimal of 40 chars
@param none
@return boolean | entailment |
private function checkPageHasImages() {
$html = $this->getPageContent();
// for newly created page
if ($html == '') {
return false;
}
$dom = $this->createDOMDocumentFromHTML($html);
$elements = $dom->getElementsByTagName('img');
return ($elements->length) ? true : false;
} | checkPageHasImages.
check if page Content has a img's in it
@param none
@return boolean | entailment |
public function getPageContent()
{
$response = Director::test($this->owner->Link());
if (!$response->isError()) {
return $response->getBody();
}
return '';
} | getPageContent
function to get html content of page which SEO score is based on
(we use the same info as gets back from $Layout in template) | entailment |
public static function fromSruRecord(SruRecord $record, Client $client = null)
{
$record->data->registerXPathNamespace('marc', 'http://www.loc.gov/MARC21/slim');
$mmsId = $record->data->text('.//marc:controlfield[@tag="001"]');
return (new self($client, $mmsId))
->setMarcRecord($record->data->asXML());
} | Initialize from SRU record without having to fetch the Bib record.
@param SruRecord $record
@param Client|null $client
@return Bib | entailment |
public function save()
{
// If initialized from an SRU record, we need to fetch the
// remaining parts of the Bib record.
$this->init();
// Inject the MARC record
$marcXml = new QuiteSimpleXMLElement($this->_marc->toXML('UTF-8', false, false));
$this->data->first('record')->replace($marcXml);
// Serialize
$newData = $this->data->asXML();
// Alma doesn't like namespaces
$newData = str_replace(' xmlns="http://www.loc.gov/MARC21/slim"', '', $newData);
return $this->client->putXML($this->url(), $newData);
} | Save the MARC record. | entailment |
public function getNzMmsId()
{
// If initialized from an SRU record, we need to fetch the
// remaining parts of the Bib record.
$this->init();
$nz_mms_id = $this->data->text("linked_record_id[@type='NZ']");
if (!$nz_mms_id) {
throw new NoLinkedNetworkZoneRecordException("Record $this->mms_id is not linked to a network zone record.");
}
return $nz_mms_id;
} | Get the MMS ID of the linked record in network zone. | entailment |
protected function configureProperties(OptionsResolver $resolver)
{
$resolver->setRequired('programs');
$this->configureArrayProperty('programs', $resolver);
$resolver->setDefined('priority')
->setAllowedTypes('priority', 'int');
} | {@inheritdoc} | entailment |
public function load(Configuration $configuration = null)
{
try {
$ini = $this->getParser()->parse($this->string);
} catch (ParserException $e) {
throw new LoaderException('Cannot parse INI', 0, $e);
}
return $this->parseSections($ini, $configuration);
} | {@inheritdoc} | entailment |
public function handle()
{
$offline = $this->option('offline');
if ($offline)
$this->info('Checking Local Versions Only');
else
$this->info('Checking Local and Github Versions. Please wait...');
$client = $this->client;
$base_url = $this->base_url;
$headers = [
'Accept' => 'application/json',
];
$this->table(['Package Name', 'Local Version', 'Latest Github'],
array_map(function ($package) use ($offline, $base_url, $client, $headers) {
if ($offline) {
return [
ucfirst($package),
config($package . '.config.version'),
'Offline',
];
}
$url = str_replace(':repo', 'eveseat/' . $package, $base_url);
return [
ucfirst($package),
config($package . '.config.version'),
json_decode($client->get($url, $headers)->getBody())->tag_name,
];
}, $this->packages));
} | Execute the console command. | entailment |
public function valid()
{
if (!isset($this->resources[$this->position])) {
$this->fetchBatch();
}
return isset($this->resources[$this->position]);
} | Checks if current position is valid.
@link http://php.net/manual/en/iterator.valid.php
@return bool | entailment |
public function run()
{
for ($i = 1; $i <= $this->maxRetry; $i++) {
try {
return call_user_func_array($this->process, $this->args);
} catch (\Exception $e) {
if (in_array(get_class($e), $this->allowedExceptions)) {
throw $e;
}
}
if ($i < $this->maxRetry) {
sleep($this->timeout);
$this->logger->warning(sprintf('[%s] Can\'t perform action, retrying [%s/%s]', $this->logInfos['callable'], $i, $this->maxRetry));
} else {
$this->logger->error(sprintf('[%s] %s retry has failed, aborting [%s/%s]', $this->logInfos['callable'], $i, $this->maxRetry));
$retryException = new YoloException('', 0, $e);
$retryException->setRetry($this->maxRetry);
$retryException->setTimeout($this->timeout);
throw $retryException;
}
}
} | @return mixed
@throws YoloException
@throws \Exception | entailment |
public function tryUntil($callback)
{
try {
return call_user_func_array($this->process, $this->args);
} catch (\Exception $e) {
if (in_array(get_class($e), $this->allowedExceptions)) {
throw $e;
}
}
$this->logger->warning(sprintf('[%s] Waiting until callback return a success', $this->logInfos['callable']));
$startTime = time();
$retry = 1;
for (;;) {
if ($callback instanceof YoloInterface) {
$available = $callback->isAvailable();
} else {
$available = call_user_func($callback);
}
if (true === $available) {
try {
return call_user_func_array($this->process, $this->args);
} catch (\Exception $e) {
$this->logger->warning(sprintf('[%s] Can\'t perform action [%s/%s]', $this->logInfos['callable'], $retry, $this->maxRetry));
if (in_array(get_class($e), $this->allowedExceptions)) {
throw $e;
}
++$retry;
}
if ($retry >= $this->maxRetry) {
$this->logger->error(sprintf('[%s] retry has failed, aborting [%s/%s]', $this->logInfos['callable'], $retry, $this->maxRetry));
$retryException = new YoloException('', 0, $e);
$retryException->setRetry($this->maxRetry);
$retryException->setTimeout($this->timeout);
throw $retryException;
}
} else {
$this->logger->warning(sprintf('[%s] Can\'t perform action, waiting next tick', $this->logInfos['callable']));
}
if ($this->timeout > 0 && (time() - $startTime) >= $this->timeout) {
$retryException = new YoloException('Timed out');
$retryException->setRetry($this->maxRetry);
$retryException->setTimeout($this->timeout);
throw $retryException;
}
sleep(1);
}
} | @param $callback
@return mixed|null
@throws \Exception | entailment |
public function setProperty($key, $value)
{
$properties = $this->properties;
$properties[$key] = $value;
$this->setProperties($properties);
} | {@inheritdoc} | entailment |
protected function configureArrayProperty($property, OptionsResolver $resolver)
{
$resolver
->setAllowedTypes($property, ['array', 'string'])
->setNormalizer($property, function (Options $options, $value) {
return is_array($value) ? $value : explode(',', str_replace(' ', '', $value));
});
} | Configures an array property for OptionsResolver.
@param string $property
@param OptionsResolver $resolver | entailment |
protected function configureEnvironmentProperty(OptionsResolver $resolver)
{
$resolver
->setDefined('environment')
->setAllowedTypes('environment', ['array', 'string'])
->setNormalizer('environment', function (Options $options, $value) {
if (is_array($value)) {
$normalized = [];
foreach ($value as $key => $val) {
is_string($key) and $normalized[] = sprintf('%s="%s"', strtoupper($key), $val);
}
$value = implode(',', $normalized);
}
return $value;
});
} | Configures an environment property for OptionsResolver.
@param OptionsResolver $resolver | entailment |
protected function configureByteProperty($property, OptionsResolver $resolver)
{
$resolver
->setAllowedTypes($property, 'byte')
->setNormalizer($property, function (Options $options, $value) {
return is_numeric($value) ? intval($value) : $value;
});
} | Configures a byte property for OptionsResolver.
@param string $property
@param OptionsResolver $resolver | entailment |
public function handle()
{
Map::dispatch();
Structures::withChain([new Stations])->dispatch();
Affiliation::withChain([new Names])->dispatch();
Alliances::withChain([new Members])->dispatch();
Prices::dispatch();
PublicCorporationHistory::dispatch();
PublicInfoJob::dispatch();
} | Execute the console command. | entailment |
protected function buildUrl($url, $query = [])
{
$url = explode('?', $url, 2);
if (count($url) == 2) {
parse_str($url[1], $query0);
$query = array_merge($query0, $query);
}
$query['apikey'] = $this->key;
$url = $url[0];
if (strpos($url, $this->baseUrl) === false) {
$url = $this->baseUrl . $url;
}
return $this->uriFactory->createUri($url)
->withQuery(http_build_query($query));
} | Extend an URL with query string parameters and return an UriInterface object.
@param string $url
@param array $query
@return UriInterface | entailment |
public function request(RequestInterface $request, $attempt = 1)
{
if (!$this->key) {
throw new AlmaClientException('No API key defined for ' . $this->zone);
}
try {
return $this->http->sendRequest($request);
} catch (HttpException $e) {
// Thrown for 400 and 500 level errors.
$error = $this->parseClientError($e);
if ($error->getErrorCode() === 'PER_SECOND_THRESHOLD') {
// We've run into the "Max 25 API calls per institution per second" limit.
// Wait a sec and retry, unless we've tried too many times already.
if ($attempt > $this->maxAttempts) {
throw new MaxNumberOfAttemptsExhausted(
'Rate limiting error - max number of retry attempts exhausted.',
0,
$e
);
}
time_nanosleep(0, $this->sleepTimeOnRetry * 1000000000);
return $this->request($request, $attempt + 1);
}
// Throw exception for other errors
throw $error;
} catch (NetworkException $e) {
// Thrown in case of a networking error
// Wait a sec and retry, unless we've tried too many times already.
if ($attempt > $this->maxAttempts) {
throw new MaxNumberOfAttemptsExhausted(
'Network error - max number of retry attempts exhausted.',
0,
$e
);
}
time_nanosleep(0, $this->sleepTimeOnRetry * 1000000000);
return $this->request($request, $attempt + 1);
}
} | Make a synchronous HTTP request and return a PSR7 response if successful.
In the case of intermittent errors (connection problem, 429 or 5XX error), the request is
attempted a maximum of {$this->maxAttempts} times with a sleep of {$this->sleepTimeOnRetry}
between each attempt to avoid hammering the server.
@param RequestInterface $request
@param int $attempt
@return ResponseInterface | entailment |
public function get($url, $query = [], $contentType = 'application/json')
{
$url = $this->buildUrl($url, $query);
$request = $this->requestFactory->createRequest('GET', $url)
->withHeader('Accept', $contentType);
$response = $this->request($request);
return strval($response->getBody());
} | Make a GET request.
@param string $url
@param array $query
@param string $contentType
@return string The response body | entailment |
public function getJSON($url, $query = [])
{
$responseBody = $this->get($url, $query, 'application/json');
return json_decode($responseBody);
} | Make a GET request, accepting JSON.
@param string $url
@param array $query
@return \stdClass JSON response as an object. | entailment |
public function getXML($url, $query = [])
{
$responseBody = $this->get($url, $query, 'application/xml');
return new QuiteSimpleXMLElement($responseBody);
} | Make a GET request, accepting XML.
@param string $url
@param array $query
@return QuiteSimpleXMLElement | entailment |
public function putJSON($url, $data)
{
$responseBody = $this->put($url, json_encode($data), 'application/json');
return json_decode($responseBody);
} | Make a PUT request, sending JSON data.
@param string $url
@param $data
@return \stdClass | entailment |
public function putXML($url, $data)
{
$responseBody = $this->put($url, $data, 'application/xml');
return new QuiteSimpleXMLElement($responseBody);
} | Make a PUT request, sending XML data.
@param string $url
@param $data
@return QuiteSimpleXMLElement | entailment |
public function post($url, $data, $contentType = 'application/json')
{
$uri = $this->buildUrl($url);
$request = $this->requestFactory->createRequest('POST', $uri);
if (!is_null($contentType)) {
$request = $request->withHeader('Content-Type', $contentType);
$request = $request->withHeader('Accept', $contentType);
}
$request = $request->withBody(stream_for($data));
$response = $this->request($request);
return strval($response->getBody());
} | Make a POST request.
@param string $url
@param $data
@param string $contentType
@return string The response body | entailment |
public function postJSON($url, $data = null)
{
$responseBody = $this->post($url, json_encode($data), 'application/json');
return json_decode($responseBody);
} | Make a POST request, sending JSON data.
@param string $url
@param $data
@return \stdClass | entailment |
public function postXML($url, $data = null)
{
$responseBody = $this->post($url, $data, 'application/xml');
return new QuiteSimpleXMLElement($responseBody);
} | Make a POST request, sending XML data.
@param string $url
@param $data
@return QuiteSimpleXMLElement | entailment |
public function getRedirectLocation($url, $query = [])
{
$url = $this->buildUrl($url, $query);
$request = $this->requestFactory->createRequest('GET', $url);
try {
$response = $this->request($request);
} catch (ResourceNotFound $e) {
return;
}
$locations = $response->getHeader('Location');
return count($locations) ? $locations[0] : null;
} | Get the redirect target location of an URL, or null if not a redirect.
@param string $url
@param array $query
@return string|null | entailment |
protected function parseClientError(HttpException $exception)
{
$contentType = explode(';', $exception->getResponse()->getHeaderLine('Content-Type'))[0];
$responseBody = (string) $exception->getResponse()->getBody();
switch ($contentType) {
case 'application/json':
$res = json_decode($responseBody, true);
if (isset($res['web_service_result'])) {
$res = $res['web_service_result'];
}
$err = $res['errorList']['error'][0];
$message = $err['errorMessage'];
$code = $err['errorCode'];
break;
case 'application/xml':
$xml = new QuiteSimpleXMLElement($responseBody);
$xml->registerXPathNamespace('xb', 'http://com/exlibris/urm/general/xmlbeans');
$message = $xml->text('//xb:errorMessage');
$code = $xml->text('//xb:errorCode');
break;
default:
$message = $responseBody;
$code = '';
}
// The error code is often an integer, but sometimes a string,
// so we generalize it as a string.
$code = empty($code) ? null : (string) $code;
if (strtolower($message) == 'invalid api key') {
return new InvalidApiKey($message, null, $exception);
}
if (preg_match('/(no items?|not) found/i', $message)) {
return new ResourceNotFound($message, $code, $exception);
}
return new RequestFailed($message, $code, $exception);
} | Generate a client exception.
@param HttpException $exception
@return RequestFailed | entailment |
public function write(Configuration $configuration)
{
$ini = $this->getRenderer()->render($configuration->toArray());
if (false === $result = $this->filesystem->put($this->file, $ini)) {
throw new WriterException(sprintf('Cannot write configuration into file %s', $this->file));
}
return $result;
} | {@inheritdoc} | entailment |
public function ping($timeout = 1)
{
if ($socket = @fsockopen($this->protocol . '://' . $this->host, $this->port, $errCode, $errStr, $timeout)) {
fclose($socket);
return true;
}
return false;
} | @param int $timeout
@return array|bool | entailment |
protected function setHeaders(array $headers)
{
// Ensure this is an atomic operation, either all headers are set or none.
$before = $this->headers;
try {
foreach ($headers as $name => $value) {
$this->setHeader($name, $value);
}
} catch (\Throwable $e) {
$this->headers = $before;
throw $e;
}
} | Sets the headers from the given array.
@param string[]|string[][] $headers | entailment |
protected function setHeader(string $name, $value)
{
\assert($this->isNameValid($name), "Invalid header name");
if (\is_array($value)) {
if (!$value) {
$this->removeHeader($name);
return;
}
$value = \array_values(\array_map("strval", $value));
} else {
$value = [(string) $value];
}
\assert($this->isValueValid($value), "Invalid header value");
$name = \strtolower($name);
$this->headers[$name] = $value;
} | Sets the named header to the given value.
@param string $name
@param string|string[] $value
@throws \Error If the header name or value is invalid. | entailment |
protected function addHeader(string $name, $value)
{
\assert($this->isNameValid($name), "Invalid header name");
if (\is_array($value)) {
if (!$value) {
return;
}
$value = \array_values(\array_map("strval", $value));
} else {
$value = [(string) $value];
}
\assert($this->isValueValid($value), "Invalid header value");
$name = \strtolower($name);
if (isset($this->headers[$name])) {
$this->headers[$name] = \array_merge($this->headers[$name], $value);
} else {
$this->headers[$name] = $value;
}
} | Adds the value to the named header, or creates the header with the given value if it did not exist.
@param string $name
@param string|string[] $value
@throws \Error If the header name or value is invalid. | entailment |
private function isValueValid(array $values): bool
{
foreach ($values as $value) {
if (\preg_match("/[^\t\r\n\x20-\x7e\x80-\xfe]|\r\n/", $value)) {
return false;
}
}
return true;
} | Determines if the given value is a valid header value.
@param string[] $values
@return bool
@throws \Error If the given value cannot be converted to a string and is not an array of values that can be
converted to strings. | entailment |
public static function parseHeaders(string $rawHeaders): array
{
// Ensure that the last line also ends with a newline, this is important.
\assert(\substr($rawHeaders, -2) === "\r\n", "Argument 1 must end with CRLF");
/** @var array[] $matches */
$count = \preg_match_all(self::HEADER_REGEX, $rawHeaders, $matches, \PREG_SET_ORDER);
// If these aren't the same, then one line didn't match and there's an invalid header.
if ($count !== \substr_count($rawHeaders, "\n")) {
// Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
if (\preg_match(self::HEADER_FOLD_REGEX, $rawHeaders)) {
throw new InvalidHeaderException("Invalid header syntax: Obsolete line folding");
}
throw new InvalidHeaderException("Invalid header syntax");
}
$headers = [];
foreach ($matches as $match) {
// We avoid a call to \trim() here due to the regex.
// Unfortunately, we can't avoid the \strtolower() calls due to \array_change_key_case() behavior
// when equal headers are present with different casing, e.g. 'set-cookie' and 'Set-Cookie'.
// Accessing matches directly instead of using foreach (... as list(...)) is slightly faster.
$headers[\strtolower($match[1])][] = $match[2];
}
return $headers;
} | Parses headers according to RFC 7230 and 2616.
Allows empty header values, as HTTP/1.0 allows that.
@param string $rawHeaders
@return array Associative array mapping header names to arrays of values.
@throws InvalidHeaderException If invalid headers have been passed. | entailment |
public static function formatHeaders(array $headers): string
{
$buffer = "";
$lines = 0;
foreach ($headers as $name => $values) {
// PHP casts integer-like keys to integers
$name = (string) $name;
// Ignore any HTTP/2 pseudo headers
if ($name[0] === ":") {
continue;
}
/** @var array $values */
foreach ($values as $value) {
$buffer .= "{$name}: {$value}\r\n";
$lines++;
}
}
$count = \preg_match_all(self::HEADER_REGEX, $buffer);
if ($lines !== $count || $lines !== \substr_count($buffer, "\n")) {
throw new InvalidHeaderException("Invalid headers");
}
return $buffer;
} | Format headers in to their on-the-wire format.
Headers are always validated syntactically. This protects against response splitting and header injection
attacks.
@param array $headers Headers in a format as returned by {@see parseHeaders()}.
@return string Formatted headers.
@throws InvalidHeaderException If header names or values are invalid. | entailment |
protected function loadRoutes(): RouteCollection
{
$builder = $this->getRouteCollectionBuilder();
if (\is_callable($this->routeCallback)) {
call_user_func($this->routeCallback, $builder);
}
return $builder->build();
} | Returns routes for request handling.
@return RouteCollection | entailment |
public function handle(Request $request): Response
{
try {
$matcher = $this->getUrlMatcher($request);
$parameters = $matcher->match($request->getPathInfo());
if (empty($parameters['_controller'])) {
throw new InvalidRouteException('Route requires a _controller callable');
}
if (!\is_callable($parameters['_controller'])) {
throw new InvalidRouteException('_controller must be a callable');
}
$callback = $parameters['_controller'];
$result = call_user_func_array($callback, $this->getControllerParameters($request, $parameters));
if (!$result instanceof Response) {
throw new InvalidResponseException('Response must be an instance of \Symfony\Component\HttpFoundation\Response');
}
} catch (\Exception $e) {
$result = $this->handleException($request, $e);
}
return $result;
} | Handles HTTP request and returns response.
@param Request $request
@return Response | entailment |
protected function getControllerParameters(Request $request, array $parameters): array
{
$result = [$request];
foreach ($parameters as $key => $value) {
if (strpos($key, '_') !== 0) {
$result[$key] = $value;
}
}
return $result;
} | Returns arguments for controller callback.
@param Request $request
@param array $parameters
@return array | entailment |
public function match(string $pattern, $callback, array $requirements = [], array $methods = [])
{
$route = new Route(
$pattern, // path
array('_controller' => $callback), // default values
$requirements, // requirements
array(), // options
'', // host
array(), // schemes
$methods // methods
);
$this->addRoute($route);
return $this;
} | Maps a pattern to a callable.
You can optionally specify HTTP methods that should be matched.
@param string $pattern Matched route pattern
@param callable $callback Callback that returns the response when matched
@param array $requirements
@param array $methods
@return $this | entailment |
public function get(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_GET, Request::METHOD_HEAD]);
} | Maps a GET request to a callable.
@param string $pattern
@param callable $callback
@param array $requirements
@return $this | entailment |
public function post(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_POST]);
} | Maps a POST request to a callable.
@param string $pattern
@param callable $callback
@param array $requirements
@return $this | entailment |
public function put(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_PUT]);
} | Maps a PUT request to a callable.
@param string $pattern
@param callable $callback
@param array $requirements
@return $this | entailment |
public function delete(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_DELETE]);
} | Maps a DELETE request to a callable.
@param string $pattern
@param $callback
@param array $requirements
@return $this | entailment |
public function options(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_OPTIONS]);
} | Maps an OPTIONS request to a callable.
@param string $pattern
@param $callback
@param array $requirements
@return $this | entailment |
public function patch(string $pattern, $callback, array $requirements = [])
{
return $this->match($pattern, $callback, $requirements, [Request::METHOD_PATCH]);
} | Maps a PATCH request to a callable.
@param string $pattern
@param $callback
@param array $requirements
@return $this | entailment |
public function compare(\DateInterval $first, \DateInterval $second)
{
if ($this->safe) {
$this->safecheck($first);
$this->safecheck($second);
}
if ($first->y > $second->y) {
return 1;
}
if ($first->y < $second->y) {
return -1;
}
if ($first->m > $second->m) {
return 1;
}
if ($first->m < $second->m) {
return -1;
}
if ($first->d > $second->d) {
return 1;
}
if ($first->d < $second->d) {
return -1;
}
if ($first->h > $second->h) {
return 1;
}
if ($first->h < $second->h) {
return -1;
}
if ($first->i > $second->i) {
return 1;
}
if ($first->i < $second->i) {
return -1;
}
if ($first->s > $second->s) {
return 1;
}
if ($first->s < $second->s) {
return -1;
}
return 0;
} | COmpare the two date intervals.
If the first contains a larger timespan we return 1, if the second contains more
we return -1 and when they are equals we return 0.
@param \DateInterval $first
@param \DateInterval $second
@return int | entailment |
protected function buildClass($name)
{
$stub = parent::buildClass($name);
$this->replaceEndpoint($stub, $this->argument('endpoint'));
if (! is_null($this->option('esi-version')))
$this->replaceVersion($stub, $this->option('esi-version'));
if (! is_null($this->option('scope')))
$this->replaceScope($stub, $this->option('scope'));
return $stub;
} | Build the class with the given name.
@param string $name
@return string | entailment |
protected function replaceEndpoint(string &$stub, string $endpoint)
{
if (strlen($endpoint) > 0)
$stub = str_replace('/dummy/endpoint/', $endpoint, $stub);
return $this;
} | Replace the endpoint for the given stub.
@param string $stub
@param string $endpoint
@return $this | entailment |
protected function replaceVersion(string &$stub, string $version)
{
if (strlen($version) > 0)
$stub = str_replace('v1', $version, $stub);
return $this;
} | Replace the endpoint version for the given stub.
@param string $stub
@param string $version
@return $this | entailment |
protected function replaceScope(string &$stub, string $scope)
{
if (strlen($scope) > 0)
$stub = str_replace("'public'", "'$scope'", $stub);
return $this;
} | Replace the scope for the given stub.
@param string $stub
@param string $scope
@return $this | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
$fs = new FileSystem();
$this->io->title('RCHJWTUserBundle - Generate SSL Keys');
$rootDir = $this->getContainer()->getParameter('kernel.root_dir');
$passphrase = $this->getContainer()->getParameter('rch_jwt_user.passphrase');
$path = $rootDir.'/jwt';
/* Symfony3 directory structure */
if (is_writable($rootDir.'/../var')) {
$path = $rootDir.'/../var/jwt';
}
if (!$fs->exists($path)) {
$fs->mkdir($path);
}
$this->generatePrivateKey($path, $passphrase, $this->io);
$this->generatePublicKey($path, $passphrase, $this->io);
$outputMessage = 'RSA keys successfully generated';
if ($passphrase) {
$outputMessage .= $this->io->getFormatter()->format(
sprintf(' with passphrase <comment>%s</comment></info>', $passphrase)
);
}
$this->io->success($outputMessage);
} | {@inheritdoc} | entailment |
protected function generatePrivateKey($path, $passphrase)
{
if ($passphrase) {
$processArgs = sprintf('genrsa -out %s/private.pem -aes256 -passout pass:%s 4096', $path, $passphrase);
} else {
$processArgs = sprintf('genrsa -out %s/private.pem 4096', $path);
}
$this->generateKey($processArgs);
} | Generate a RSA private key.
@param string $path
@param string $passphrase
@param OutputInterface $output
@throws ProcessFailedException | entailment |
protected function generatePublicKey($path, $passphrase)
{
$processArgs = sprintf('rsa -pubout -in %s/private.pem -out %s/public.pem -passin pass:%s', $path, $path, $passphrase);
$this->generateKey($processArgs);
} | Generate a RSA public key.
@param string $path
@param string $passphrase
@param OutputInterface $output | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.