repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1 value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
krixon/datetime | src/DateTime.php | DateTime.fromTimestampWithMicroseconds | public static function fromTimestampWithMicroseconds(int $timestamp) : self
{
$seconds = (int)($timestamp / 10 ** 6);
$microseconds = $timestamp - ($seconds * 10 ** 6);
// Ensure microseconds are right-padded with zeros because values like 012345 will be 12345 when expressed
// as an integer, and the concatenation below will therefore shift digits left by one place.
$microseconds = str_pad($microseconds, 6, '0', STR_PAD_LEFT);
return static::fromFormat('U.u', $seconds . '.' . $microseconds);
} | php | public static function fromTimestampWithMicroseconds(int $timestamp) : self
{
$seconds = (int)($timestamp / 10 ** 6);
$microseconds = $timestamp - ($seconds * 10 ** 6);
// Ensure microseconds are right-padded with zeros because values like 012345 will be 12345 when expressed
// as an integer, and the concatenation below will therefore shift digits left by one place.
$microseconds = str_pad($microseconds, 6, '0', STR_PAD_LEFT);
return static::fromFormat('U.u', $seconds . '.' . $microseconds);
} | [
"public",
"static",
"function",
"fromTimestampWithMicroseconds",
"(",
"int",
"$",
"timestamp",
")",
":",
"self",
"{",
"$",
"seconds",
"=",
"(",
"int",
")",
"(",
"$",
"timestamp",
"/",
"10",
"**",
"6",
")",
";",
"$",
"microseconds",
"=",
"$",
"timestamp",... | Creates a new instance from a microsecond-precision unix timestamp.
@param int $timestamp
@return self | [
"Creates",
"a",
"new",
"instance",
"from",
"a",
"microsecond",
"-",
"precision",
"unix",
"timestamp",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L190-L200 | train |
krixon/datetime | src/DateTime.php | DateTime.withDateAt | public function withDateAt(int $year = null, int $month = null, int $day = null) : self
{
if (null === $year && null === $month && null === $day) {
return $this;
}
$year = $year === null ? $this->year() : $year;
$month = $month ?: $this->month();
$day = $day ?: $this->day();
$instance = clone $this;
$instance->date->setDate($year, $month, $day);
return $instance;
} | php | public function withDateAt(int $year = null, int $month = null, int $day = null) : self
{
if (null === $year && null === $month && null === $day) {
return $this;
}
$year = $year === null ? $this->year() : $year;
$month = $month ?: $this->month();
$day = $day ?: $this->day();
$instance = clone $this;
$instance->date->setDate($year, $month, $day);
return $instance;
} | [
"public",
"function",
"withDateAt",
"(",
"int",
"$",
"year",
"=",
"null",
",",
"int",
"$",
"month",
"=",
"null",
",",
"int",
"$",
"day",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"null",
"===",
"$",
"year",
"&&",
"null",
"===",
"$",
"month",... | Returns a new instance with the date set accordingly.
Any omitted values will default to the current value.
@param int $year
@param int $month
@param int $day
@return self | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"date",
"set",
"accordingly",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L244-L259 | train |
krixon/datetime | src/DateTime.php | DateTime.withDateAtStartOfYear | public function withDateAtStartOfYear() : self
{
$instance = $this->withTimeAtMidnight();
$instance->date->setDate($instance->format('Y'), 1, 1);
return $instance;
} | php | public function withDateAtStartOfYear() : self
{
$instance = $this->withTimeAtMidnight();
$instance->date->setDate($instance->format('Y'), 1, 1);
return $instance;
} | [
"public",
"function",
"withDateAtStartOfYear",
"(",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"$",
"this",
"->",
"withTimeAtMidnight",
"(",
")",
";",
"$",
"instance",
"->",
"date",
"->",
"setDate",
"(",
"$",
"instance",
"->",
"format",
"(",
"'Y'",
")"... | Returns a new instance with the date set to 1st of Jan in the current year and time set to midnight.
@return self | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"date",
"set",
"to",
"1st",
"of",
"Jan",
"in",
"the",
"current",
"year",
"and",
"time",
"set",
"to",
"midnight",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L267-L274 | train |
krixon/datetime | src/DateTime.php | DateTime.withDateAtEndOfMonth | public function withDateAtEndOfMonth() : self
{
$instance = $this->withDateAtStartOfMonth();
$instance->date->modify('+1 month');
$instance->date->modify('-1 day');
return $instance;
} | php | public function withDateAtEndOfMonth() : self
{
$instance = $this->withDateAtStartOfMonth();
$instance->date->modify('+1 month');
$instance->date->modify('-1 day');
return $instance;
} | [
"public",
"function",
"withDateAtEndOfMonth",
"(",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"$",
"this",
"->",
"withDateAtStartOfMonth",
"(",
")",
";",
"$",
"instance",
"->",
"date",
"->",
"modify",
"(",
"'+1 month'",
")",
";",
"$",
"instance",
"->",
... | Returns a new instance with the date set to last day of the current month and time set to midnight.
@return self | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"date",
"set",
"to",
"last",
"day",
"of",
"the",
"current",
"month",
"and",
"time",
"set",
"to",
"midnight",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L297-L305 | train |
krixon/datetime | src/DateTime.php | DateTime.withDateAtDayOfWeekInMonth | public function withDateAtDayOfWeekInMonth(int $dayOfWeek, int $occurrence) : self
{
self::assertValidDayOfWeek($dayOfWeek);
if ($occurrence < -5 || $occurrence === 0 || $occurrence > 5) {
throw new \InvalidArgumentException("Invalid occurrence: $occurrence.");
}
$calendar = $this->createCalendar();
// IntlCalendar uses Sunday as day 1 - convert that to Monday as day 1.
if (++$dayOfWeek === 8) {
$dayOfWeek = 1;
}
$calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK, $dayOfWeek);
$calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH, $occurrence);
return static::fromIntlCalendar($calendar);
} | php | public function withDateAtDayOfWeekInMonth(int $dayOfWeek, int $occurrence) : self
{
self::assertValidDayOfWeek($dayOfWeek);
if ($occurrence < -5 || $occurrence === 0 || $occurrence > 5) {
throw new \InvalidArgumentException("Invalid occurrence: $occurrence.");
}
$calendar = $this->createCalendar();
// IntlCalendar uses Sunday as day 1 - convert that to Monday as day 1.
if (++$dayOfWeek === 8) {
$dayOfWeek = 1;
}
$calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK, $dayOfWeek);
$calendar->set(\IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH, $occurrence);
return static::fromIntlCalendar($calendar);
} | [
"public",
"function",
"withDateAtDayOfWeekInMonth",
"(",
"int",
"$",
"dayOfWeek",
",",
"int",
"$",
"occurrence",
")",
":",
"self",
"{",
"self",
"::",
"assertValidDayOfWeek",
"(",
"$",
"dayOfWeek",
")",
";",
"if",
"(",
"$",
"occurrence",
"<",
"-",
"5",
"||"... | Returns a new instance with the date set to the specified instance of the week day in the current month.
For example, given Monday and 1, this would set the date to the first Monday of the month. Given Friday and 3,
it would set the day of week to the third Friday of the month.
Maximum occurrence is 5. Negative occurrences are allowed up to a maximum of -5, in which case the relevant
occurrence from the end of the month is used. For example, Friday, -2 would be the penultimate Friday of
the month.
0 is not a valid occurrence.
Note that if the occurrence exceeds the number of occurrences in the month the date will overflow (or underflow)
to the next (or previous) month. For example, if the 5th Monday of the month is required in a month with only
4 Mondays, the date will actually be the first Monday of the following month.
@param int $dayOfWeek The day of the week where 1 is Monday.
@param int $occurrence
@return DateTime | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"date",
"set",
"to",
"the",
"specified",
"instance",
"of",
"the",
"week",
"day",
"in",
"the",
"current",
"month",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L329-L348 | train |
krixon/datetime | src/DateTime.php | DateTime.withTimeAt | public function withTimeAt(
int $hour = null,
int $minute = null,
int $second = null,
int $microsecond = null
) : self {
$instance = clone $this;
$hour = $hour === null ? $this->hour() : $hour;
$minute = $minute === null ? $this->minute() : $minute;
$second = $second === null ? $this->second() : $second;
$microsecond = $microsecond === null ? $this->microsecond() : $microsecond;
$instance->date->setTime($hour, $minute, $second);
// There is no API for setting the microsecond explicitly so a new instance has to be constructed.
$format = 'Y-m-d H:i:s';
$value = $instance->format($format) . '.' . substr($microsecond, 0, 6);
$instance->date = \DateTime::createFromFormat("$format.u", $value);
return $instance;
} | php | public function withTimeAt(
int $hour = null,
int $minute = null,
int $second = null,
int $microsecond = null
) : self {
$instance = clone $this;
$hour = $hour === null ? $this->hour() : $hour;
$minute = $minute === null ? $this->minute() : $minute;
$second = $second === null ? $this->second() : $second;
$microsecond = $microsecond === null ? $this->microsecond() : $microsecond;
$instance->date->setTime($hour, $minute, $second);
// There is no API for setting the microsecond explicitly so a new instance has to be constructed.
$format = 'Y-m-d H:i:s';
$value = $instance->format($format) . '.' . substr($microsecond, 0, 6);
$instance->date = \DateTime::createFromFormat("$format.u", $value);
return $instance;
} | [
"public",
"function",
"withTimeAt",
"(",
"int",
"$",
"hour",
"=",
"null",
",",
"int",
"$",
"minute",
"=",
"null",
",",
"int",
"$",
"second",
"=",
"null",
",",
"int",
"$",
"microsecond",
"=",
"null",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"clo... | Returns a new instance with the time set accordingly.
Any omitted values will default to the current value.
@param int|null $hour
@param int|null $minute
@param int|null $second
@param int|null $microsecond
@return self | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"time",
"set",
"accordingly",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L417-L439 | train |
krixon/datetime | src/DateTime.php | DateTime.withTimeZone | public function withTimeZone(\DateTimeZone $timezone) : self
{
if ($this->timezone()->getName() === $timezone->getName()) {
return $this;
}
$instance = clone $this;
$instance->date->setTimezone($timezone);
return $instance;
} | php | public function withTimeZone(\DateTimeZone $timezone) : self
{
if ($this->timezone()->getName() === $timezone->getName()) {
return $this;
}
$instance = clone $this;
$instance->date->setTimezone($timezone);
return $instance;
} | [
"public",
"function",
"withTimeZone",
"(",
"\\",
"DateTimeZone",
"$",
"timezone",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"timezone",
"(",
")",
"->",
"getName",
"(",
")",
"===",
"$",
"timezone",
"->",
"getName",
"(",
")",
")",
"{",
"retu... | Returns a new instance with the specified timezone.
@param DateTimeZone $timezone
@return DateTime | [
"Returns",
"a",
"new",
"instance",
"with",
"the",
"specified",
"timezone",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L460-L471 | train |
krixon/datetime | src/DateTime.php | DateTime.subtract | public function subtract($interval) : self
{
$instance = clone $this;
$instance->date->sub(self::resolveDateInterval($interval));
return $instance;
} | php | public function subtract($interval) : self
{
$instance = clone $this;
$instance->date->sub(self::resolveDateInterval($interval));
return $instance;
} | [
"public",
"function",
"subtract",
"(",
"$",
"interval",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"clone",
"$",
"this",
";",
"$",
"instance",
"->",
"date",
"->",
"sub",
"(",
"self",
"::",
"resolveDateInterval",
"(",
"$",
"interval",
")",
")",
";",
... | Creates a new instance with the interval subtracted from it.
@param DateInterval|string $interval A DateInterval instance or a DateInterval spec as a string.
@return self | [
"Creates",
"a",
"new",
"instance",
"with",
"the",
"interval",
"subtracted",
"from",
"it",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L547-L554 | train |
krixon/datetime | src/DateTime.php | DateTime.add | public function add($interval) : self
{
$instance = clone $this;
$instance->date->add(self::resolveDateInterval($interval));
return $instance;
} | php | public function add($interval) : self
{
$instance = clone $this;
$instance->date->add(self::resolveDateInterval($interval));
return $instance;
} | [
"public",
"function",
"add",
"(",
"$",
"interval",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"clone",
"$",
"this",
";",
"$",
"instance",
"->",
"date",
"->",
"add",
"(",
"self",
"::",
"resolveDateInterval",
"(",
"$",
"interval",
")",
")",
";",
"ret... | Creates a new instance with the interval added to it.
@param DateInterval|string $interval A DateInterval instance or a DateInterval spec as a string.
@return self | [
"Creates",
"a",
"new",
"instance",
"with",
"the",
"interval",
"added",
"to",
"it",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L564-L571 | train |
krixon/datetime | src/DateTime.php | DateTime.modify | public function modify(string $specification) : self
{
$instance = clone $this;
$instance->date->modify($specification);
return $instance;
} | php | public function modify(string $specification) : self
{
$instance = clone $this;
$instance->date->modify($specification);
return $instance;
} | [
"public",
"function",
"modify",
"(",
"string",
"$",
"specification",
")",
":",
"self",
"{",
"$",
"instance",
"=",
"clone",
"$",
"this",
";",
"$",
"instance",
"->",
"date",
"->",
"modify",
"(",
"$",
"specification",
")",
";",
"return",
"$",
"instance",
... | Creates a new instance modified according to the specification.
For valid formats @see http://php.net/manual/en/datetime.formats.relative.php
@param string $specification
@return self | [
"Creates",
"a",
"new",
"instance",
"modified",
"according",
"to",
"the",
"specification",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateTime.php#L583-L590 | train |
krixon/datetime | src/DateRange.php | DateRange.contains | public function contains(DateTime $dateTime) : bool
{
return $this->from->isEarlierThanOrEqualTo($dateTime) && $this->until->isLaterThan($dateTime);
} | php | public function contains(DateTime $dateTime) : bool
{
return $this->from->isEarlierThanOrEqualTo($dateTime) && $this->until->isLaterThan($dateTime);
} | [
"public",
"function",
"contains",
"(",
"DateTime",
"$",
"dateTime",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"from",
"->",
"isEarlierThanOrEqualTo",
"(",
"$",
"dateTime",
")",
"&&",
"$",
"this",
"->",
"until",
"->",
"isLaterThan",
"(",
"$",
"d... | Determines if the range contains a specified date and time.
@param DateTime $dateTime
@return bool | [
"Determines",
"if",
"the",
"range",
"contains",
"a",
"specified",
"date",
"and",
"time",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateRange.php#L86-L89 | train |
krixon/datetime | src/DateRange.php | DateRange.equals | public function equals(self $other) : bool
{
if ($other === $this) {
return true;
}
return $other->from->equals($this->from) && $other->until->equals($this->until);
} | php | public function equals(self $other) : bool
{
if ($other === $this) {
return true;
}
return $other->from->equals($this->from) && $other->until->equals($this->until);
} | [
"public",
"function",
"equals",
"(",
"self",
"$",
"other",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"other",
"===",
"$",
"this",
")",
"{",
"return",
"true",
";",
"}",
"return",
"$",
"other",
"->",
"from",
"->",
"equals",
"(",
"$",
"this",
"->",
"fr... | Determines if an instance is equal to this instance.
@param self $other
@return bool | [
"Determines",
"if",
"an",
"instance",
"is",
"equal",
"to",
"this",
"instance",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateRange.php#L110-L117 | train |
krixon/datetime | src/DateRange.php | DateRange.dateDiff | private function dateDiff() : DateInterval
{
if (null === $this->dateDiff) {
$this->dateDiff = $this->from->withTimeAtMidnight()->diff($this->until->withTimeAtMidnight());
}
return $this->dateDiff;
} | php | private function dateDiff() : DateInterval
{
if (null === $this->dateDiff) {
$this->dateDiff = $this->from->withTimeAtMidnight()->diff($this->until->withTimeAtMidnight());
}
return $this->dateDiff;
} | [
"private",
"function",
"dateDiff",
"(",
")",
":",
"DateInterval",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"dateDiff",
")",
"{",
"$",
"this",
"->",
"dateDiff",
"=",
"$",
"this",
"->",
"from",
"->",
"withTimeAtMidnight",
"(",
")",
"->",
"diff",... | A diff between the two dates with times set to midnight to guarantee resolution to whole days.
@return DateInterval | [
"A",
"diff",
"between",
"the",
"two",
"dates",
"with",
"times",
"set",
"to",
"midnight",
"to",
"guarantee",
"resolution",
"to",
"whole",
"days",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateRange.php#L174-L181 | train |
krixon/datetime | src/DateRange.php | DateRange.fullDiff | private function fullDiff() : DateInterval
{
if (null === $this->fullDiff) {
$this->fullDiff = $this->from->diff($this->until);
}
return $this->fullDiff;
} | php | private function fullDiff() : DateInterval
{
if (null === $this->fullDiff) {
$this->fullDiff = $this->from->diff($this->until);
}
return $this->fullDiff;
} | [
"private",
"function",
"fullDiff",
"(",
")",
":",
"DateInterval",
"{",
"if",
"(",
"null",
"===",
"$",
"this",
"->",
"fullDiff",
")",
"{",
"$",
"this",
"->",
"fullDiff",
"=",
"$",
"this",
"->",
"from",
"->",
"diff",
"(",
"$",
"this",
"->",
"until",
... | A full diff between the two dates.
@return DateInterval | [
"A",
"full",
"diff",
"between",
"the",
"two",
"dates",
"."
] | 9a39084119bbfae2cf6e22d794aa04dd79344ce0 | https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/DateRange.php#L189-L196 | train |
flipboxfactory/craft-integration | src/queries/ObjectAttributeTrait.php | ObjectAttributeTrait.applyObjectConditions | protected function applyObjectConditions()
{
if ($this->object !== null) {
$this->andWhere(Db::parseParam('objectId', $this->object));
}
} | php | protected function applyObjectConditions()
{
if ($this->object !== null) {
$this->andWhere(Db::parseParam('objectId', $this->object));
}
} | [
"protected",
"function",
"applyObjectConditions",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"object",
"!==",
"null",
")",
"{",
"$",
"this",
"->",
"andWhere",
"(",
"Db",
"::",
"parseParam",
"(",
"'objectId'",
",",
"$",
"this",
"->",
"object",
")",
")... | Apply query specific conditions | [
"Apply",
"query",
"specific",
"conditions"
] | ec19fc1b78a8f6e726fc75156924f548351e6b71 | https://github.com/flipboxfactory/craft-integration/blob/ec19fc1b78a8f6e726fc75156924f548351e6b71/src/queries/ObjectAttributeTrait.php#L77-L82 | train |
PitonCMS/Engine | app/Controllers/AdminAccessController.php | AdminAccessController.requestLoginToken | public function requestLoginToken()
{
// Get dependencies
$session = $this->container->sessionHandler;
$email = $this->container->emailHandler;
$security = $this->container->accessHandler;
$userMapper = ($this->container->dataMapper)('UserMapper');
$body = $this->request->getParsedBody();
// Fetch all users
$userList = $userMapper->find();
// Clean provided email
$providedEmail = strtolower(trim($body['email']));
$foundValidUser = false;
foreach ($userList as $user) {
if ($user->email === $providedEmail) {
$foundValidUser = $user;
break;
}
}
// Did we find a match?
if (!$foundValidUser) {
// No, log and silently redirect to home
$this->container->logger->alert('Failed login attempt: ' . $body['email']);
return $this->redirect('home');
}
// Belt and braces/suspenders double check
if ($foundValidUser->email === $providedEmail) {
// Get and set token, and user ID
$token = $security->generateLoginToken();
$session->setData([
$this->loginTokenKey => $token,
$this->loginTokenExpiresKey => time() + 120,
'user_id' => $foundValidUser->id,
'email' => $foundValidUser->email
]);
// Get request details to create login link and email to user
$scheme = $this->request->getUri()->getScheme();
$host = $this->request->getUri()->getHost();
$link = $scheme . '://' . $host;
$link .= $this->container->router->pathFor('adminProcessLoginToken', ['token' => $token]);
// Send message
$email->setTo($providedEmail, '')
->setSubject('PitonCMS Login')
->setMessage("Click to login\n\n {$link}")
->send();
}
// Direct to home page
return $this->redirect('home');
} | php | public function requestLoginToken()
{
// Get dependencies
$session = $this->container->sessionHandler;
$email = $this->container->emailHandler;
$security = $this->container->accessHandler;
$userMapper = ($this->container->dataMapper)('UserMapper');
$body = $this->request->getParsedBody();
// Fetch all users
$userList = $userMapper->find();
// Clean provided email
$providedEmail = strtolower(trim($body['email']));
$foundValidUser = false;
foreach ($userList as $user) {
if ($user->email === $providedEmail) {
$foundValidUser = $user;
break;
}
}
// Did we find a match?
if (!$foundValidUser) {
// No, log and silently redirect to home
$this->container->logger->alert('Failed login attempt: ' . $body['email']);
return $this->redirect('home');
}
// Belt and braces/suspenders double check
if ($foundValidUser->email === $providedEmail) {
// Get and set token, and user ID
$token = $security->generateLoginToken();
$session->setData([
$this->loginTokenKey => $token,
$this->loginTokenExpiresKey => time() + 120,
'user_id' => $foundValidUser->id,
'email' => $foundValidUser->email
]);
// Get request details to create login link and email to user
$scheme = $this->request->getUri()->getScheme();
$host = $this->request->getUri()->getHost();
$link = $scheme . '://' . $host;
$link .= $this->container->router->pathFor('adminProcessLoginToken', ['token' => $token]);
// Send message
$email->setTo($providedEmail, '')
->setSubject('PitonCMS Login')
->setMessage("Click to login\n\n {$link}")
->send();
}
// Direct to home page
return $this->redirect('home');
} | [
"public",
"function",
"requestLoginToken",
"(",
")",
"{",
"// Get dependencies",
"$",
"session",
"=",
"$",
"this",
"->",
"container",
"->",
"sessionHandler",
";",
"$",
"email",
"=",
"$",
"this",
"->",
"container",
"->",
"emailHandler",
";",
"$",
"security",
... | Request Login Token
Validates email and sends login link to user | [
"Request",
"Login",
"Token"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminAccessController.php#L53-L110 | train |
PitonCMS/Engine | app/Controllers/AdminAccessController.php | AdminAccessController.processLoginToken | public function processLoginToken($args)
{
// Get dependencies
$session = $this->container->sessionHandler;
$security = $this->container->accessHandler;
$savedToken = $session->getData($this->loginTokenKey);
$tokenExpires = $session->getData($this->loginTokenExpiresKey);
// Checks whether token matches, and if within expires time
if ($args['token'] === $savedToken && time() < $tokenExpires) {
// Successful, set session
$security->startAuthenticatedSession();
// Delete token
$session->unsetData($this->loginTokenKey);
$session->unsetData($this->loginTokenExpiresKey);
// Go to admin dashboard
return $this->redirect('adminHome');
}
// Not valid, direct home
$message = $args['token'] . ' saved: ' . $savedToken . ' time: ' . time() . ' expires: ' . $tokenExpires;
$this->container->logger->info('Invalid login token, supplied: ' . $message);
return $this->notFound();
} | php | public function processLoginToken($args)
{
// Get dependencies
$session = $this->container->sessionHandler;
$security = $this->container->accessHandler;
$savedToken = $session->getData($this->loginTokenKey);
$tokenExpires = $session->getData($this->loginTokenExpiresKey);
// Checks whether token matches, and if within expires time
if ($args['token'] === $savedToken && time() < $tokenExpires) {
// Successful, set session
$security->startAuthenticatedSession();
// Delete token
$session->unsetData($this->loginTokenKey);
$session->unsetData($this->loginTokenExpiresKey);
// Go to admin dashboard
return $this->redirect('adminHome');
}
// Not valid, direct home
$message = $args['token'] . ' saved: ' . $savedToken . ' time: ' . time() . ' expires: ' . $tokenExpires;
$this->container->logger->info('Invalid login token, supplied: ' . $message);
return $this->notFound();
} | [
"public",
"function",
"processLoginToken",
"(",
"$",
"args",
")",
"{",
"// Get dependencies",
"$",
"session",
"=",
"$",
"this",
"->",
"container",
"->",
"sessionHandler",
";",
"$",
"security",
"=",
"$",
"this",
"->",
"container",
"->",
"accessHandler",
";",
... | Process Login Token
Validate login token and authenticate request | [
"Process",
"Login",
"Token"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminAccessController.php#L117-L143 | train |
PitonCMS/Engine | app/Controllers/AdminSettingController.php | AdminSettingController.showSettings | public function showSettings()
{
// Get dependencies
$settingMapper = ($this->container->dataMapper)('SettingMapper');
$json = $this->container->json;
// Fetch settings from database
$allSettings = $settingMapper->findSiteSettings();
// Fetch custom settings
$jsonFilePath = ROOT_DIR . "structure/definitions/customSettings.json";
if (null === $customSettings = $json->getJson($jsonFilePath, 'setting')) {
$this->setAlert('danger', 'Custom Settings Error', $json->getErrorMessages());
} else {
// Merge saved settings with custom settings
$allSettings = $this->mergeSettings($allSettings, $customSettings->settings);
}
return $this->render('editSettings.html', $allSettings);
} | php | public function showSettings()
{
// Get dependencies
$settingMapper = ($this->container->dataMapper)('SettingMapper');
$json = $this->container->json;
// Fetch settings from database
$allSettings = $settingMapper->findSiteSettings();
// Fetch custom settings
$jsonFilePath = ROOT_DIR . "structure/definitions/customSettings.json";
if (null === $customSettings = $json->getJson($jsonFilePath, 'setting')) {
$this->setAlert('danger', 'Custom Settings Error', $json->getErrorMessages());
} else {
// Merge saved settings with custom settings
$allSettings = $this->mergeSettings($allSettings, $customSettings->settings);
}
return $this->render('editSettings.html', $allSettings);
} | [
"public",
"function",
"showSettings",
"(",
")",
"{",
"// Get dependencies",
"$",
"settingMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'SettingMapper'",
")",
";",
"$",
"json",
"=",
"$",
"this",
"->",
"container",
"->",
"... | Manage Site Settings
List all site configuration settings to bulk edit | [
"Manage",
"Site",
"Settings"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminSettingController.php#L23-L42 | train |
helsingborg-stad/broken-link-detector | source/php/ExternalDetector.php | ExternalDetector.lookForBrokenLinks | public function lookForBrokenLinks($postId = null, $url = null)
{
\BrokenLinkDetector\App::checkInstall();
$foundUrls = array();
if ($url) {
$url = "REGEXP ('.*(href=\"{$url}\").*')";
} else {
$url = "RLIKE ('href=*')";
}
global $wpdb;
$sql = "
SELECT ID, post_content
FROM $wpdb->posts
WHERE
post_content {$url}
AND post_type NOT IN ('attachment', 'revision', 'acf', 'acf-field', 'acf-field-group')
AND post_status IN ('publish', 'private', 'password')
";
if (is_numeric($postId)) {
$sql .= " AND ID = $postId";
}
$posts = $wpdb->get_results($sql);
if(is_array($posts) && !empty($posts)) {
foreach ($posts as $post) {
preg_match_all('/<a[^>]+href=([\'"])(http|https)(.+?)\1[^>]*>/i', $post->post_content, $m);
if (!isset($m[3]) || count($m[3]) > 0) {
foreach ($m[3] as $key => $url) {
$url = $m[2][$key] . $url;
// Replace whitespaces in url
if (preg_match('/\s/', $url)) {
$newUrl = preg_replace('/ /', '%20', $url);
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->posts
SET post_content = REPLACE(post_content, %s, %s)
WHERE post_content LIKE %s
AND ID = %d",
$url,
$newUrl,
'%' . $wpdb->esc_like($url) . '%',
$post->ID
)
);
$url = $newUrl;
}
if ($postId !== 'internal' && !$this->isBroken($url)) {
continue;
}
$foundUrls[] = array(
'post_id' => $post->ID,
'url' => $url
);
}
}
}
}
$this->saveBrokenLinks($foundUrls, $postId);
} | php | public function lookForBrokenLinks($postId = null, $url = null)
{
\BrokenLinkDetector\App::checkInstall();
$foundUrls = array();
if ($url) {
$url = "REGEXP ('.*(href=\"{$url}\").*')";
} else {
$url = "RLIKE ('href=*')";
}
global $wpdb;
$sql = "
SELECT ID, post_content
FROM $wpdb->posts
WHERE
post_content {$url}
AND post_type NOT IN ('attachment', 'revision', 'acf', 'acf-field', 'acf-field-group')
AND post_status IN ('publish', 'private', 'password')
";
if (is_numeric($postId)) {
$sql .= " AND ID = $postId";
}
$posts = $wpdb->get_results($sql);
if(is_array($posts) && !empty($posts)) {
foreach ($posts as $post) {
preg_match_all('/<a[^>]+href=([\'"])(http|https)(.+?)\1[^>]*>/i', $post->post_content, $m);
if (!isset($m[3]) || count($m[3]) > 0) {
foreach ($m[3] as $key => $url) {
$url = $m[2][$key] . $url;
// Replace whitespaces in url
if (preg_match('/\s/', $url)) {
$newUrl = preg_replace('/ /', '%20', $url);
$wpdb->query(
$wpdb->prepare(
"UPDATE $wpdb->posts
SET post_content = REPLACE(post_content, %s, %s)
WHERE post_content LIKE %s
AND ID = %d",
$url,
$newUrl,
'%' . $wpdb->esc_like($url) . '%',
$post->ID
)
);
$url = $newUrl;
}
if ($postId !== 'internal' && !$this->isBroken($url)) {
continue;
}
$foundUrls[] = array(
'post_id' => $post->ID,
'url' => $url
);
}
}
}
}
$this->saveBrokenLinks($foundUrls, $postId);
} | [
"public",
"function",
"lookForBrokenLinks",
"(",
"$",
"postId",
"=",
"null",
",",
"$",
"url",
"=",
"null",
")",
"{",
"\\",
"BrokenLinkDetector",
"\\",
"App",
"::",
"checkInstall",
"(",
")",
";",
"$",
"foundUrls",
"=",
"array",
"(",
")",
";",
"if",
"(",... | Look for broken links in post_content
@param integer $post_id Optional post_id to update broken links for
@return void | [
"Look",
"for",
"broken",
"links",
"in",
"post_content"
] | f7ddc4a7258235b67dbfabe994de7335e7bcb73b | https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/ExternalDetector.php#L42-L109 | train |
helsingborg-stad/broken-link-detector | source/php/ExternalDetector.php | ExternalDetector.isBroken | public function isBroken($url)
{
if (!$domain = parse_url($url, PHP_URL_HOST)) {
return true;
}
if(in_array($domain, (array) apply_filters('brokenLinks/External/ExceptedDomains', array()))) {
return false;
}
// Convert domain name to IDNA ASCII form
if(count(explode('.', $domain)) == count(array_filter(explode('.', $domain),
function($var) {
if(strlen($var) < 1) {
return false;
}
return true;
})))
{
try {
$punycode = new Punycode();
$domainAscii = $punycode->encode($domain);
$url = str_ireplace($domain, $domainAscii, $url);
} catch (Exception $e) {
return false;
}
}
// Test if URL is internal and page exist
if ($this->isInternal($url)) {
return false;
}
// Validate domain name
if (!$this->isValidDomainName(isset($domainAscii) ? $domainAscii : $domain)) {
return true;
}
// Test if domain is available
return !$this->isDomainAvailable($url);
} | php | public function isBroken($url)
{
if (!$domain = parse_url($url, PHP_URL_HOST)) {
return true;
}
if(in_array($domain, (array) apply_filters('brokenLinks/External/ExceptedDomains', array()))) {
return false;
}
// Convert domain name to IDNA ASCII form
if(count(explode('.', $domain)) == count(array_filter(explode('.', $domain),
function($var) {
if(strlen($var) < 1) {
return false;
}
return true;
})))
{
try {
$punycode = new Punycode();
$domainAscii = $punycode->encode($domain);
$url = str_ireplace($domain, $domainAscii, $url);
} catch (Exception $e) {
return false;
}
}
// Test if URL is internal and page exist
if ($this->isInternal($url)) {
return false;
}
// Validate domain name
if (!$this->isValidDomainName(isset($domainAscii) ? $domainAscii : $domain)) {
return true;
}
// Test if domain is available
return !$this->isDomainAvailable($url);
} | [
"public",
"function",
"isBroken",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"!",
"$",
"domain",
"=",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_HOST",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"in_array",
"(",
"$",
"domain",
",",
"(",
"a... | Test if domain is valid with different methods
@param string $url Url to check
@return boolean | [
"Test",
"if",
"domain",
"is",
"valid",
"with",
"different",
"methods"
] | f7ddc4a7258235b67dbfabe994de7335e7bcb73b | https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/ExternalDetector.php#L152-L192 | train |
helsingborg-stad/broken-link-detector | source/php/ExternalDetector.php | ExternalDetector.isDomainAvailable | public function isDomainAvailable($url, $timeOut = 7)
{
// Init curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Get the response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
$curlErrorNo = curl_errno($ch);
curl_close($ch);
//Curl response error
if($curlErrorNo) {
if(in_array($curlErrorNo, array(CURLE_TOO_MANY_REDIRECTS))) {
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Could not probe url " . $url . " due to a malfunction of curl [" . $curlErrorNo. " - " . $curlError . "]");
}
return true; //Do not log
} else {
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Could not probe url " . $url . ", link is considerd broken [" . $curlErrorNo. " - " . $curlError . "]");
}
return false; // Do log
}
}
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Probe data " . $url . " [Curl error no: " . $curlErrorNo. "] [Curl error message:" . $curlError . "] [Http code: ".$httpCode."]");
}
//Validate
if($response) {
//Genereic codes
if($httpCode >= 200 && $httpCode < 400) {
return true;
}
//Specific out of scope codes
//401: Unathorized
//406: Not acceptable
//413: Payload to large
//418: I'm a teapot
if(in_array($httpCode, array(401, 406, 413))) {
return true;
}
}
return false;
} | php | public function isDomainAvailable($url, $timeOut = 7)
{
// Init curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeOut);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Get the response
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
$curlErrorNo = curl_errno($ch);
curl_close($ch);
//Curl response error
if($curlErrorNo) {
if(in_array($curlErrorNo, array(CURLE_TOO_MANY_REDIRECTS))) {
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Could not probe url " . $url . " due to a malfunction of curl [" . $curlErrorNo. " - " . $curlError . "]");
}
return true; //Do not log
} else {
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Could not probe url " . $url . ", link is considerd broken [" . $curlErrorNo. " - " . $curlError . "]");
}
return false; // Do log
}
}
if(defined("BROKEN_LINKS_LOG") && BROKEN_LINKS_LOG) {
error_log("Broken links: Probe data " . $url . " [Curl error no: " . $curlErrorNo. "] [Curl error message:" . $curlError . "] [Http code: ".$httpCode."]");
}
//Validate
if($response) {
//Genereic codes
if($httpCode >= 200 && $httpCode < 400) {
return true;
}
//Specific out of scope codes
//401: Unathorized
//406: Not acceptable
//413: Payload to large
//418: I'm a teapot
if(in_array($httpCode, array(401, 406, 413))) {
return true;
}
}
return false;
} | [
"public",
"function",
"isDomainAvailable",
"(",
"$",
"url",
",",
"$",
"timeOut",
"=",
"7",
")",
"{",
"// Init curl",
"$",
"ch",
"=",
"curl_init",
"(",
"$",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_USERAGENT",
",",
"'Mozilla/5.0 (Window... | Test if domain is available with curl
@param string $url Url to check
@return bool | [
"Test",
"if",
"domain",
"is",
"available",
"with",
"curl"
] | f7ddc4a7258235b67dbfabe994de7335e7bcb73b | https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/ExternalDetector.php#L211-L269 | train |
helsingborg-stad/broken-link-detector | source/php/ExternalDetector.php | ExternalDetector.isInternal | public function isInternal($url)
{
// Check if post exist by url (only works with 'public' posts)
$postId = url_to_postid($url);
if ($postId > 0) {
return true;
}
// Check if the URL is internal or external
$siteUrlComponents = parse_url(get_site_url());
$urlComponents = parse_url($url);
if (!empty($siteUrlComponents['host']) && !empty($urlComponents['host']) && strcasecmp($urlComponents['host'], $siteUrlComponents['host']) === 0) {
// Test with get_page_by_path() to get other post statuses
$postTypes = get_post_types(array('public' => true));
if (!empty($urlComponents['path']) && !empty(get_page_by_path(basename(untrailingslashit($urlComponents['path'])), ARRAY_A, $postTypes))) {
return true;
}
}
return false;
} | php | public function isInternal($url)
{
// Check if post exist by url (only works with 'public' posts)
$postId = url_to_postid($url);
if ($postId > 0) {
return true;
}
// Check if the URL is internal or external
$siteUrlComponents = parse_url(get_site_url());
$urlComponents = parse_url($url);
if (!empty($siteUrlComponents['host']) && !empty($urlComponents['host']) && strcasecmp($urlComponents['host'], $siteUrlComponents['host']) === 0) {
// Test with get_page_by_path() to get other post statuses
$postTypes = get_post_types(array('public' => true));
if (!empty($urlComponents['path']) && !empty(get_page_by_path(basename(untrailingslashit($urlComponents['path'])), ARRAY_A, $postTypes))) {
return true;
}
}
return false;
} | [
"public",
"function",
"isInternal",
"(",
"$",
"url",
")",
"{",
"// Check if post exist by url (only works with 'public' posts)",
"$",
"postId",
"=",
"url_to_postid",
"(",
"$",
"url",
")",
";",
"if",
"(",
"$",
"postId",
">",
"0",
")",
"{",
"return",
"true",
";"... | Test if URL is internal and page exist
@param string $url Url to check
@return bool | [
"Test",
"if",
"URL",
"is",
"internal",
"and",
"page",
"exist"
] | f7ddc4a7258235b67dbfabe994de7335e7bcb73b | https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/ExternalDetector.php#L276-L296 | train |
TuumPHP/Respond | src/Service/ViewHelper.php | ViewHelper.call | public function call($presenter, array $data = [])
{
$response = $this->builder
->getView()
->start($this->request, $this->response)
->call($presenter, $data);
return $this->returnResponseBody($response);
} | php | public function call($presenter, array $data = [])
{
$response = $this->builder
->getView()
->start($this->request, $this->response)
->call($presenter, $data);
return $this->returnResponseBody($response);
} | [
"public",
"function",
"call",
"(",
"$",
"presenter",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"builder",
"->",
"getView",
"(",
")",
"->",
"start",
"(",
"$",
"this",
"->",
"request",
",",
"$",
"t... | call a presenter object and renders the content.
@param string|PresenterInterface $presenter
@param null|mixed|ViewData $data
@return string | [
"call",
"a",
"presenter",
"object",
"and",
"renders",
"the",
"content",
"."
] | 5861ec0bffc97c500d88bf307a53277f1c2fe12f | https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Service/ViewHelper.php#L250-L258 | train |
TuumPHP/Respond | src/Service/ViewHelper.php | ViewHelper.render | public function render($viewFile, $data = [])
{
return $this->builder
->getView()
->start($this->request, $this->response)
->renderContents($viewFile, $data);
} | php | public function render($viewFile, $data = [])
{
return $this->builder
->getView()
->start($this->request, $this->response)
->renderContents($viewFile, $data);
} | [
"public",
"function",
"render",
"(",
"$",
"viewFile",
",",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"builder",
"->",
"getView",
"(",
")",
"->",
"start",
"(",
"$",
"this",
"->",
"request",
",",
"$",
"this",
"->",
"response"... | renders another template.
@param string $viewFile
@param array $data
@return string | [
"renders",
"another",
"template",
"."
] | 5861ec0bffc97c500d88bf307a53277f1c2fe12f | https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Service/ViewHelper.php#L267-L273 | train |
locomotivemtl/charcoal-email | src/Charcoal/Email/EmailQueueItem.php | EmailQueueItem.setIdent | public function setIdent($ident)
{
if ($ident === null) {
$this->ident = null;
return $this;
}
if (!is_string($ident)) {
throw new InvalidArgumentException(
'Ident needs to be a string'
);
}
$this->ident = $ident;
return $this;
} | php | public function setIdent($ident)
{
if ($ident === null) {
$this->ident = null;
return $this;
}
if (!is_string($ident)) {
throw new InvalidArgumentException(
'Ident needs to be a string'
);
}
$this->ident = $ident;
return $this;
} | [
"public",
"function",
"setIdent",
"(",
"$",
"ident",
")",
"{",
"if",
"(",
"$",
"ident",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"ident",
"=",
"null",
";",
"return",
"$",
"this",
";",
"}",
"if",
"(",
"!",
"is_string",
"(",
"$",
"ident",
")",
... | Set the queue item's ID.
@param string|null $ident The unique queue item identifier.
@throws InvalidArgumentException If the identifier is not a string.
@return self | [
"Set",
"the",
"queue",
"item",
"s",
"ID",
"."
] | 99ccabcd0a91802e308177e0b6b626eaf0f940da | https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/EmailQueueItem.php#L105-L121 | train |
locomotivemtl/charcoal-email | src/Charcoal/Email/EmailQueueItem.php | EmailQueueItem.process | public function process(
callable $callback = null,
callable $successCallback = null,
callable $failureCallback = null
) {
if ($this->processed() === true) {
// Do not process twice, ever.
return null;
}
$email = $this->emailFactory()->create('email');
$email->setData($this->data());
try {
$res = $email->send();
if ($res === true) {
$this->setProcessed(true);
$this->setProcessedDate('now');
$this->update(['processed', 'processed_date']);
if ($successCallback !== null) {
$successCallback($this);
}
} else {
if ($failureCallback !== null) {
$failureCallback($this);
}
}
if ($callback !== null) {
$callback($this);
}
return $res;
} catch (Exception $e) {
// Todo log error
if ($failureCallback !== null) {
$failureCallback($this);
}
return false;
}
} | php | public function process(
callable $callback = null,
callable $successCallback = null,
callable $failureCallback = null
) {
if ($this->processed() === true) {
// Do not process twice, ever.
return null;
}
$email = $this->emailFactory()->create('email');
$email->setData($this->data());
try {
$res = $email->send();
if ($res === true) {
$this->setProcessed(true);
$this->setProcessedDate('now');
$this->update(['processed', 'processed_date']);
if ($successCallback !== null) {
$successCallback($this);
}
} else {
if ($failureCallback !== null) {
$failureCallback($this);
}
}
if ($callback !== null) {
$callback($this);
}
return $res;
} catch (Exception $e) {
// Todo log error
if ($failureCallback !== null) {
$failureCallback($this);
}
return false;
}
} | [
"public",
"function",
"process",
"(",
"callable",
"$",
"callback",
"=",
"null",
",",
"callable",
"$",
"successCallback",
"=",
"null",
",",
"callable",
"$",
"failureCallback",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"processed",
"(",
")",
"==... | Process the item.
@param callable $callback An optional callback routine executed after the item is processed.
@param callable $successCallback An optional callback routine executed when the item is resolved.
@param callable $failureCallback An optional callback routine executed when the item is rejected.
@return boolean|null Success / Failure | [
"Process",
"the",
"item",
"."
] | 99ccabcd0a91802e308177e0b6b626eaf0f940da | https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/EmailQueueItem.php#L307-L350 | train |
PitonCMS/Engine | app/Controllers/AdminController.php | AdminController.home | public function home()
{
$json = $this->container->json;
// Get Piton Engine version from composer.lock
if (null === $definition = $json->getJson(ROOT_DIR . '/composer.lock')) {
$this->setAlert('danger', 'Error Reading composer.lock', $json->getErrorMessages());
}
$engineKey = array_search('pitoncms/engine', array_column($definition->packages, 'name'));
$engineVersion = $definition->packages[$engineKey]->version;
return $this->render('home.html', ['pitonEngineVersion' => $engineVersion]);
} | php | public function home()
{
$json = $this->container->json;
// Get Piton Engine version from composer.lock
if (null === $definition = $json->getJson(ROOT_DIR . '/composer.lock')) {
$this->setAlert('danger', 'Error Reading composer.lock', $json->getErrorMessages());
}
$engineKey = array_search('pitoncms/engine', array_column($definition->packages, 'name'));
$engineVersion = $definition->packages[$engineKey]->version;
return $this->render('home.html', ['pitonEngineVersion' => $engineVersion]);
} | [
"public",
"function",
"home",
"(",
")",
"{",
"$",
"json",
"=",
"$",
"this",
"->",
"container",
"->",
"json",
";",
"// Get Piton Engine version from composer.lock",
"if",
"(",
"null",
"===",
"$",
"definition",
"=",
"$",
"json",
"->",
"getJson",
"(",
"ROOT_DIR... | Admin Home Page
@param void | [
"Admin",
"Home",
"Page"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminController.php#L21-L34 | train |
PitonCMS/Engine | app/Controllers/AdminController.php | AdminController.release | public function release($args)
{
$json = $this->container->json;
$markdown = $this->container->markdownParser;
$responseBody = '';
// If curl is not installed display alert
if (!function_exists('curl_init')) {
$this->setAlert('warning', 'Required PHP cURL not installed');
} else {
// https://developer.github.com/v3/repos/releases
$githubApi = 'https://api.github.com/repos/PitonCMS/Engine/releases';
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $githubApi,
CURLOPT_USERAGENT => $this->request->getHeaderLine('HTTP_USER_AGENT')
]);
$responseBody = curl_exec($curl);
$responseStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// Verify that we have a response
if ($responseStatus == '200') {
$releases = json_decode($responseBody);
$releases = array_slice($releases, 0, 5, true);
// Format Markdown
foreach ($releases as $key => $release) {
$releases[$key]->body = $markdown->text($release->body);
}
// Check if there is a more current release
if (array_search($args['release'], array_column($releases, 'tag_name')) > 0) {
$message = "The current version is {$releases[0]->tag_name}, you have version {$args['release']}.";
$message .= "\nTo upgrade, from your project root run <code>composer update pitoncms/engine</code>";
$this->setAlert('info', 'There is a newer version of the PitonCMS Engine', $message);
}
} else {
$releases = [];
$this->setAlert('warning', "$responseStatus Response From GitHub", $responseBody);
}
}
return $this->render('releaseNotes.html', ['releases' => $releases]);
} | php | public function release($args)
{
$json = $this->container->json;
$markdown = $this->container->markdownParser;
$responseBody = '';
// If curl is not installed display alert
if (!function_exists('curl_init')) {
$this->setAlert('warning', 'Required PHP cURL not installed');
} else {
// https://developer.github.com/v3/repos/releases
$githubApi = 'https://api.github.com/repos/PitonCMS/Engine/releases';
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $githubApi,
CURLOPT_USERAGENT => $this->request->getHeaderLine('HTTP_USER_AGENT')
]);
$responseBody = curl_exec($curl);
$responseStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
// Verify that we have a response
if ($responseStatus == '200') {
$releases = json_decode($responseBody);
$releases = array_slice($releases, 0, 5, true);
// Format Markdown
foreach ($releases as $key => $release) {
$releases[$key]->body = $markdown->text($release->body);
}
// Check if there is a more current release
if (array_search($args['release'], array_column($releases, 'tag_name')) > 0) {
$message = "The current version is {$releases[0]->tag_name}, you have version {$args['release']}.";
$message .= "\nTo upgrade, from your project root run <code>composer update pitoncms/engine</code>";
$this->setAlert('info', 'There is a newer version of the PitonCMS Engine', $message);
}
} else {
$releases = [];
$this->setAlert('warning', "$responseStatus Response From GitHub", $responseBody);
}
}
return $this->render('releaseNotes.html', ['releases' => $releases]);
} | [
"public",
"function",
"release",
"(",
"$",
"args",
")",
"{",
"$",
"json",
"=",
"$",
"this",
"->",
"container",
"->",
"json",
";",
"$",
"markdown",
"=",
"$",
"this",
"->",
"container",
"->",
"markdownParser",
";",
"$",
"responseBody",
"=",
"''",
";",
... | Show Piton Engine Release Notes
@param array $args GET Segment array | [
"Show",
"Piton",
"Engine",
"Release",
"Notes"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminController.php#L41-L86 | train |
yawik/settings | src/Module.php | Module.onBootstrap | public function onBootstrap(MvcEvent $e)
{
// we attach with wildcard events name
$events = $e->getApplication()->getEventManager();
$events->attach(
MvcEvent::EVENT_RENDER,
new InjectSubNavigationListener(),
10
);
} | php | public function onBootstrap(MvcEvent $e)
{
// we attach with wildcard events name
$events = $e->getApplication()->getEventManager();
$events->attach(
MvcEvent::EVENT_RENDER,
new InjectSubNavigationListener(),
10
);
} | [
"public",
"function",
"onBootstrap",
"(",
"MvcEvent",
"$",
"e",
")",
"{",
"// we attach with wildcard events name",
"$",
"events",
"=",
"$",
"e",
"->",
"getApplication",
"(",
")",
"->",
"getEventManager",
"(",
")",
";",
"$",
"events",
"->",
"attach",
"(",
"M... | Sets up services on the bootstrap event.
@internal
Creates the translation service and a ModuleRouteListener
@param MvcEvent $e | [
"Sets",
"up",
"services",
"on",
"the",
"bootstrap",
"event",
"."
] | fc49d14a5eec21fcc074ce29b1428d91191efecf | https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Module.php#L30-L39 | train |
excelwebzone/Omlex | lib/Omlex/Discoverer.php | Discoverer.getEndpointForUrl | public function getEndpointForUrl($url)
{
if (!isset($this->cachedEndpoints[$url])) {
$this->cachedEndpoints[$url] = $this->fetchEndpointForUrl($url);
}
return $this->cachedEndpoints[$url];
} | php | public function getEndpointForUrl($url)
{
if (!isset($this->cachedEndpoints[$url])) {
$this->cachedEndpoints[$url] = $this->fetchEndpointForUrl($url);
}
return $this->cachedEndpoints[$url];
} | [
"public",
"function",
"getEndpointForUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"cachedEndpoints",
"[",
"$",
"url",
"]",
")",
")",
"{",
"$",
"this",
"->",
"cachedEndpoints",
"[",
"$",
"url",
"]",
"=",
"$",
"th... | Get the provider's endpoint URL for the supplied resource
@param string $url The URL to get the endpoint's URL for | [
"Get",
"the",
"provider",
"s",
"endpoint",
"URL",
"for",
"the",
"supplied",
"resource"
] | 88fa11bf02d1ab364fbc1cba208e82156d5ef784 | https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/Discoverer.php#L56-L63 | train |
excelwebzone/Omlex | lib/Omlex/Discoverer.php | Discoverer.fetchEndpointForUrl | protected function fetchEndpointForUrl($url)
{
$client = new Client($url);
$body = $client->send();
$regexp = str_replace(
'@formats@',
implode('|', $this->supportedFormats),
self::LINK_REGEXP
);
if (!preg_match_all($regexp, $body, $matches, PREG_SET_ORDER)) {
throw new \InvalidArgumentException('No valid oEmbed links found on page.');
}
foreach ($matches as $match) {
if ($match['Format'] === $this->preferredFormat) {
return $this->extractEndpointFromAttributes($match['Attributes']);
}
}
return $this->extractEndpointFromAttributes($match['Attributes']);
} | php | protected function fetchEndpointForUrl($url)
{
$client = new Client($url);
$body = $client->send();
$regexp = str_replace(
'@formats@',
implode('|', $this->supportedFormats),
self::LINK_REGEXP
);
if (!preg_match_all($regexp, $body, $matches, PREG_SET_ORDER)) {
throw new \InvalidArgumentException('No valid oEmbed links found on page.');
}
foreach ($matches as $match) {
if ($match['Format'] === $this->preferredFormat) {
return $this->extractEndpointFromAttributes($match['Attributes']);
}
}
return $this->extractEndpointFromAttributes($match['Attributes']);
} | [
"protected",
"function",
"fetchEndpointForUrl",
"(",
"$",
"url",
")",
"{",
"$",
"client",
"=",
"new",
"Client",
"(",
"$",
"url",
")",
";",
"$",
"body",
"=",
"$",
"client",
"->",
"send",
"(",
")",
";",
"$",
"regexp",
"=",
"str_replace",
"(",
"'@format... | Fetch the provider's endpoint URL for the supplied resource
@param string $url The provider's endpoint URL for the supplied resource
@return string
@throws \InvalidArgumentException If no valid link was found | [
"Fetch",
"the",
"provider",
"s",
"endpoint",
"URL",
"for",
"the",
"supplied",
"resource"
] | 88fa11bf02d1ab364fbc1cba208e82156d5ef784 | https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/Discoverer.php#L74-L97 | train |
Nekland/Tools | src/Tools/DateTimeComparator.php | DateTimeComparator.lowest | public static function lowest(... $datetimes)
{
$lowest = null;
foreach ($datetimes as $datetime) {
if (!$datetime instanceof \DateTimeInterface) {
continue;
}
if ($datetime < $lowest || null === $lowest) {
$lowest = $datetime;
}
}
return $lowest;
} | php | public static function lowest(... $datetimes)
{
$lowest = null;
foreach ($datetimes as $datetime) {
if (!$datetime instanceof \DateTimeInterface) {
continue;
}
if ($datetime < $lowest || null === $lowest) {
$lowest = $datetime;
}
}
return $lowest;
} | [
"public",
"static",
"function",
"lowest",
"(",
"...",
"$",
"datetimes",
")",
"{",
"$",
"lowest",
"=",
"null",
";",
"foreach",
"(",
"$",
"datetimes",
"as",
"$",
"datetime",
")",
"{",
"if",
"(",
"!",
"$",
"datetime",
"instanceof",
"\\",
"DateTimeInterface"... | Get the lowest "DateTimeInterface" from the parameters
@param mixed $datetimes,... A various number of instances implementing `DateTimeInterface`
@return \DateTimeInterface|null | [
"Get",
"the",
"lowest",
"DateTimeInterface",
"from",
"the",
"parameters"
] | b3f05e5cf2291271e21397060069221a2b65d201 | https://github.com/Nekland/Tools/blob/b3f05e5cf2291271e21397060069221a2b65d201/src/Tools/DateTimeComparator.php#L33-L47 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.authenticate | public function authenticate(
$appID,
$sharedSecret = null,
$ipAddress = null,
$manual = false
) {
// set app_id before trying to authenticate for logging and report purpose
$this->setResponse('app_id', $appID);
// attempt authentication
$client = $this->clientRepo->authenticate($appID, $sharedSecret,
$ipAddress, $manual);
// client is authenticated
if ($client) {
$this->setAuthenticatedClient($client);
return true;
}
// client is not authenticated
$this->setResponse('responsecode', 'MT009');
$this->setResponse('verbosemessage', $this->clientRepo->getMessage());
$this->clientRepo->setMessage(null);
return false;
} | php | public function authenticate(
$appID,
$sharedSecret = null,
$ipAddress = null,
$manual = false
) {
// set app_id before trying to authenticate for logging and report purpose
$this->setResponse('app_id', $appID);
// attempt authentication
$client = $this->clientRepo->authenticate($appID, $sharedSecret,
$ipAddress, $manual);
// client is authenticated
if ($client) {
$this->setAuthenticatedClient($client);
return true;
}
// client is not authenticated
$this->setResponse('responsecode', 'MT009');
$this->setResponse('verbosemessage', $this->clientRepo->getMessage());
$this->clientRepo->setMessage(null);
return false;
} | [
"public",
"function",
"authenticate",
"(",
"$",
"appID",
",",
"$",
"sharedSecret",
"=",
"null",
",",
"$",
"ipAddress",
"=",
"null",
",",
"$",
"manual",
"=",
"false",
")",
"{",
"// set app_id before trying to authenticate for logging and report purpose",
"$",
"this",... | Authenticate a client
@param $appID
@param null $sharedSecret
@param null $ipAddress
@param bool $manual
@return bool | [
"Authenticate",
"a",
"client"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L57-L82 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.isDoiAuthenticatedClients | public function isDoiAuthenticatedClients($doiValue, $client_id = null)
{
if ($client_id === null) {
return false;
}
$client = $this->getAuthenticatedClient();
if ($client->client_id != $client_id) {
return false;
}
// everyone has access to test prefix
if (strpos($doiValue, DOIServiceProvider::$globalTestPrefix) === 0) {
return true;
}
// check if the client owns the prefix
foreach ($client->prefixes as $clientPrefix) {
if (strpos($doiValue, $clientPrefix->prefix->prefix_value) === 0) {
return true;
}
}
return false;
} | php | public function isDoiAuthenticatedClients($doiValue, $client_id = null)
{
if ($client_id === null) {
return false;
}
$client = $this->getAuthenticatedClient();
if ($client->client_id != $client_id) {
return false;
}
// everyone has access to test prefix
if (strpos($doiValue, DOIServiceProvider::$globalTestPrefix) === 0) {
return true;
}
// check if the client owns the prefix
foreach ($client->prefixes as $clientPrefix) {
if (strpos($doiValue, $clientPrefix->prefix->prefix_value) === 0) {
return true;
}
}
return false;
} | [
"public",
"function",
"isDoiAuthenticatedClients",
"(",
"$",
"doiValue",
",",
"$",
"client_id",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"client_id",
"===",
"null",
")",
"{",
"return",
"false",
";",
"}",
"$",
"client",
"=",
"$",
"this",
"->",
"getAuthentic... | Returns if a client is authenticated
@param $doiValue
@param null $client_id
@return bool | [
"Returns",
"if",
"a",
"client",
"is",
"authenticated"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L121-L146 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.mint | public function mint($url, $xml, $manual = false)
{
// @todo event handler, message
if (!$this->isClientAuthenticated()) {
$this->setResponse("responsecode", "MT009");
return false;
}
// Validate URL and URL Domain
$this->setResponse('url', $url);
$validDomain = URLValidator::validDomains(
$url, $this->getAuthenticatedClient()->domains
);
if (!$validDomain) {
$this->setResponse("responsecode", "MT014");
return false;
}
// construct DOI
if($manual===true){
$doiValue = XMLValidator::getDOIValue($xml);
}else{
$doiValue = $this->getNewDOI();
// replaced doiValue
$xml = XMLValidator::replaceDOIValue($doiValue, $xml);
}
$this->setResponse('doi', $doiValue);
// validation on the DOIValue
// Validate xml
if($this->validateXML($xml) === false){
$this->setResponse('responsecode', 'MT006');
return false;
}
//update the database DOIRepository
$doi = $this->insertNewDOI($doiValue,$xml,$url);
// mint using dataciteClient
$result = $this->dataciteClient->mint($doiValue, $url, $xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT001');
$this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT005');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
}
return $result;
} | php | public function mint($url, $xml, $manual = false)
{
// @todo event handler, message
if (!$this->isClientAuthenticated()) {
$this->setResponse("responsecode", "MT009");
return false;
}
// Validate URL and URL Domain
$this->setResponse('url', $url);
$validDomain = URLValidator::validDomains(
$url, $this->getAuthenticatedClient()->domains
);
if (!$validDomain) {
$this->setResponse("responsecode", "MT014");
return false;
}
// construct DOI
if($manual===true){
$doiValue = XMLValidator::getDOIValue($xml);
}else{
$doiValue = $this->getNewDOI();
// replaced doiValue
$xml = XMLValidator::replaceDOIValue($doiValue, $xml);
}
$this->setResponse('doi', $doiValue);
// validation on the DOIValue
// Validate xml
if($this->validateXML($xml) === false){
$this->setResponse('responsecode', 'MT006');
return false;
}
//update the database DOIRepository
$doi = $this->insertNewDOI($doiValue,$xml,$url);
// mint using dataciteClient
$result = $this->dataciteClient->mint($doiValue, $url, $xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT001');
$this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT005');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
}
return $result;
} | [
"public",
"function",
"mint",
"(",
"$",
"url",
",",
"$",
"xml",
",",
"$",
"manual",
"=",
"false",
")",
"{",
"// @todo event handler, message",
"if",
"(",
"!",
"$",
"this",
"->",
"isClientAuthenticated",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setResponse... | Mint a new DOI
@param $url
@param $xml
@return bool | [
"Mint",
"a",
"new",
"DOI"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L155-L210 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.validateXML | public function validateXML($xml)
{
$xmlValidator = new XMLValidator();
$result = $xmlValidator->validateSchemaVersion($xml);
if ($result === false) {
$this->setResponse("verbosemessage", $xmlValidator->getValidationMessage());
return false;
}
return true;
} | php | public function validateXML($xml)
{
$xmlValidator = new XMLValidator();
$result = $xmlValidator->validateSchemaVersion($xml);
if ($result === false) {
$this->setResponse("verbosemessage", $xmlValidator->getValidationMessage());
return false;
}
return true;
} | [
"public",
"function",
"validateXML",
"(",
"$",
"xml",
")",
"{",
"$",
"xmlValidator",
"=",
"new",
"XMLValidator",
"(",
")",
";",
"$",
"result",
"=",
"$",
"xmlValidator",
"->",
"validateSchemaVersion",
"(",
"$",
"xml",
")",
";",
"if",
"(",
"$",
"result",
... | Returns true if xml is datacite valid else false and sets error
@param $xml
@return bool | [
"Returns",
"true",
"if",
"xml",
"is",
"datacite",
"valid",
"else",
"false",
"and",
"sets",
"error"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L218-L227 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.getNewDOI | public function getNewDOI()
{
// get the first active prefix for this authenticated client
$prefix = "";
$testStr = "";
$client = $this->getAuthenticatedClient();
//if this client is not in test mode grab their production prefix
if(sizeof($client->prefixes) > 0 && $client->mode !== 'test'){
foreach ($client->prefixes as $clientPrefix) {
if($clientPrefix->active && $clientPrefix->is_test == 0) {
$prefix = $clientPrefix->prefix->prefix_value;
break;
}
}
}
if(sizeof($client->prefixes) > 0 && $client->mode == 'test'){
foreach ($client->prefixes as $clientPrefix) {
if($clientPrefix->active && $clientPrefix->is_test == 1) {
$prefix = $clientPrefix->prefix->prefix_value;
$testStr = "TEST_DOI_";
break;
}
}
}
$prefix = ends_with($prefix, '/') ? $prefix : $prefix .'/';
$doiValue = uniqid();
return $prefix . $testStr . $doiValue;
} | php | public function getNewDOI()
{
// get the first active prefix for this authenticated client
$prefix = "";
$testStr = "";
$client = $this->getAuthenticatedClient();
//if this client is not in test mode grab their production prefix
if(sizeof($client->prefixes) > 0 && $client->mode !== 'test'){
foreach ($client->prefixes as $clientPrefix) {
if($clientPrefix->active && $clientPrefix->is_test == 0) {
$prefix = $clientPrefix->prefix->prefix_value;
break;
}
}
}
if(sizeof($client->prefixes) > 0 && $client->mode == 'test'){
foreach ($client->prefixes as $clientPrefix) {
if($clientPrefix->active && $clientPrefix->is_test == 1) {
$prefix = $clientPrefix->prefix->prefix_value;
$testStr = "TEST_DOI_";
break;
}
}
}
$prefix = ends_with($prefix, '/') ? $prefix : $prefix .'/';
$doiValue = uniqid();
return $prefix . $testStr . $doiValue;
} | [
"public",
"function",
"getNewDOI",
"(",
")",
"{",
"// get the first active prefix for this authenticated client",
"$",
"prefix",
"=",
"\"\"",
";",
"$",
"testStr",
"=",
"\"\"",
";",
"$",
"client",
"=",
"$",
"this",
"->",
"getAuthenticatedClient",
"(",
")",
";",
"... | Returns a new DOI for the currently existing authenticated client
if client has no active prefix it probably means it's a test client
@return string | [
"Returns",
"a",
"new",
"DOI",
"for",
"the",
"currently",
"existing",
"authenticated",
"client",
"if",
"client",
"has",
"no",
"active",
"prefix",
"it",
"probably",
"means",
"it",
"s",
"a",
"test",
"client"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L235-L267 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.update | public function update($doiValue, $url=NULL, $xml=NULL)
{
if (!$this->isClientAuthenticated()) {
$this->setResponse("responsecode", "MT009");
return false;
}
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
// Validate URL and URL Domain
if (isset($url) && $url!="") {
$this->setResponse('url', $url);
$validDomain = URLValidator::validDomains(
$url, $this->getAuthenticatedClient()->domains
);
if (!$validDomain) {
$this->setResponse("responsecode", "MT014");
return false;
}
}
if(isset($xml) && $xml!="") {
// need to check that doi provided in xml matches doi
$xml = XMLValidator::replaceDOIValue($doiValue, $xml);
// Validate xml
if ($this->validateXML($xml) === false) {
$this->setResponse('responsecode', 'MT007');
return false;
}
}
if (isset($url) && $url!="") {
$result = $this->dataciteClient->updateURL($doiValue, $url);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('url'=>$url));
} else {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
}
if(isset($xml) && $xml!="") {
$result = $this->dataciteClient->update($xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('datacite_xml'=>$xml,'status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
}
return true;
} | php | public function update($doiValue, $url=NULL, $xml=NULL)
{
if (!$this->isClientAuthenticated()) {
$this->setResponse("responsecode", "MT009");
return false;
}
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
// Validate URL and URL Domain
if (isset($url) && $url!="") {
$this->setResponse('url', $url);
$validDomain = URLValidator::validDomains(
$url, $this->getAuthenticatedClient()->domains
);
if (!$validDomain) {
$this->setResponse("responsecode", "MT014");
return false;
}
}
if(isset($xml) && $xml!="") {
// need to check that doi provided in xml matches doi
$xml = XMLValidator::replaceDOIValue($doiValue, $xml);
// Validate xml
if ($this->validateXML($xml) === false) {
$this->setResponse('responsecode', 'MT007');
return false;
}
}
if (isset($url) && $url!="") {
$result = $this->dataciteClient->updateURL($doiValue, $url);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('url'=>$url));
} else {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
}
if(isset($xml) && $xml!="") {
$result = $this->dataciteClient->update($xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT002');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('datacite_xml'=>$xml,'status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage', array_first($this->dataciteClient->getErrors()));
return false;
}
}
return true;
} | [
"public",
"function",
"update",
"(",
"$",
"doiValue",
",",
"$",
"url",
"=",
"NULL",
",",
"$",
"xml",
"=",
"NULL",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isClientAuthenticated",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setResponse",
"(",
"\"re... | Update a DOI
@param $doiValue
@param null $url
@param null $xml
@return bool | [
"Update",
"a",
"DOI"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L302-L376 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.activate | public function activate($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
$doi_xml = $doi->datacite_xml;
//check if the doi is inactive
if ($doi->status != 'INACTIVE') {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage',
'DOI ' . $doiValue . " not set to INACTIVE so cannot activate it");
return false;
}
// activate using dataciteClient update method;
$result = $this->dataciteClient->update($doi_xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT004');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
}
return $result;
} | php | public function activate($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
$doi_xml = $doi->datacite_xml;
//check if the doi is inactive
if ($doi->status != 'INACTIVE') {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage',
'DOI ' . $doiValue . " not set to INACTIVE so cannot activate it");
return false;
}
// activate using dataciteClient update method;
$result = $this->dataciteClient->update($doi_xml);
if ($result === true) {
$this->setResponse('responsecode', 'MT004');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('status'=>'ACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
}
return $result;
} | [
"public",
"function",
"activate",
"(",
"$",
"doiValue",
")",
"{",
"// validate client",
"if",
"(",
"!",
"$",
"this",
"->",
"isClientAuthenticated",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setResponse",
"(",
"'responsecode'",
",",
"'MT009'",
")",
";",
"retu... | Activate a DOI
@param $doiValue
@return bool|mixed | [
"Activate",
"a",
"DOI"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L384-L430 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.getStatus | public function getStatus($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage', $doiValue . " is not owned by " . $this->getAuthenticatedClient()->client_name);
return false;
}
$this->setResponse('responsecode', 'MT019');
$this->setResponse('verbosemessage', $doi->status);
return true;
} | php | public function getStatus($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage', $doiValue . " is not owned by " . $this->getAuthenticatedClient()->client_name);
return false;
}
$this->setResponse('responsecode', 'MT019');
$this->setResponse('verbosemessage', $doi->status);
return true;
} | [
"public",
"function",
"getStatus",
"(",
"$",
"doiValue",
")",
"{",
"// validate client",
"if",
"(",
"!",
"$",
"this",
"->",
"isClientAuthenticated",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setResponse",
"(",
"'responsecode'",
",",
"'MT009'",
")",
";",
"ret... | get status of the DOI
@param $doiValue
@return bool | [
"get",
"status",
"of",
"the",
"DOI"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L438-L467 | train |
au-research/ANDS-DOI-Service | src/DOIServiceProvider.php | DOIServiceProvider.deactivate | public function deactivate($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
//check if the doi is inactive
if ($doi->status != 'ACTIVE') {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage',
'DOI ' . $doiValue . " not set to ACTIVE so cannot deactivate it");
return false;
}
$result = $this->dataciteClient->deActivate($doiValue);
if ($result === true) {
$this->setResponse('responsecode', 'MT003');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('status'=>'INACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
}
return $result;
} | php | public function deactivate($doiValue)
{
// validate client
if (!$this->isClientAuthenticated()) {
$this->setResponse('responsecode', 'MT009');
return false;
}
//get the doi info
$doi = $this->doiRepo->getByID($doiValue);
$this->setResponse('doi', $doiValue);
if ($doi === null) {
$this->setResponse('responsecode', 'MT011');
return true;
}
// check if this client owns this doi
if (!$this->isDoiAuthenticatedClients($doiValue, $doi->client_id)) {
$this->setResponse('responsecode', 'MT008');
$this->setResponse('verbosemessage',$doiValue." is not owned by ".$this->getAuthenticatedClient()->client_name);
return false;
}
//check if the doi is inactive
if ($doi->status != 'ACTIVE') {
$this->setResponse('responsecode', 'MT010');
$this->setResponse('verbosemessage',
'DOI ' . $doiValue . " not set to ACTIVE so cannot deactivate it");
return false;
}
$result = $this->dataciteClient->deActivate($doiValue);
if ($result === true) {
$this->setResponse('responsecode', 'MT003');
//update the database DOIRepository
$this->doiRepo->doiUpdate($doi, array('status'=>'INACTIVE'));
} else {
$this->setResponse('responsecode', 'MT010');
}
return $result;
} | [
"public",
"function",
"deactivate",
"(",
"$",
"doiValue",
")",
"{",
"// validate client",
"if",
"(",
"!",
"$",
"this",
"->",
"isClientAuthenticated",
"(",
")",
")",
"{",
"$",
"this",
"->",
"setResponse",
"(",
"'responsecode'",
",",
"'MT009'",
")",
";",
"re... | Deactivate a DOI
@param $doiValue
@return bool | [
"Deactivate",
"a",
"DOI"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/DOIServiceProvider.php#L476-L521 | train |
drdplusinfo/tables | DrdPlus/Tables/Measurements/Experiences/Level.php | Level.guardLevelBoundaries | private function guardLevelBoundaries($levelValue)
{
if ($levelValue < static::MIN_LEVEL) {
throw new Exceptions\MinLevelUnderflow(
'Level has to be at least ' . self::MIN_LEVEL . ', got ' . $levelValue
);
}
if ($levelValue > static::MAX_LEVEL) {
throw new Exceptions\MaxLevelOverflow(
'Level can not be greater than ' . self::MAX_LEVEL . ', got ' . $levelValue
);
}
} | php | private function guardLevelBoundaries($levelValue)
{
if ($levelValue < static::MIN_LEVEL) {
throw new Exceptions\MinLevelUnderflow(
'Level has to be at least ' . self::MIN_LEVEL . ', got ' . $levelValue
);
}
if ($levelValue > static::MAX_LEVEL) {
throw new Exceptions\MaxLevelOverflow(
'Level can not be greater than ' . self::MAX_LEVEL . ', got ' . $levelValue
);
}
} | [
"private",
"function",
"guardLevelBoundaries",
"(",
"$",
"levelValue",
")",
"{",
"if",
"(",
"$",
"levelValue",
"<",
"static",
"::",
"MIN_LEVEL",
")",
"{",
"throw",
"new",
"Exceptions",
"\\",
"MinLevelUnderflow",
"(",
"'Level has to be at least '",
".",
"self",
"... | Level is not limited by table values, so has to be in code
@param int $levelValue
@throws \DrdPlus\Tables\Measurements\Experiences\Exceptions\MinLevelUnderflow
@throws \DrdPlus\Tables\Measurements\Experiences\Exceptions\MaxLevelOverflow | [
"Level",
"is",
"not",
"limited",
"by",
"table",
"values",
"so",
"has",
"to",
"be",
"in",
"code"
] | 7a577ddbd1748369eec4e84effcc92ffcb54d1f3 | https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Measurements/Experiences/Level.php#L33-L45 | train |
php-toolkit/php-utils | src/PhpException.php | PhpException.toJson | public static function toJson($e, bool $getTrace = true, string $catcher = null): string
{
if (!$getTrace) {
return \json_encode(['msg' => "Error: {$e->getMessage()}"]);
}
$map = [
'code' => $e->getCode() ?: 500,
'msg' => sprintf(
'%s(%d): %s, File: %s(Line %d)',
\get_class($e),
$e->getCode(),
$e->getMessage(),
$e->getFile(),
$e->getLine()
),
'data' => $e->getTrace()
];
if ($catcher) {
$map['catcher'] = $catcher;
}
if ($getTrace) {
$map['trace'] = $e->getTrace();
}
return \json_encode($map);
} | php | public static function toJson($e, bool $getTrace = true, string $catcher = null): string
{
if (!$getTrace) {
return \json_encode(['msg' => "Error: {$e->getMessage()}"]);
}
$map = [
'code' => $e->getCode() ?: 500,
'msg' => sprintf(
'%s(%d): %s, File: %s(Line %d)',
\get_class($e),
$e->getCode(),
$e->getMessage(),
$e->getFile(),
$e->getLine()
),
'data' => $e->getTrace()
];
if ($catcher) {
$map['catcher'] = $catcher;
}
if ($getTrace) {
$map['trace'] = $e->getTrace();
}
return \json_encode($map);
} | [
"public",
"static",
"function",
"toJson",
"(",
"$",
"e",
",",
"bool",
"$",
"getTrace",
"=",
"true",
",",
"string",
"$",
"catcher",
"=",
"null",
")",
":",
"string",
"{",
"if",
"(",
"!",
"$",
"getTrace",
")",
"{",
"return",
"\\",
"json_encode",
"(",
... | Converts an exception into a json string.
@param \Exception|\Throwable $e the exception being converted
@param bool $getTrace
@param null|string $catcher
@return string the string representation of the exception. | [
"Converts",
"an",
"exception",
"into",
"a",
"json",
"string",
"."
] | 6e4b249b1c3cae36e19db466ddf5c7dd2c985904 | https://github.com/php-toolkit/php-utils/blob/6e4b249b1c3cae36e19db466ddf5c7dd2c985904/src/PhpException.php#L88-L116 | train |
froq/froq-http | src/request/Files.php | Files.normalizeFilesArray | public static function normalizeFilesArray(array $files): array
{
$return = [];
foreach ($files as $i => $file) {
foreach ($file as $key => $value) {
$return[$key][$i] = $value;
}
}
return $return;
} | php | public static function normalizeFilesArray(array $files): array
{
$return = [];
foreach ($files as $i => $file) {
foreach ($file as $key => $value) {
$return[$key][$i] = $value;
}
}
return $return;
} | [
"public",
"static",
"function",
"normalizeFilesArray",
"(",
"array",
"$",
"files",
")",
":",
"array",
"{",
"$",
"return",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"files",
"as",
"$",
"i",
"=>",
"$",
"file",
")",
"{",
"foreach",
"(",
"$",
"file",
"a... | Normalize files array.
@param array $files
@return array | [
"Normalize",
"files",
"array",
"."
] | 067207669b5054b867b7df2b5557acf1d43f572a | https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/request/Files.php#L75-L85 | train |
mirko-pagliai/me-cms | src/Controller/PostsTagsController.php | PostsTagsController.index | public function index()
{
$page = $this->request->getQuery('page', 1);
$this->paginate['order'] = ['tag' => 'ASC'];
//Limit X4
$this->paginate['limit'] = $this->paginate['maxLimit'] = $this->paginate['limit'] * 4;
//Sets the cache name
$cache = sprintf('tags_limit_%s_page_%s', $this->paginate['limit'], $page);
//Tries to get data from the cache
list($tags, $paging) = array_values(Cache::readMany(
[$cache, sprintf('%s_paging', $cache)],
$this->PostsTags->getCacheName()
));
//If the data are not available from the cache
if (empty($tags) || empty($paging)) {
$query = $this->PostsTags->Tags->find('active');
$tags = $this->paginate($query);
//Writes on cache
Cache::writeMany([
$cache => $tags,
sprintf('%s_paging', $cache) => $this->request->getParam('paging'),
], $this->PostsTags->getCacheName());
//Else, sets the paging parameter
} else {
$this->request = $this->request->withParam('paging', $paging);
}
$this->set(compact('tags'));
} | php | public function index()
{
$page = $this->request->getQuery('page', 1);
$this->paginate['order'] = ['tag' => 'ASC'];
//Limit X4
$this->paginate['limit'] = $this->paginate['maxLimit'] = $this->paginate['limit'] * 4;
//Sets the cache name
$cache = sprintf('tags_limit_%s_page_%s', $this->paginate['limit'], $page);
//Tries to get data from the cache
list($tags, $paging) = array_values(Cache::readMany(
[$cache, sprintf('%s_paging', $cache)],
$this->PostsTags->getCacheName()
));
//If the data are not available from the cache
if (empty($tags) || empty($paging)) {
$query = $this->PostsTags->Tags->find('active');
$tags = $this->paginate($query);
//Writes on cache
Cache::writeMany([
$cache => $tags,
sprintf('%s_paging', $cache) => $this->request->getParam('paging'),
], $this->PostsTags->getCacheName());
//Else, sets the paging parameter
} else {
$this->request = $this->request->withParam('paging', $paging);
}
$this->set(compact('tags'));
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"page",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'page'",
",",
"1",
")",
";",
"$",
"this",
"->",
"paginate",
"[",
"'order'",
"]",
"=",
"[",
"'tag'",
"=>",
"'ASC'",
"]",
";",
"//... | Lists posts tags
@return void | [
"Lists",
"posts",
"tags"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PostsTagsController.php#L30-L64 | train |
mirko-pagliai/me-cms | src/Controller/PostsTagsController.php | PostsTagsController.view | public function view($slug = null)
{
//Data can be passed as query string, from a widget
if ($this->request->getQuery('q')) {
return $this->redirect([$this->request->getQuery('q')]);
}
$slug = Text::slug($slug, ['replacement' => ' ']);
$tag = $this->PostsTags->Tags->findActiveByTag($slug)
->cache((sprintf('tag_%s', md5($slug))), $this->PostsTags->getCacheName())
->firstOrFail();
$page = $this->request->getQuery('page', 1);
//Sets the cache name
$cache = sprintf('tag_%s_limit_%s_page_%s', md5($slug), $this->paginate['limit'], $page);
//Tries to get data from the cache
list($posts, $paging) = array_values(Cache::readMany(
[$cache, sprintf('%s_paging', $cache)],
$this->PostsTags->getCacheName()
));
//If the data are not available from the cache
if (empty($posts) || empty($paging)) {
$query = $this->PostsTags->Posts->find('active')
->find('forIndex')
->matching($this->PostsTags->Tags->getAlias(), function (Query $q) use ($slug) {
return $q->where(['tag' => $slug]);
});
$posts = $this->paginate($query);
//Writes on cache
Cache::writeMany([
$cache => $posts,
sprintf('%s_paging', $cache) => $this->request->getParam('paging'),
], $this->PostsTags->getCacheName());
//Else, sets the paging parameter
} else {
$this->request = $this->request->withParam('paging', $paging);
}
$this->set(compact('posts', 'tag'));
} | php | public function view($slug = null)
{
//Data can be passed as query string, from a widget
if ($this->request->getQuery('q')) {
return $this->redirect([$this->request->getQuery('q')]);
}
$slug = Text::slug($slug, ['replacement' => ' ']);
$tag = $this->PostsTags->Tags->findActiveByTag($slug)
->cache((sprintf('tag_%s', md5($slug))), $this->PostsTags->getCacheName())
->firstOrFail();
$page = $this->request->getQuery('page', 1);
//Sets the cache name
$cache = sprintf('tag_%s_limit_%s_page_%s', md5($slug), $this->paginate['limit'], $page);
//Tries to get data from the cache
list($posts, $paging) = array_values(Cache::readMany(
[$cache, sprintf('%s_paging', $cache)],
$this->PostsTags->getCacheName()
));
//If the data are not available from the cache
if (empty($posts) || empty($paging)) {
$query = $this->PostsTags->Posts->find('active')
->find('forIndex')
->matching($this->PostsTags->Tags->getAlias(), function (Query $q) use ($slug) {
return $q->where(['tag' => $slug]);
});
$posts = $this->paginate($query);
//Writes on cache
Cache::writeMany([
$cache => $posts,
sprintf('%s_paging', $cache) => $this->request->getParam('paging'),
], $this->PostsTags->getCacheName());
//Else, sets the paging parameter
} else {
$this->request = $this->request->withParam('paging', $paging);
}
$this->set(compact('posts', 'tag'));
} | [
"public",
"function",
"view",
"(",
"$",
"slug",
"=",
"null",
")",
"{",
"//Data can be passed as query string, from a widget",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'q'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"redirect",
"(",
... | Lists posts for a tag
@param string $slug Tag slug
@return \Cake\Network\Response|null|void | [
"Lists",
"posts",
"for",
"a",
"tag"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/PostsTagsController.php#L71-L115 | train |
mirko-pagliai/me-cms | src/Command/Install/CreateGroupsCommand.php | CreateGroupsCommand.execute | public function execute(Arguments $args, ConsoleIo $io)
{
$this->loadModel('MeCms.UsersGroups');
if (!$this->UsersGroups->find()->isEmpty()) {
$io->error(__d('me_cms', 'Some user groups already exist'));
return null;
}
//Truncates the table (this resets IDs), then saves groups
ConnectionManager::get('default')->execute(sprintf('TRUNCATE TABLE `%s`', $this->UsersGroups->getTable()));
$this->UsersGroups->saveMany($this->UsersGroups->newEntities([
['id' => 1, 'name' => 'admin', 'label' => 'Admin'],
['id' => 2, 'name' => 'manager', 'label' => 'Manager'],
['id' => 3, 'name' => 'user', 'label' => 'User'],
]));
$io->verbose(__d('me_cms', 'The user groups have been created'));
return null;
} | php | public function execute(Arguments $args, ConsoleIo $io)
{
$this->loadModel('MeCms.UsersGroups');
if (!$this->UsersGroups->find()->isEmpty()) {
$io->error(__d('me_cms', 'Some user groups already exist'));
return null;
}
//Truncates the table (this resets IDs), then saves groups
ConnectionManager::get('default')->execute(sprintf('TRUNCATE TABLE `%s`', $this->UsersGroups->getTable()));
$this->UsersGroups->saveMany($this->UsersGroups->newEntities([
['id' => 1, 'name' => 'admin', 'label' => 'Admin'],
['id' => 2, 'name' => 'manager', 'label' => 'Manager'],
['id' => 3, 'name' => 'user', 'label' => 'User'],
]));
$io->verbose(__d('me_cms', 'The user groups have been created'));
return null;
} | [
"public",
"function",
"execute",
"(",
"Arguments",
"$",
"args",
",",
"ConsoleIo",
"$",
"io",
")",
"{",
"$",
"this",
"->",
"loadModel",
"(",
"'MeCms.UsersGroups'",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"UsersGroups",
"->",
"find",
"(",
")",
"->",... | Creates the user groups
@param Arguments $args The command arguments
@param ConsoleIo $io The console io
@return null|int The exit code or null for success | [
"Creates",
"the",
"user",
"groups"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/Install/CreateGroupsCommand.php#L43-L63 | train |
drdplusinfo/health | DrdPlus/Health/Inflictions/Glared.php | Glared.getCurrentMalus | public function getCurrentMalus(): int
{
if ($this->getGettingUsedToForRounds() === 0) {
return $this->malus;
}
if ($this->isShined()) {
// each rounds of getting used to lowers malus by one point
return $this->malus + $this->getGettingUsedToForRounds();
}
// ten rounds of getting used to are needed to lower glare malus by a single point
return $this->malus + SumAndRound::floor($this->getGettingUsedToForRounds() / 10);
} | php | public function getCurrentMalus(): int
{
if ($this->getGettingUsedToForRounds() === 0) {
return $this->malus;
}
if ($this->isShined()) {
// each rounds of getting used to lowers malus by one point
return $this->malus + $this->getGettingUsedToForRounds();
}
// ten rounds of getting used to are needed to lower glare malus by a single point
return $this->malus + SumAndRound::floor($this->getGettingUsedToForRounds() / 10);
} | [
"public",
"function",
"getCurrentMalus",
"(",
")",
":",
"int",
"{",
"if",
"(",
"$",
"this",
"->",
"getGettingUsedToForRounds",
"(",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
"->",
"malus",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"isShined",
"... | Gives malus to activities requiring sight, already lowered by a time getting used to the glare, if any.
@return int negative integer or zero | [
"Gives",
"malus",
"to",
"activities",
"requiring",
"sight",
"already",
"lowered",
"by",
"a",
"time",
"getting",
"used",
"to",
"the",
"glare",
"if",
"any",
"."
] | f8dee76ddf651367afbbaab6f30376fc80f97001 | https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Inflictions/Glared.php#L54-L65 | train |
drdplusinfo/health | DrdPlus/Health/Inflictions/Glared.php | Glared.setGettingUsedToForTime | public function setGettingUsedToForTime(Time $gettingUsedToFor)
{
$inRounds = $gettingUsedToFor->findRounds();
if ($inRounds === null) {
// it can not be expressed by rounds, so definitely get used to it - malus zeroed
if ($this->isShined()) {
$this->gettingUsedToForRounds = -$this->malus;
} else { // if blinded than needs ten more time to get used to it
$this->gettingUsedToForRounds = -$this->malus * 10;
}
return;
}
if ($this->isShined()) {
if ($this->malus + $inRounds->getValue() > 0) { // more time than needed, malus is gone
$this->gettingUsedToForRounds = -$this->malus; // zeroed malus in fact
} else {
$this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus
}
} else { // if blinded than needs ten more time to get used to it
if ($this->malus + $inRounds->getValue() / 10 > 0) { // more time than needed, malus is gone
$this->gettingUsedToForRounds = -$this->malus * 10; // zeroed malus in fact
} else {
$this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus
}
}
} | php | public function setGettingUsedToForTime(Time $gettingUsedToFor)
{
$inRounds = $gettingUsedToFor->findRounds();
if ($inRounds === null) {
// it can not be expressed by rounds, so definitely get used to it - malus zeroed
if ($this->isShined()) {
$this->gettingUsedToForRounds = -$this->malus;
} else { // if blinded than needs ten more time to get used to it
$this->gettingUsedToForRounds = -$this->malus * 10;
}
return;
}
if ($this->isShined()) {
if ($this->malus + $inRounds->getValue() > 0) { // more time than needed, malus is gone
$this->gettingUsedToForRounds = -$this->malus; // zeroed malus in fact
} else {
$this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus
}
} else { // if blinded than needs ten more time to get used to it
if ($this->malus + $inRounds->getValue() / 10 > 0) { // more time than needed, malus is gone
$this->gettingUsedToForRounds = -$this->malus * 10; // zeroed malus in fact
} else {
$this->gettingUsedToForRounds = $inRounds->getValue(); // not enough to remove whole glare and malus
}
}
} | [
"public",
"function",
"setGettingUsedToForTime",
"(",
"Time",
"$",
"gettingUsedToFor",
")",
"{",
"$",
"inRounds",
"=",
"$",
"gettingUsedToFor",
"->",
"findRounds",
"(",
")",
";",
"if",
"(",
"$",
"inRounds",
"===",
"null",
")",
"{",
"// it can not be expressed by... | Total rounds of getting used to current contrast, which lowers glare and malus.
@param Time $gettingUsedToFor | [
"Total",
"rounds",
"of",
"getting",
"used",
"to",
"current",
"contrast",
"which",
"lowers",
"glare",
"and",
"malus",
"."
] | f8dee76ddf651367afbbaab6f30376fc80f97001 | https://github.com/drdplusinfo/health/blob/f8dee76ddf651367afbbaab6f30376fc80f97001/DrdPlus/Health/Inflictions/Glared.php#L87-L114 | train |
nails/module-auth | src/Controller/BaseMfa.php | BaseMfa.loginUser | protected function loginUser()
{
// Set login data for this user
$oUserModel = Factory::model('User', 'nails/module-auth');
$oUserModel->setLoginData($this->mfaUser->id);
// If we're remembering this user set a cookie
if ($this->remember) {
$oUserModel->setRememberCookie(
$this->mfaUser->id,
$this->mfaUser->password,
$this->mfaUser->email
);
}
// Update their last login and increment their login count
$oUserModel->updateLastLogin($this->mfaUser->id);
// --------------------------------------------------------------------------
// Generate an event for this log in
create_event('did_log_in', ['method' => $this->loginMethod], $this->mfaUser->id);
// --------------------------------------------------------------------------
// Say hello
if ($this->mfaUser->last_login) {
$oConfig = Factory::service('Config');
if ($oConfig->item('authShowNicetimeOnLogin')) {
$sLastLogin = niceTime(strtotime($this->mfaUser->last_login));
} else {
$sLastLogin = toUserDatetime($this->mfaUser->last_login);
}
if ($oConfig->item('authShowLastIpOnLogin')) {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome_with_ip',
[
$this->mfaUser->first_name,
$sLastLogin,
$this->mfaUser->last_ip,
]
);
} else {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome',
[
$this->mfaUser->first_name,
$sLastLogin,
]
);
}
} else {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome_notime',
[
$this->mfaUser->first_name,
]
);
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
// --------------------------------------------------------------------------
// Delete the token we generated, it's no needed, eh!
$oAuthModel = Factory::model('Auth', 'nails/module-auth');
$oAuthModel->mfaTokenDelete($this->data['token']['id']);
// --------------------------------------------------------------------------
$sRedirectUrl = $this->returnTo != site_url() ? $this->returnTo : $this->mfaUser->group_homepage;
redirect($sRedirectUrl);
} | php | protected function loginUser()
{
// Set login data for this user
$oUserModel = Factory::model('User', 'nails/module-auth');
$oUserModel->setLoginData($this->mfaUser->id);
// If we're remembering this user set a cookie
if ($this->remember) {
$oUserModel->setRememberCookie(
$this->mfaUser->id,
$this->mfaUser->password,
$this->mfaUser->email
);
}
// Update their last login and increment their login count
$oUserModel->updateLastLogin($this->mfaUser->id);
// --------------------------------------------------------------------------
// Generate an event for this log in
create_event('did_log_in', ['method' => $this->loginMethod], $this->mfaUser->id);
// --------------------------------------------------------------------------
// Say hello
if ($this->mfaUser->last_login) {
$oConfig = Factory::service('Config');
if ($oConfig->item('authShowNicetimeOnLogin')) {
$sLastLogin = niceTime(strtotime($this->mfaUser->last_login));
} else {
$sLastLogin = toUserDatetime($this->mfaUser->last_login);
}
if ($oConfig->item('authShowLastIpOnLogin')) {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome_with_ip',
[
$this->mfaUser->first_name,
$sLastLogin,
$this->mfaUser->last_ip,
]
);
} else {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome',
[
$this->mfaUser->first_name,
$sLastLogin,
]
);
}
} else {
$sStatus = 'positive';
$sMessage = lang(
'auth_login_ok_welcome_notime',
[
$this->mfaUser->first_name,
]
);
}
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->setFlashData($sStatus, $sMessage);
// --------------------------------------------------------------------------
// Delete the token we generated, it's no needed, eh!
$oAuthModel = Factory::model('Auth', 'nails/module-auth');
$oAuthModel->mfaTokenDelete($this->data['token']['id']);
// --------------------------------------------------------------------------
$sRedirectUrl = $this->returnTo != site_url() ? $this->returnTo : $this->mfaUser->group_homepage;
redirect($sRedirectUrl);
} | [
"protected",
"function",
"loginUser",
"(",
")",
"{",
"// Set login data for this user",
"$",
"oUserModel",
"=",
"Factory",
"::",
"model",
"(",
"'User'",
",",
"'nails/module-auth'",
")",
";",
"$",
"oUserModel",
"->",
"setLoginData",
"(",
"$",
"this",
"->",
"mfaU... | Logs a user In | [
"Logs",
"a",
"user",
"In"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Controller/BaseMfa.php#L121-L205 | train |
PitonCMS/Engine | app/Middleware/LoadSiteSettings.php | LoadSiteSettings.loadSettings | public function loadSettings()
{
$SettingMapper = ($this->dataMapper)('SettingMapper');
$siteSettings = $SettingMapper->find();
// Create new multi-dimensional array keyed by the setting category and key
$this->settings = array_column($siteSettings, 'setting_value', 'setting_key');
// Load some config file settings into new settings
$this->settings['production'] = $this->appSettings['site']['production'];
$this->settings['pitonDev'] = isset($this->appSettings['site']['pitonDev']) ? $this->appSettings['site']['pitonDev'] : false;
} | php | public function loadSettings()
{
$SettingMapper = ($this->dataMapper)('SettingMapper');
$siteSettings = $SettingMapper->find();
// Create new multi-dimensional array keyed by the setting category and key
$this->settings = array_column($siteSettings, 'setting_value', 'setting_key');
// Load some config file settings into new settings
$this->settings['production'] = $this->appSettings['site']['production'];
$this->settings['pitonDev'] = isset($this->appSettings['site']['pitonDev']) ? $this->appSettings['site']['pitonDev'] : false;
} | [
"public",
"function",
"loadSettings",
"(",
")",
"{",
"$",
"SettingMapper",
"=",
"(",
"$",
"this",
"->",
"dataMapper",
")",
"(",
"'SettingMapper'",
")",
";",
"$",
"siteSettings",
"=",
"$",
"SettingMapper",
"->",
"find",
"(",
")",
";",
"// Create new multi-dim... | Load settings from DB
@param none
@return void | [
"Load",
"settings",
"from",
"DB"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Middleware/LoadSiteSettings.php#L81-L92 | train |
PitonCMS/Engine | app/Middleware/LoadSiteSettings.php | LoadSiteSettings.loadPages | public function loadPages($request)
{
$pageMapper = ($this->dataMapper)('pageMapper');
// Fetch all published pages
$this->pages = $pageMapper->findPages();
// Set flag on page for current request
$url = $request->getUri()->getPath();
// Check if home page '/' to match slug name
$url = ($url === '/') ? 'home' : ltrim($url, '/');
$key = array_search($url, array_column($this->pages, 'slug'));
if (is_numeric($key)) {
$this->pages[$key]->currentPage = true;
}
return;
} | php | public function loadPages($request)
{
$pageMapper = ($this->dataMapper)('pageMapper');
// Fetch all published pages
$this->pages = $pageMapper->findPages();
// Set flag on page for current request
$url = $request->getUri()->getPath();
// Check if home page '/' to match slug name
$url = ($url === '/') ? 'home' : ltrim($url, '/');
$key = array_search($url, array_column($this->pages, 'slug'));
if (is_numeric($key)) {
$this->pages[$key]->currentPage = true;
}
return;
} | [
"public",
"function",
"loadPages",
"(",
"$",
"request",
")",
"{",
"$",
"pageMapper",
"=",
"(",
"$",
"this",
"->",
"dataMapper",
")",
"(",
"'pageMapper'",
")",
";",
"// Fetch all published pages",
"$",
"this",
"->",
"pages",
"=",
"$",
"pageMapper",
"->",
"f... | Load pages from DB
Sets currentPage = true flag on page record for current request
@param \Psr\Http\Message\ServerRequestInterface $request PSR7 request
@return void | [
"Load",
"pages",
"from",
"DB"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Middleware/LoadSiteSettings.php#L101-L119 | train |
vanilla/garden-db | src/Literal.php | Literal.getValue | public function getValue(Db $db, ...$args) {
$driver = $this->driverKey($db);
if (isset($this->driverValues[$driver])) {
return sprintf($this->driverValues[$driver], ...$args);
} elseif (isset($this->driverValues['default'])) {
return sprintf($this->driverValues['default'], ...$args);
} else {
throw new \InvalidArgumentException("No literal for driver '$driver'.", 500);
}
} | php | public function getValue(Db $db, ...$args) {
$driver = $this->driverKey($db);
if (isset($this->driverValues[$driver])) {
return sprintf($this->driverValues[$driver], ...$args);
} elseif (isset($this->driverValues['default'])) {
return sprintf($this->driverValues['default'], ...$args);
} else {
throw new \InvalidArgumentException("No literal for driver '$driver'.", 500);
}
} | [
"public",
"function",
"getValue",
"(",
"Db",
"$",
"db",
",",
"...",
"$",
"args",
")",
"{",
"$",
"driver",
"=",
"$",
"this",
"->",
"driverKey",
"(",
"$",
"db",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"driverValues",
"[",
"$",
"driver... | Get the literal value.
@param Db $db The database driver getting the value.
@param mixed ...$args Arguments to pass into the literal. This uses **sprintf()** so arguments must already be escaped.
@return string Returns the value for the specific driver, the default literal, or "null" if there is no default. | [
"Get",
"the",
"literal",
"value",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Literal.php#L46-L56 | train |
vanilla/garden-db | src/Literal.php | Literal.setValue | public function setValue($value, $driver = 'default') {
$driver = $this->driverKey($driver);
$this->driverValues[$driver] = $value;
return $this;
} | php | public function setValue($value, $driver = 'default') {
$driver = $this->driverKey($driver);
$this->driverValues[$driver] = $value;
return $this;
} | [
"public",
"function",
"setValue",
"(",
"$",
"value",
",",
"$",
"driver",
"=",
"'default'",
")",
"{",
"$",
"driver",
"=",
"$",
"this",
"->",
"driverKey",
"(",
"$",
"driver",
")",
";",
"$",
"this",
"->",
"driverValues",
"[",
"$",
"driver",
"]",
"=",
... | Set the literal value.
@param string $value The new value to set.
@param string|object $driver The name of the database driver to set the value for.
@return Literal Returns $this for fluent calls. | [
"Set",
"the",
"literal",
"value",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Literal.php#L65-L69 | train |
vanilla/garden-db | src/Literal.php | Literal.driverKey | protected function driverKey($key) {
if (is_object($key)) {
$key = get_class($key);
}
$key = strtolower(basename($key));
if (preg_match('`([az]+)(Db)?$`', $key, $m)) {
$key = $m;
}
return $key;
} | php | protected function driverKey($key) {
if (is_object($key)) {
$key = get_class($key);
}
$key = strtolower(basename($key));
if (preg_match('`([az]+)(Db)?$`', $key, $m)) {
$key = $m;
}
return $key;
} | [
"protected",
"function",
"driverKey",
"(",
"$",
"key",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"key",
")",
")",
"{",
"$",
"key",
"=",
"get_class",
"(",
"$",
"key",
")",
";",
"}",
"$",
"key",
"=",
"strtolower",
"(",
"basename",
"(",
"$",
"key"... | Normalize the driver name for the drivers array.
@param string|object $key The name of the driver or an instance of a database driver.
@return string Returns the driver name normalized. | [
"Normalize",
"the",
"driver",
"name",
"for",
"the",
"drivers",
"array",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Literal.php#L77-L87 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.getOptions | public static function getOptions($userSpecified, $defaults)
{
$options = static::getAnyOptions($userSpecified, $defaults);
foreach ($options as $key => $null) {
if (array_key_exists($key, $defaults)) {
continue;
}
throw new \InvalidArgumentException("Unknown parameter (" . $key . ")");
}
return $options;
} | php | public static function getOptions($userSpecified, $defaults)
{
$options = static::getAnyOptions($userSpecified, $defaults);
foreach ($options as $key => $null) {
if (array_key_exists($key, $defaults)) {
continue;
}
throw new \InvalidArgumentException("Unknown parameter (" . $key . ")");
}
return $options;
} | [
"public",
"static",
"function",
"getOptions",
"(",
"$",
"userSpecified",
",",
"$",
"defaults",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getAnyOptions",
"(",
"$",
"userSpecified",
",",
"$",
"defaults",
")",
";",
"foreach",
"(",
"$",
"options",
"as",
... | Simulate named arguments using associative arrays.
Basically just merge the two arrays, giving user specified options the preference.
Also ensures that each paramater in the user array is valid and throws an exception if an unknown element is found.
@param array $userSpecified The array of options passed to the function call
@param array $defaults The default options to be used
@return array | [
"Simulate",
"named",
"arguments",
"using",
"associative",
"arrays",
".",
"Basically",
"just",
"merge",
"the",
"two",
"arrays",
"giving",
"user",
"specified",
"options",
"the",
"preference",
".",
"Also",
"ensures",
"that",
"each",
"paramater",
"in",
"the",
"user"... | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L23-L35 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.toString | public static function toString($data)
{
if (is_array($data)) {
$newData = [];
foreach ($data as $key => $val) {
$key = (string)$key;
$newData[$key] = static::toString($val);
}
} else {
$newData = (string)$data;
}
return $newData;
} | php | public static function toString($data)
{
if (is_array($data)) {
$newData = [];
foreach ($data as $key => $val) {
$key = (string)$key;
$newData[$key] = static::toString($val);
}
} else {
$newData = (string)$data;
}
return $newData;
} | [
"public",
"static",
"function",
"toString",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"$",
"newData",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"$",
... | Ensure that the passed parameter is a string, or an array of strings.
@param mixed $data The value to convert to a string
@return string|string[] | [
"Ensure",
"that",
"the",
"passed",
"parameter",
"is",
"a",
"string",
"or",
"an",
"array",
"of",
"strings",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L67-L80 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.toArray | public static function toArray($value)
{
# If it's already an array then just pass it back
if (is_array($value)) {
return $value;
}
if ($value instanceof SerialObject) {
return $value->asArray();
}
if ($value instanceof \ArrayObject) {
return $value->getArrayCopy();
}
# If it's not an array then create a new array to be returned
$array = [];
# If a value was passed as a string/int then include it in the new array
if ($value) {
$array[] = $value;
}
return $array;
} | php | public static function toArray($value)
{
# If it's already an array then just pass it back
if (is_array($value)) {
return $value;
}
if ($value instanceof SerialObject) {
return $value->asArray();
}
if ($value instanceof \ArrayObject) {
return $value->getArrayCopy();
}
# If it's not an array then create a new array to be returned
$array = [];
# If a value was passed as a string/int then include it in the new array
if ($value) {
$array[] = $value;
}
return $array;
} | [
"public",
"static",
"function",
"toArray",
"(",
"$",
"value",
")",
"{",
"# If it's already an array then just pass it back",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"value",
";",
"}",
"if",
"(",
"$",
"value",
"instanceof",
"Se... | Ensure that the passed parameter is an array.
If it is a truthy value then make it the sole element of an array.
@param mixed $value The value to convert to an array
@return array | [
"Ensure",
"that",
"the",
"passed",
"parameter",
"is",
"an",
"array",
".",
"If",
"it",
"is",
"a",
"truthy",
"value",
"then",
"make",
"it",
"the",
"sole",
"element",
"of",
"an",
"array",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L91-L115 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.dateDiff | public static function dateDiff($from, $to = null)
{
if (!$to) {
$to = $from;
$from = date("d/m/Y");
}
if (!$dateFrom = static::date("U", $from)) {
return;
}
if (!$dateTo = static::date("U", $to)) {
return;
}
$diff = $dateTo - $dateFrom;
$days = round($diff / 86400);
return $days;
} | php | public static function dateDiff($from, $to = null)
{
if (!$to) {
$to = $from;
$from = date("d/m/Y");
}
if (!$dateFrom = static::date("U", $from)) {
return;
}
if (!$dateTo = static::date("U", $to)) {
return;
}
$diff = $dateTo - $dateFrom;
$days = round($diff / 86400);
return $days;
} | [
"public",
"static",
"function",
"dateDiff",
"(",
"$",
"from",
",",
"$",
"to",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"to",
")",
"{",
"$",
"to",
"=",
"$",
"from",
";",
"$",
"from",
"=",
"date",
"(",
"\"d/m/Y\"",
")",
";",
"}",
"if",
"(",
... | Compare two dates and return an integer representing their difference in days.
Returns null if any of the parsing fails.
@param string|int $from The first date to parse
@param string|int $to The second date to parse
@return int|null | [
"Compare",
"two",
"dates",
"and",
"return",
"an",
"integer",
"representing",
"their",
"difference",
"in",
"days",
".",
"Returns",
"null",
"if",
"any",
"of",
"the",
"parsing",
"fails",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L284-L303 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.getBestDivisor | public static function getBestDivisor($rows, $options = null)
{
$options = static::getOptions($options, [
"min" => 5,
"max" => 10,
]);
if ($rows <= $options["max"]) {
return $rows;
}
$divisor = false;
$divisorDiff = false;
for ($i = $options["max"]; $i >= $options["min"]; $i--) {
$remain = $rows % $i;
# Calculate how close the remainder is to the postentional divisor
$quality = $i - $remain;
# If no divisor has been set yet then set it to this one, and record it's quality
if (!$num) {
$divisor = $i;
$divisorQuality = $quality;
continue;
}
# If the potentional divisor is a better match than the currently selected one then select it instead
if ($quality < $divisorQuality) {
$divisor = $i;
$divisorQuality = $quality;
}
}
return $divisor;
} | php | public static function getBestDivisor($rows, $options = null)
{
$options = static::getOptions($options, [
"min" => 5,
"max" => 10,
]);
if ($rows <= $options["max"]) {
return $rows;
}
$divisor = false;
$divisorDiff = false;
for ($i = $options["max"]; $i >= $options["min"]; $i--) {
$remain = $rows % $i;
# Calculate how close the remainder is to the postentional divisor
$quality = $i - $remain;
# If no divisor has been set yet then set it to this one, and record it's quality
if (!$num) {
$divisor = $i;
$divisorQuality = $quality;
continue;
}
# If the potentional divisor is a better match than the currently selected one then select it instead
if ($quality < $divisorQuality) {
$divisor = $i;
$divisorQuality = $quality;
}
}
return $divisor;
} | [
"public",
"static",
"function",
"getBestDivisor",
"(",
"$",
"rows",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"min\"",
"=>",
"5",
",",
"\"max\"",
"=>",
"10",
",",
"... | Calculate the most reasonable divisor for a total.
Useful for repeating headers in a table with many rows.
$options:
- int "min" The minimum number of rows to allow before breaking (default: 5)
- int "max" The maximum number of rows to allow before breaking (default: 10)
@param int $rows The total number to calculate from (eg, total number of rows in a table)
@param array $options An array of options (see above)
@return int | [
"Calculate",
"the",
"most",
"reasonable",
"divisor",
"for",
"a",
"total",
".",
"Useful",
"for",
"repeating",
"headers",
"in",
"a",
"table",
"with",
"many",
"rows",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L354-L389 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.createPassword | public static function createPassword($options = null)
{
$options = static::getOptions($options, [
"bad" => ["1", "l", "I", "5", "S", "0", "O", "o"],
"exclude" => [],
"length" => 10,
"lowercase" => true,
"uppercase" => true,
"numbers" => true,
"specialchars" => true,
]);
$password = "";
if (!$options["lowercase"] && !$options["specialchars"] && !$options["numbers"] && !$options["uppercase"]) {
return $password;
}
$exclude = array_merge($options["bad"], $options["exclude"]);
# Keep adding characters until the password is at least as long as required
while (mb_strlen($password) < $options["length"]) {
# Add a few characters from each acceptable set
if ($options["lowercase"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(97, 122));
}
}
if ($options["specialchars"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
switch (rand(0, 3)) {
case 0:
$password .= chr(rand(33, 47));
break;
case 1:
$password .= chr(rand(58, 64));
break;
case 2:
$password .= chr(rand(91, 93));
break;
case 3:
$password .= chr(rand(123, 126));
break;
}
}
}
if ($options["numbers"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(48, 57));
}
}
if ($options["uppercase"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(65, 90));
}
}
# Remove excluded characters
$password = str_replace($exclude, "", $password);
}
# Reduce the length of the generated password to the required length
$password = mb_substr($password, 0, $options["length"]);
return $password;
} | php | public static function createPassword($options = null)
{
$options = static::getOptions($options, [
"bad" => ["1", "l", "I", "5", "S", "0", "O", "o"],
"exclude" => [],
"length" => 10,
"lowercase" => true,
"uppercase" => true,
"numbers" => true,
"specialchars" => true,
]);
$password = "";
if (!$options["lowercase"] && !$options["specialchars"] && !$options["numbers"] && !$options["uppercase"]) {
return $password;
}
$exclude = array_merge($options["bad"], $options["exclude"]);
# Keep adding characters until the password is at least as long as required
while (mb_strlen($password) < $options["length"]) {
# Add a few characters from each acceptable set
if ($options["lowercase"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(97, 122));
}
}
if ($options["specialchars"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
switch (rand(0, 3)) {
case 0:
$password .= chr(rand(33, 47));
break;
case 1:
$password .= chr(rand(58, 64));
break;
case 2:
$password .= chr(rand(91, 93));
break;
case 3:
$password .= chr(rand(123, 126));
break;
}
}
}
if ($options["numbers"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(48, 57));
}
}
if ($options["uppercase"]) {
$max = rand(1, 3);
for ($i = 0; $i < $max; ++$i) {
$password .= chr(rand(65, 90));
}
}
# Remove excluded characters
$password = str_replace($exclude, "", $password);
}
# Reduce the length of the generated password to the required length
$password = mb_substr($password, 0, $options["length"]);
return $password;
} | [
"public",
"static",
"function",
"createPassword",
"(",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"bad\"",
"=>",
"[",
"\"1\"",
",",
"\"l\"",
",",
"\"I\"",
",",
"\"5\"",
","... | Generate a password.
$options:
- array "bad" Characters that should not be used as they are ambigious (default: [1, l, I, 5, S, 0, O, o])
- array "exclude" Other characters that should not be used (default: [])
- int "length" The length of the password that should be generated (default: 10)
- bool "lowercase" Include lowercase letters (default: true)
- bool "uppercase" Include uppercase letters (default: true)
- bool "numbers" Include numbers (default: true)
- bool "specialchars" Include special characters (default: true)
@param array $options An array of options (see above)
@return string | [
"Generate",
"a",
"password",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L408-L482 | train |
duncan3dc/php-helpers | src/Helper.php | Helper.checkPassword | public static function checkPassword($password, $options = null)
{
$options = static::getOptions($options, [
"length" => 8,
"unique" => 4,
"lowercase" => true,
"uppercase" => true,
"alpha" => true,
"numeric" => true,
]);
$problems = [];
$len = mb_strlen($password);
if ($len < $options["length"]) {
$problems["length"] = "Passwords must be at least " . $options["length"] . " characters long";
}
$unique = [];
for ($i = 0; $i < $len; ++$i) {
$char = mb_substr($password, $i, 1);
if (!in_array($char, $unique)) {
$unique[] = $char;
}
}
if (count($unique) < $options["unique"]) {
$problems["unique"] = "Passwords must contain at least " . $options["unique"] . " unique characters";
}
if (!preg_match("/[a-z]/", $password)) {
$problems["lowercase"] = "Passwords must contain at least 1 lowercase letter";
}
if (!preg_match("/[A-Z]/", $password)) {
$problems["uppercase"] = "Passwords must contain at least 1 uppercase letter";
}
if (!preg_match("/[a-z]/i", $password)) {
$problems["alpha"] = "Passwords must contain at least 1 letter";
}
if (!preg_match("/[0-9]/", $password)) {
$problems["numeric"] = "Passwords must contain at least 1 number";
}
return $problems;
} | php | public static function checkPassword($password, $options = null)
{
$options = static::getOptions($options, [
"length" => 8,
"unique" => 4,
"lowercase" => true,
"uppercase" => true,
"alpha" => true,
"numeric" => true,
]);
$problems = [];
$len = mb_strlen($password);
if ($len < $options["length"]) {
$problems["length"] = "Passwords must be at least " . $options["length"] . " characters long";
}
$unique = [];
for ($i = 0; $i < $len; ++$i) {
$char = mb_substr($password, $i, 1);
if (!in_array($char, $unique)) {
$unique[] = $char;
}
}
if (count($unique) < $options["unique"]) {
$problems["unique"] = "Passwords must contain at least " . $options["unique"] . " unique characters";
}
if (!preg_match("/[a-z]/", $password)) {
$problems["lowercase"] = "Passwords must contain at least 1 lowercase letter";
}
if (!preg_match("/[A-Z]/", $password)) {
$problems["uppercase"] = "Passwords must contain at least 1 uppercase letter";
}
if (!preg_match("/[a-z]/i", $password)) {
$problems["alpha"] = "Passwords must contain at least 1 letter";
}
if (!preg_match("/[0-9]/", $password)) {
$problems["numeric"] = "Passwords must contain at least 1 number";
}
return $problems;
} | [
"public",
"static",
"function",
"checkPassword",
"(",
"$",
"password",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"static",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"length\"",
"=>",
"8",
",",
"\"unique\"",
"=>",
"4",
... | Check if a password conforms to the specified complexitiy rules.
If the password passes all tests then the function returns an empty array.
Otherwise it returns an array of all the checks that failed.
$options:
- int "length" The minimum length the password must be (default: 8)
- int "unique" The number of unique characters the password must contain (default: 4)
- bool "lowercase" Whether the password must contain lowercase letters (default: true)
- bool "uppercase" Whether the password must contain uppercase letters (default: true)
- bool "alpha" Whether the password must contain letters (default: true)
- bool "numbers" Whether the password must contain numbers (default: true)
@param string $password The password to check
@param array $options An array of options (see above)
@return string[] | [
"Check",
"if",
"a",
"password",
"conforms",
"to",
"the",
"specified",
"complexitiy",
"rules",
".",
"If",
"the",
"password",
"passes",
"all",
"tests",
"then",
"the",
"function",
"returns",
"an",
"empty",
"array",
".",
"Otherwise",
"it",
"returns",
"an",
"arra... | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Helper.php#L503-L547 | train |
Kolyunya/codeception-markup-validator | sources/Lib/MarkupValidator/MarkupValidatorMessage.php | MarkupValidatorMessage.setType | public function setType($type)
{
if ($type === null) {
$type = self::TYPE_UNDEFINED;
}
$this->type = $type;
return $this;
} | php | public function setType($type)
{
if ($type === null) {
$type = self::TYPE_UNDEFINED;
}
$this->type = $type;
return $this;
} | [
"public",
"function",
"setType",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"null",
")",
"{",
"$",
"type",
"=",
"self",
"::",
"TYPE_UNDEFINED",
";",
"}",
"$",
"this",
"->",
"type",
"=",
"$",
"type",
";",
"return",
"$",
"this",
";"... | Sets message type.
@param string $type Message type.
@return self Returns self. | [
"Sets",
"message",
"type",
"."
] | 89b5fa5e28602af7e7f2a8ee42686be697dd00a7 | https://github.com/Kolyunya/codeception-markup-validator/blob/89b5fa5e28602af7e7f2a8ee42686be697dd00a7/sources/Lib/MarkupValidator/MarkupValidatorMessage.php#L91-L100 | train |
vegas-cmf/core | src/Cli/Bootstrap.php | Bootstrap.initEventsManager | public function initEventsManager()
{
$taskListener = new TaskListener();
//extracts default events manager
$eventsManager = $this->di->getShared('eventsManager');
//attaches new event console:beforeTaskHandle and console:afterTaskHandle
$eventsManager->attach(
'console:beforeHandleTask', $taskListener->beforeHandleTask($this->arguments)
);
$eventsManager->attach(
'console:afterHandleTask', $taskListener->afterHandleTask()
);
$this->application->setEventsManager($eventsManager);
} | php | public function initEventsManager()
{
$taskListener = new TaskListener();
//extracts default events manager
$eventsManager = $this->di->getShared('eventsManager');
//attaches new event console:beforeTaskHandle and console:afterTaskHandle
$eventsManager->attach(
'console:beforeHandleTask', $taskListener->beforeHandleTask($this->arguments)
);
$eventsManager->attach(
'console:afterHandleTask', $taskListener->afterHandleTask()
);
$this->application->setEventsManager($eventsManager);
} | [
"public",
"function",
"initEventsManager",
"(",
")",
"{",
"$",
"taskListener",
"=",
"new",
"TaskListener",
"(",
")",
";",
"//extracts default events manager",
"$",
"eventsManager",
"=",
"$",
"this",
"->",
"di",
"->",
"getShared",
"(",
"'eventsManager'",
")",
";"... | Setups CLI events manager | [
"Setups",
"CLI",
"events",
"manager"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Bootstrap.php#L128-L142 | train |
Alorel/phpunit-auto-rerun | src/Annotations/Tags/RetryCount.php | RetryCount.create | public static function create($body, DescriptionFactory $descriptionFactory = null, Context $context = null) {
Assert::integerish($body, self::MSG);
Assert::greaterThanEq($body, 0, self::MSG);
Assert::notNull($descriptionFactory);
return new static($descriptionFactory->create($body, $context));
} | php | public static function create($body, DescriptionFactory $descriptionFactory = null, Context $context = null) {
Assert::integerish($body, self::MSG);
Assert::greaterThanEq($body, 0, self::MSG);
Assert::notNull($descriptionFactory);
return new static($descriptionFactory->create($body, $context));
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"body",
",",
"DescriptionFactory",
"$",
"descriptionFactory",
"=",
"null",
",",
"Context",
"$",
"context",
"=",
"null",
")",
"{",
"Assert",
"::",
"integerish",
"(",
"$",
"body",
",",
"self",
"::",
"MSG",
... | Create the tag
@param string $body Tag body
@param DescriptionFactory $descriptionFactory The description factory
@param Context|null $context The Context is used to resolve Types and FQSENs, although optional
it is highly recommended to pass it. If you omit it then it is assumed that
the DocBlock is in the global namespace and has no `use` statements.
@return RetryCount | [
"Create",
"the",
"tag"
] | 5ed91cf5ce25ad3cee31a517b928cbbf9cd9771a | https://github.com/Alorel/phpunit-auto-rerun/blob/5ed91cf5ce25ad3cee31a517b928cbbf9cd9771a/src/Annotations/Tags/RetryCount.php#L62-L68 | train |
bwaidelich/Wwwision.PrivateResources | Classes/Resource/Target/ProtectedResourceTarget.php | ProtectedResourceTarget.detectResourcesBaseUri | protected function detectResourcesBaseUri()
{
$uri = '';
$request = $this->getHttpRequest();
if ($request instanceof HttpRequest) {
$uri = $request->getBaseUri();
}
return (string)$uri;
} | php | protected function detectResourcesBaseUri()
{
$uri = '';
$request = $this->getHttpRequest();
if ($request instanceof HttpRequest) {
$uri = $request->getBaseUri();
}
return (string)$uri;
} | [
"protected",
"function",
"detectResourcesBaseUri",
"(",
")",
"{",
"$",
"uri",
"=",
"''",
";",
"$",
"request",
"=",
"$",
"this",
"->",
"getHttpRequest",
"(",
")",
";",
"if",
"(",
"$",
"request",
"instanceof",
"HttpRequest",
")",
"{",
"$",
"uri",
"=",
"$... | Detects and returns the website's base URI
@return string The website's base URI | [
"Detects",
"and",
"returns",
"the",
"website",
"s",
"base",
"URI"
] | d74bd290131d77c0247a5e70ea42a6ff29241a6e | https://github.com/bwaidelich/Wwwision.PrivateResources/blob/d74bd290131d77c0247a5e70ea42a6ff29241a6e/Classes/Resource/Target/ProtectedResourceTarget.php#L173-L181 | train |
vegas-cmf/core | src/DI/ServiceManager.php | ServiceManager.getService | public function getService($name)
{
try {
if (!$this->isRegisteredService($name)) {
$this->registerService($name);
}
return $this->di->get($name);
} catch (\Phalcon\DI\Exception $ex) {
throw new Exception($ex->getMessage().', using: '.$name);
}
} | php | public function getService($name)
{
try {
if (!$this->isRegisteredService($name)) {
$this->registerService($name);
}
return $this->di->get($name);
} catch (\Phalcon\DI\Exception $ex) {
throw new Exception($ex->getMessage().', using: '.$name);
}
} | [
"public",
"function",
"getService",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isRegisteredService",
"(",
"$",
"name",
")",
")",
"{",
"$",
"this",
"->",
"registerService",
"(",
"$",
"name",
")",
";",
"}",
"return",
... | Try to register and return service.
@param $name
@return object
@throws Service\Exception | [
"Try",
"to",
"register",
"and",
"return",
"service",
"."
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/DI/ServiceManager.php#L53-L63 | train |
vegas-cmf/core | src/DI/ServiceManager.php | ServiceManager.hasService | public function hasService($name)
{
try {
$service = $this->getService($name);
return !empty($service);
} catch (\Vegas\DI\Service\Exception $ex) {
return false;
}
} | php | public function hasService($name)
{
try {
$service = $this->getService($name);
return !empty($service);
} catch (\Vegas\DI\Service\Exception $ex) {
return false;
}
} | [
"public",
"function",
"hasService",
"(",
"$",
"name",
")",
"{",
"try",
"{",
"$",
"service",
"=",
"$",
"this",
"->",
"getService",
"(",
"$",
"name",
")",
";",
"return",
"!",
"empty",
"(",
"$",
"service",
")",
";",
"}",
"catch",
"(",
"\\",
"Vegas",
... | Try to register service and return information about service existence.
@param $name
@return bool | [
"Try",
"to",
"register",
"service",
"and",
"return",
"information",
"about",
"service",
"existence",
"."
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/DI/ServiceManager.php#L82-L90 | train |
vegas-cmf/core | src/Mvc/ControllerAbstract.php | ControllerAbstract.jsonResponse | protected function jsonResponse($data = array())
{
$this->view->disable();
$this->response->setContentType('application/json', 'UTF-8');
return $this->response->setJsonContent($data);
} | php | protected function jsonResponse($data = array())
{
$this->view->disable();
$this->response->setContentType('application/json', 'UTF-8');
return $this->response->setJsonContent($data);
} | [
"protected",
"function",
"jsonResponse",
"(",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"view",
"->",
"disable",
"(",
")",
";",
"$",
"this",
"->",
"response",
"->",
"setContentType",
"(",
"'application/json'",
",",
"'UTF-8'",
")",... | Renders JSON response
Disables view
@param array|\Phalcon\Http\ResponseInterface $data
@return null|\Phalcon\Http\ResponseInterface | [
"Renders",
"JSON",
"response",
"Disables",
"view"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Mvc/ControllerAbstract.php#L48-L54 | train |
neos/Neos.MarketPlace | Classes/Property/TypeConverter/PackageConverter.php | PackageConverter.getForce | protected function getForce(PropertyMappingConfigurationInterface $configuration = null)
{
if ($configuration === null) {
throw new InvalidPropertyMappingConfigurationException('Missing property configuration', 1457516367);
}
return (boolean)$configuration->getConfigurationValue(PackageConverter::class, self::FORCE);
} | php | protected function getForce(PropertyMappingConfigurationInterface $configuration = null)
{
if ($configuration === null) {
throw new InvalidPropertyMappingConfigurationException('Missing property configuration', 1457516367);
}
return (boolean)$configuration->getConfigurationValue(PackageConverter::class, self::FORCE);
} | [
"protected",
"function",
"getForce",
"(",
"PropertyMappingConfigurationInterface",
"$",
"configuration",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"configuration",
"===",
"null",
")",
"{",
"throw",
"new",
"InvalidPropertyMappingConfigurationException",
"(",
"'Missing prope... | Is force mode enabled
If force mode is enabled the package is update regardless the last updated version.
@param PropertyMappingConfigurationInterface|null $configuration
@return bool
@throws InvalidPropertyMappingConfigurationException | [
"Is",
"force",
"mode",
"enabled"
] | 42b844be976cfcd1e2ab4c8966da006047f04abf | https://github.com/neos/Neos.MarketPlace/blob/42b844be976cfcd1e2ab4c8966da006047f04abf/Classes/Property/TypeConverter/PackageConverter.php#L608-L614 | train |
duncan3dc/php-helpers | src/Html.php | Html.getCurrencies | public static function getCurrencies($symbols = null)
{
$currencies = Cache::call("get-currencies", function() {
$currencies = Yaml::decodeFromFile(__DIR__ . "/../data/currencies.yaml");
if ($currencies instanceof SerialObject) {
$currencies = $currencies->asArray();
}
return array_map(function($data) {
if (!isset($data["prefix"])) {
$data["prefix"] = "";
}
if (!isset($data["suffix"])) {
$data["suffix"] = "";
}
return $data;
}, $currencies);
});
if ($symbols) {
return $currencies;
}
$return = [];
foreach ($currencies as $key => $val) {
$return[$key] = $val["title"];
}
return $return;
} | php | public static function getCurrencies($symbols = null)
{
$currencies = Cache::call("get-currencies", function() {
$currencies = Yaml::decodeFromFile(__DIR__ . "/../data/currencies.yaml");
if ($currencies instanceof SerialObject) {
$currencies = $currencies->asArray();
}
return array_map(function($data) {
if (!isset($data["prefix"])) {
$data["prefix"] = "";
}
if (!isset($data["suffix"])) {
$data["suffix"] = "";
}
return $data;
}, $currencies);
});
if ($symbols) {
return $currencies;
}
$return = [];
foreach ($currencies as $key => $val) {
$return[$key] = $val["title"];
}
return $return;
} | [
"public",
"static",
"function",
"getCurrencies",
"(",
"$",
"symbols",
"=",
"null",
")",
"{",
"$",
"currencies",
"=",
"Cache",
"::",
"call",
"(",
"\"get-currencies\"",
",",
"function",
"(",
")",
"{",
"$",
"currencies",
"=",
"Yaml",
"::",
"decodeFromFile",
"... | Get the currencies supported by the Html class methods.
@param boolean $symbols Whether to return a multi-dimensional array with the symbols of a currency, or just the currency codes and their names
@return array Keyed by the currency code, value depends on the $symbols parameter | [
"Get",
"the",
"currencies",
"supported",
"by",
"the",
"Html",
"class",
"methods",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Html.php#L82-L112 | train |
duncan3dc/php-helpers | src/Html.php | Html.formatKey | public static function formatKey($key, $options = null)
{
$options = Helper::getOptions($options, [
"underscores" => true,
"ucwords" => true,
]);
if ($options["underscores"]) {
$val = str_replace("_", " ", $key);
}
if ($options["ucwords"]) {
$val = ucwords($val);
}
return $val;
} | php | public static function formatKey($key, $options = null)
{
$options = Helper::getOptions($options, [
"underscores" => true,
"ucwords" => true,
]);
if ($options["underscores"]) {
$val = str_replace("_", " ", $key);
}
if ($options["ucwords"]) {
$val = ucwords($val);
}
return $val;
} | [
"public",
"static",
"function",
"formatKey",
"(",
"$",
"key",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"Helper",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"underscores\"",
"=>",
"true",
",",
"\"ucwords\"",
"=>",
"true",... | Format a string in a human readable way.
Typically used for converting "safe" strings like "section_title" to user displayable strings like "Section Title"
$options:
- string "underscores" Convert underscores to spaces (default: true)
- string "ucwords" Run the string through ucwords (default: true)
@param string $key The string to format
@param array $options An array of options (see above)
@return string | [
"Format",
"a",
"string",
"in",
"a",
"human",
"readable",
"way",
".",
"Typically",
"used",
"for",
"converting",
"safe",
"strings",
"like",
"section_title",
"to",
"user",
"displayable",
"strings",
"like",
"Section",
"Title"
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Html.php#L128-L144 | train |
duncan3dc/php-helpers | src/Html.php | Html.string | public static function string($string, $options = null)
{
$options = Helper::getOptions($options, [
"alt" => "n/a",
]);
$string = trim($string);
if (!$string) {
return $options["alt"];
}
return $string;
} | php | public static function string($string, $options = null)
{
$options = Helper::getOptions($options, [
"alt" => "n/a",
]);
$string = trim($string);
if (!$string) {
return $options["alt"];
}
return $string;
} | [
"public",
"static",
"function",
"string",
"(",
"$",
"string",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"Helper",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"alt\"",
"=>",
"\"n/a\"",
",",
"]",
")",
";",
"$",
"string",... | Trim a string, and return an alternative if it is falsey.
$options:
- string "alt" The string that should be returned if the input is falsey (default: "n/a")
@param string $string The string to format
@param array $options An array of options (see above)
@return string | [
"Trim",
"a",
"string",
"and",
"return",
"an",
"alternative",
"if",
"it",
"is",
"falsey",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Html.php#L158-L171 | train |
duncan3dc/php-helpers | src/Html.php | Html.stringLimit | public static function stringLimit($string, $options = null)
{
$options = Helper::getOptions($options, [
"length" => 30,
"extra" => 0,
"alt" => "n/a",
"words" => true,
"suffix" => "...",
]);
if (!$string = trim($string)) {
return $options["alt"];
}
if ($options["words"]) {
while (mb_strlen($string) > ($options["length"] + $options["extra"])) {
$string = mb_substr($string, 0, $options["length"]);
$string = trim($string);
$words = explode(" ", $string);
array_pop($words);
$string = implode(" ", $words);
$string .= $options["suffix"];
}
} else {
$length = $options["length"] + $options["extra"] + mb_strlen($options["suffix"]);
if (mb_strlen($string) > $length) {
$string = mb_substr($string, 0, $length);
$string .= $options["suffix"];
}
}
return $string;
} | php | public static function stringLimit($string, $options = null)
{
$options = Helper::getOptions($options, [
"length" => 30,
"extra" => 0,
"alt" => "n/a",
"words" => true,
"suffix" => "...",
]);
if (!$string = trim($string)) {
return $options["alt"];
}
if ($options["words"]) {
while (mb_strlen($string) > ($options["length"] + $options["extra"])) {
$string = mb_substr($string, 0, $options["length"]);
$string = trim($string);
$words = explode(" ", $string);
array_pop($words);
$string = implode(" ", $words);
$string .= $options["suffix"];
}
} else {
$length = $options["length"] + $options["extra"] + mb_strlen($options["suffix"]);
if (mb_strlen($string) > $length) {
$string = mb_substr($string, 0, $length);
$string .= $options["suffix"];
}
}
return $string;
} | [
"public",
"static",
"function",
"stringLimit",
"(",
"$",
"string",
",",
"$",
"options",
"=",
"null",
")",
"{",
"$",
"options",
"=",
"Helper",
"::",
"getOptions",
"(",
"$",
"options",
",",
"[",
"\"length\"",
"=>",
"30",
",",
"\"extra\"",
"=>",
"0",
",",... | Limit a string to a maximum length.
$options:
- int "length" The maximum length that the string can be (default: 30)
- int "extra" The extra length that is acceptable, while aiming for the above length (default: 0)
- string "alt" The string that should be returned if the input is falsey (default: "n/a")
- bool "words" Set to true to never break in the middle of a word (default: true)
- string "suffix" The string that should be appended if the input has been shortened (default: "...")
@param string $string The string to limit
@param array $options An array of options (see above)
@return string | [
"Limit",
"a",
"string",
"to",
"a",
"maximum",
"length",
"."
] | 0305d220183d9b515f17600bf064291da7a8813b | https://github.com/duncan3dc/php-helpers/blob/0305d220183d9b515f17600bf064291da7a8813b/src/Html.php#L189-L223 | train |
vegas-cmf/core | src/Cli/Loader.php | Loader.parseArguments | public function parseArguments(Console $console, $arguments)
{
$this->consoleApp = $console;
if (count($arguments) == 1) {
throw new TaskNotFoundException();
}
$taskName = $this->lookupTaskClass($arguments);
//prepares an array containing arguments for CLI handler
$parsedArguments = array(
'task' => $taskName,
'action' => isset($arguments[2]) ? $arguments[2] : false
);
//adds additional arguments
$parsedArguments[] = count($arguments) > 3 ? array_slice($arguments, 3) : array();
return $parsedArguments;
} | php | public function parseArguments(Console $console, $arguments)
{
$this->consoleApp = $console;
if (count($arguments) == 1) {
throw new TaskNotFoundException();
}
$taskName = $this->lookupTaskClass($arguments);
//prepares an array containing arguments for CLI handler
$parsedArguments = array(
'task' => $taskName,
'action' => isset($arguments[2]) ? $arguments[2] : false
);
//adds additional arguments
$parsedArguments[] = count($arguments) > 3 ? array_slice($arguments, 3) : array();
return $parsedArguments;
} | [
"public",
"function",
"parseArguments",
"(",
"Console",
"$",
"console",
",",
"$",
"arguments",
")",
"{",
"$",
"this",
"->",
"consoleApp",
"=",
"$",
"console",
";",
"if",
"(",
"count",
"(",
"$",
"arguments",
")",
"==",
"1",
")",
"{",
"throw",
"new",
"... | Parses indicated arguments from command line
Returns prepared array with task, action and additional arguments
@param Console $console
@param $arguments
@throws Exception\TaskActionNotSpecifiedException
@throws Exception\TaskNotFoundException
@return array | [
"Parses",
"indicated",
"arguments",
"from",
"command",
"line",
"Returns",
"prepared",
"array",
"with",
"task",
"action",
"and",
"additional",
"arguments"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Loader.php#L47-L63 | train |
vegas-cmf/core | src/Cli/Loader.php | Loader.toNamespace | private function toNamespace($str) {
$stringParts = preg_split('/_+/', $str);
foreach($stringParts as $key => $stringPart){
$stringParts[$key] = ucfirst(strtolower($stringPart));
}
return implode('\\', $stringParts) . '\\';
} | php | private function toNamespace($str) {
$stringParts = preg_split('/_+/', $str);
foreach($stringParts as $key => $stringPart){
$stringParts[$key] = ucfirst(strtolower($stringPart));
}
return implode('\\', $stringParts) . '\\';
} | [
"private",
"function",
"toNamespace",
"(",
"$",
"str",
")",
"{",
"$",
"stringParts",
"=",
"preg_split",
"(",
"'/_+/'",
",",
"$",
"str",
")",
";",
"foreach",
"(",
"$",
"stringParts",
"as",
"$",
"key",
"=>",
"$",
"stringPart",
")",
"{",
"$",
"stringParts... | Converts indicated string to namespace format.
@param string $str
@throws CliException
@return string
@internal | [
"Converts",
"indicated",
"string",
"to",
"namespace",
"format",
"."
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Loader.php#L106-L113 | train |
vegas-cmf/core | src/Cli/Loader.php | Loader.loadAppTask | private function loadAppTask(array $task)
{
//if task name contains more than 2 parts then it comes from module
if (count($task) > 2) {
$moduleName = ucfirst($task[1]);
$taskName = ucfirst($task[2]);
$taskName = $this->loadAppModuleTask($moduleName, $taskName);
} else {
$taskName = ucfirst($task[1]);
}
return $taskName;
} | php | private function loadAppTask(array $task)
{
//if task name contains more than 2 parts then it comes from module
if (count($task) > 2) {
$moduleName = ucfirst($task[1]);
$taskName = ucfirst($task[2]);
$taskName = $this->loadAppModuleTask($moduleName, $taskName);
} else {
$taskName = ucfirst($task[1]);
}
return $taskName;
} | [
"private",
"function",
"loadAppTask",
"(",
"array",
"$",
"task",
")",
"{",
"//if task name contains more than 2 parts then it comes from module",
"if",
"(",
"count",
"(",
"$",
"task",
")",
">",
"2",
")",
"{",
"$",
"moduleName",
"=",
"ucfirst",
"(",
"$",
"task",
... | Loads task from application directory
@param array $task
@return string
@internal | [
"Loads",
"task",
"from",
"application",
"directory"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Loader.php#L137-L149 | train |
vegas-cmf/core | src/Cli/Loader.php | Loader.loadAppModuleTask | private function loadAppModuleTask($moduleName, $taskName)
{
$modules = $this->consoleApp->getModules();
//checks if indicated module has been registered
if (!isset($modules[$moduleName])) {
throw new TaskNotFoundException();
}
//creates full namespace for task class placed in application module
$fullNamespace = strtr('\:moduleName\Tasks\:taskName', array(
':moduleName' => $moduleName,
':taskName' => $taskName
));
//registers task class in Class Loader
$this->registerClass($fullNamespace . 'Task');
//returns converted name of task (namespace of class containing task)
return $fullNamespace;
} | php | private function loadAppModuleTask($moduleName, $taskName)
{
$modules = $this->consoleApp->getModules();
//checks if indicated module has been registered
if (!isset($modules[$moduleName])) {
throw new TaskNotFoundException();
}
//creates full namespace for task class placed in application module
$fullNamespace = strtr('\:moduleName\Tasks\:taskName', array(
':moduleName' => $moduleName,
':taskName' => $taskName
));
//registers task class in Class Loader
$this->registerClass($fullNamespace . 'Task');
//returns converted name of task (namespace of class containing task)
return $fullNamespace;
} | [
"private",
"function",
"loadAppModuleTask",
"(",
"$",
"moduleName",
",",
"$",
"taskName",
")",
"{",
"$",
"modules",
"=",
"$",
"this",
"->",
"consoleApp",
"->",
"getModules",
"(",
")",
";",
"//checks if indicated module has been registered",
"if",
"(",
"!",
"isse... | Loads task from specified application module
@param $moduleName
@param $taskName
@return string
@throws Exception\TaskNotFoundException
@internal | [
"Loads",
"task",
"from",
"specified",
"application",
"module"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Loader.php#L160-L179 | train |
vegas-cmf/core | src/Cli/Loader.php | Loader.loadCoreTask | private function loadCoreTask(array $task)
{
//creates full namespace for task placed in Vegas library
if (count($task) == 3) {
$namespace = $this->toNamespace($task[1]);
$taskName = ucfirst($task[2]);
} else {
//for \Vegas namespace tasks are placed in \Vegas\Task namespace
$namespace = '';
$taskName = ucfirst($task[1]);
}
$fullNamespace = strtr('\Vegas\:namespaceTask\\:taskName', array(
':namespace' => $namespace,
':taskName' => $taskName
));
//registers task class in Class Loader
$this->registerClass($fullNamespace . 'Task');
//returns converted name of task (namespace of class containing task)
return $fullNamespace;
} | php | private function loadCoreTask(array $task)
{
//creates full namespace for task placed in Vegas library
if (count($task) == 3) {
$namespace = $this->toNamespace($task[1]);
$taskName = ucfirst($task[2]);
} else {
//for \Vegas namespace tasks are placed in \Vegas\Task namespace
$namespace = '';
$taskName = ucfirst($task[1]);
}
$fullNamespace = strtr('\Vegas\:namespaceTask\\:taskName', array(
':namespace' => $namespace,
':taskName' => $taskName
));
//registers task class in Class Loader
$this->registerClass($fullNamespace . 'Task');
//returns converted name of task (namespace of class containing task)
return $fullNamespace;
} | [
"private",
"function",
"loadCoreTask",
"(",
"array",
"$",
"task",
")",
"{",
"//creates full namespace for task placed in Vegas library",
"if",
"(",
"count",
"(",
"$",
"task",
")",
"==",
"3",
")",
"{",
"$",
"namespace",
"=",
"$",
"this",
"->",
"toNamespace",
"(... | Loads task from Vegas libraries, mostly placed in vendor
@param array $task
@return string
@internal | [
"Loads",
"task",
"from",
"Vegas",
"libraries",
"mostly",
"placed",
"in",
"vendor"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/Loader.php#L188-L209 | train |
A-Lawrence/laravel-ipboard | src/Endpoints/Forums/Topics.php | Topics.createForumTopic | public function createForumTopic($forumID, $authorID, $title, $post, $extra = [])
{
$data = ["forum" => $forumID, "author" => $authorID, "title" => $title, "post" => $post];
$data = array_merge($data, $extra);
$validator = \Validator::make($data, [
"forum" => "required|numeric",
"author" => "required|numeric",
"title" => "required|string",
"post" => "required|string",
"author_name" => "required_if:author,0|string",
"prefix" => "string",
"tags" => "string|is_csv_alphanumeric",
"date" => "date_format:YYYY-mm-dd H:i:s",
"ip_address" => "ip",
"locked" => "in:0,1",
"open_time" => "date_format:YYYY-mm-dd H:i:s",
"close_time" => "date_format:YYYY-mm-dd H:i:s",
"hidden" => "in:-1,0,1",
"pinned" => "in:0,1",
"featured" => "in:0,1",
], [
"is_csv_alphanumeric" => "The :attribute must be a comma separated string.",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/topics", $data);
} | php | public function createForumTopic($forumID, $authorID, $title, $post, $extra = [])
{
$data = ["forum" => $forumID, "author" => $authorID, "title" => $title, "post" => $post];
$data = array_merge($data, $extra);
$validator = \Validator::make($data, [
"forum" => "required|numeric",
"author" => "required|numeric",
"title" => "required|string",
"post" => "required|string",
"author_name" => "required_if:author,0|string",
"prefix" => "string",
"tags" => "string|is_csv_alphanumeric",
"date" => "date_format:YYYY-mm-dd H:i:s",
"ip_address" => "ip",
"locked" => "in:0,1",
"open_time" => "date_format:YYYY-mm-dd H:i:s",
"close_time" => "date_format:YYYY-mm-dd H:i:s",
"hidden" => "in:-1,0,1",
"pinned" => "in:0,1",
"featured" => "in:0,1",
], [
"is_csv_alphanumeric" => "The :attribute must be a comma separated string.",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/topics", $data);
} | [
"public",
"function",
"createForumTopic",
"(",
"$",
"forumID",
",",
"$",
"authorID",
",",
"$",
"title",
",",
"$",
"post",
",",
"$",
"extra",
"=",
"[",
"]",
")",
"{",
"$",
"data",
"=",
"[",
"\"forum\"",
"=>",
"$",
"forumID",
",",
"\"author\"",
"=>",
... | Create a forum topic with the given data.
@param $forumID
@param integer $authorID The ID of the author for the topic (if set to 0, author_name is used)
@param string $title The title of the topic.
@param string $post The HTML content of the post.
@param array $extra
@return mixed
@throws Exceptions\InvalidFormat
@throws Exceptions\IpboardMemberEmailExists
@throws Exceptions\IpboardMemberInvalidGroup
@throws Exceptions\IpboardMemberUsernameExists
@throws IpboardInvalidApiKey
@throws IpboardMemberIdInvalid
@throws IpboardThrottled
@throws \Exception | [
"Create",
"a",
"forum",
"topic",
"with",
"the",
"given",
"data",
"."
] | f9a00c3aaf58811583829484fe51c5363c8208e5 | https://github.com/A-Lawrence/laravel-ipboard/blob/f9a00c3aaf58811583829484fe51c5363c8208e5/src/Endpoints/Forums/Topics.php#L152-L183 | train |
A-Lawrence/laravel-ipboard | src/Endpoints/Forums/Topics.php | Topics.updateForumTopic | public function updateForumTopic($topicID, $data = [])
{
$validator = \Validator::make($data, [
"forum" => "numeric",
"author" => "numeric",
"author_name" => "required_if:author,0|string",
"title" => "string",
"post" => "string",
"prefix" => "string",
"tags" => "string|is_csv_alphanumeric",
"date" => "date_format:YYYY-mm-dd H:i:s",
"ip_address" => "ip",
"locked" => "in:0,1",
"open_time" => "date_format:YYYY-mm-dd H:i:s",
"close_time" => "date_format:YYYY-mm-dd H:i:s",
"hidden" => "in:-1,0,1",
"pinned" => "in:0,1",
"featured" => "in:0,1",
], [
"is_csv_alphanumeric" => "The :attribute must be a comma separated string.",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/topics/" . $topicID, $data);
} | php | public function updateForumTopic($topicID, $data = [])
{
$validator = \Validator::make($data, [
"forum" => "numeric",
"author" => "numeric",
"author_name" => "required_if:author,0|string",
"title" => "string",
"post" => "string",
"prefix" => "string",
"tags" => "string|is_csv_alphanumeric",
"date" => "date_format:YYYY-mm-dd H:i:s",
"ip_address" => "ip",
"locked" => "in:0,1",
"open_time" => "date_format:YYYY-mm-dd H:i:s",
"close_time" => "date_format:YYYY-mm-dd H:i:s",
"hidden" => "in:-1,0,1",
"pinned" => "in:0,1",
"featured" => "in:0,1",
], [
"is_csv_alphanumeric" => "The :attribute must be a comma separated string.",
]);
if ($validator->fails()) {
$message = head(array_flatten($validator->messages()));
throw new Exceptions\InvalidFormat($message);
}
return $this->postRequest("forums/topics/" . $topicID, $data);
} | [
"public",
"function",
"updateForumTopic",
"(",
"$",
"topicID",
",",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"$",
"validator",
"=",
"\\",
"Validator",
"::",
"make",
"(",
"$",
"data",
",",
"[",
"\"forum\"",
"=>",
"\"numeric\"",
",",
"\"author\"",
"=>",
"\"... | Update a forum topic with the given ID.
@param integer $topicID The ID of the topic to update.
@param array $data The data to edit.
@return mixed
@throws Exceptions\InvalidFormat
@throws Exceptions\IpboardMemberEmailExists
@throws Exceptions\IpboardMemberInvalidGroup
@throws Exceptions\IpboardMemberUsernameExists
@throws IpboardInvalidApiKey
@throws IpboardMemberIdInvalid
@throws IpboardThrottled
@throws \Exception | [
"Update",
"a",
"forum",
"topic",
"with",
"the",
"given",
"ID",
"."
] | f9a00c3aaf58811583829484fe51c5363c8208e5 | https://github.com/A-Lawrence/laravel-ipboard/blob/f9a00c3aaf58811583829484fe51c5363c8208e5/src/Endpoints/Forums/Topics.php#L201-L229 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.beforeExecuteRoute | public function beforeExecuteRoute()
{
//sets active task and action names
$this->actionName = $this->dispatcher->getActionName();
$this->taskName = $this->dispatcher->getTaskName();
$this->setupOptions();
//if -h or --help option was typed in command line then show only help
$this->args = $this->dispatcher->getParam('args');
if ($this->containHelpOption($this->args)) {
$this->renderActionHelp();
//stop dispatching
return false;
}
try {
$this->validate($this->args);
} catch (InvalidArgumentException $ex) {
$this->throwError(strtr(':command: Invalid argument `:argument` for option `:option`', [
':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')),
':option' => $ex->getOption(),
':argument' => $ex->getArgument()
]));
} catch (InvalidOptionException $ex) {
$this->throwError(strtr(':command: Invalid option `:option`', [
':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')),
':option' => $ex->getOption()
]));
}
return true;
} | php | public function beforeExecuteRoute()
{
//sets active task and action names
$this->actionName = $this->dispatcher->getActionName();
$this->taskName = $this->dispatcher->getTaskName();
$this->setupOptions();
//if -h or --help option was typed in command line then show only help
$this->args = $this->dispatcher->getParam('args');
if ($this->containHelpOption($this->args)) {
$this->renderActionHelp();
//stop dispatching
return false;
}
try {
$this->validate($this->args);
} catch (InvalidArgumentException $ex) {
$this->throwError(strtr(':command: Invalid argument `:argument` for option `:option`', [
':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')),
':option' => $ex->getOption(),
':argument' => $ex->getArgument()
]));
} catch (InvalidOptionException $ex) {
$this->throwError(strtr(':command: Invalid option `:option`', [
':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')),
':option' => $ex->getOption()
]));
}
return true;
} | [
"public",
"function",
"beforeExecuteRoute",
"(",
")",
"{",
"//sets active task and action names",
"$",
"this",
"->",
"actionName",
"=",
"$",
"this",
"->",
"dispatcher",
"->",
"getActionName",
"(",
")",
";",
"$",
"this",
"->",
"taskName",
"=",
"$",
"this",
"->"... | Sets available actions with options
Validates command line arguments and options for command
Stops dispatching when detects help option
@see http://docs.phalconphp.com/pl/latest/reference/dispatching.html
@return bool | [
"Sets",
"available",
"actions",
"with",
"options",
"Validates",
"command",
"line",
"arguments",
"and",
"options",
"for",
"command",
"Stops",
"dispatching",
"when",
"detects",
"help",
"option"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L89-L120 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.containHelpOption | private function containHelpOption($args)
{
return array_key_exists(self::HELP_OPTION, $args)
|| array_key_exists(self::HELP_SHORTOPTION, $args);
} | php | private function containHelpOption($args)
{
return array_key_exists(self::HELP_OPTION, $args)
|| array_key_exists(self::HELP_SHORTOPTION, $args);
} | [
"private",
"function",
"containHelpOption",
"(",
"$",
"args",
")",
"{",
"return",
"array_key_exists",
"(",
"self",
"::",
"HELP_OPTION",
",",
"$",
"args",
")",
"||",
"array_key_exists",
"(",
"self",
"::",
"HELP_SHORTOPTION",
",",
"$",
"args",
")",
";",
"}"
] | Determines if help option was typed in command line
@param $args
@return bool | [
"Determines",
"if",
"help",
"option",
"was",
"typed",
"in",
"command",
"line"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L136-L140 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.getOption | protected function getOption($name, $default = null)
{
$matchedOption = null;
foreach ($this->actions[$this->actionName]->getOptions() as $option) {
if ($option->matchParam($name)) {
$matchedOption = $option;
}
}
$value = $matchedOption->getValue($this->args, $default);
return $value;
} | php | protected function getOption($name, $default = null)
{
$matchedOption = null;
foreach ($this->actions[$this->actionName]->getOptions() as $option) {
if ($option->matchParam($name)) {
$matchedOption = $option;
}
}
$value = $matchedOption->getValue($this->args, $default);
return $value;
} | [
"protected",
"function",
"getOption",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"matchedOption",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"actions",
"[",
"$",
"this",
"->",
"actionName",
"]",
"->",
"getOptions",
"("... | Get option value for action from command line
@param $name
@param null $default
@throws MissingRequiredArgumentException
@return mixed | [
"Get",
"option",
"value",
"for",
"action",
"from",
"command",
"line"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L188-L199 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.renderActionHelp | protected function renderActionHelp()
{
$action = $this->actions[$this->actionName];
//puts name of action
$this->appendLine($this->getColoredString($action->getDescription(), 'green'));
$this->appendLine('');
//puts usage hint
$this->appendLine('Usage:');
$this->appendLine($this->getColoredString(sprintf(
' %s %s [options]',
$this->dispatcher->getParam('activeTask'),
$this->dispatcher->getParam('activeAction')
), 'dark_gray'));
$this->appendLine('');
//puts available options
$this->appendLine($this->getColoredString('Options:', 'gray'));
foreach ($action->getOptions() as $option) {
$this->appendLine($this->getColoredString(sprintf(
' --%s -%s %s',
$option->getName(), $option->getShortName(), $option->getDescription()
), 'light_green'));
}
} | php | protected function renderActionHelp()
{
$action = $this->actions[$this->actionName];
//puts name of action
$this->appendLine($this->getColoredString($action->getDescription(), 'green'));
$this->appendLine('');
//puts usage hint
$this->appendLine('Usage:');
$this->appendLine($this->getColoredString(sprintf(
' %s %s [options]',
$this->dispatcher->getParam('activeTask'),
$this->dispatcher->getParam('activeAction')
), 'dark_gray'));
$this->appendLine('');
//puts available options
$this->appendLine($this->getColoredString('Options:', 'gray'));
foreach ($action->getOptions() as $option) {
$this->appendLine($this->getColoredString(sprintf(
' --%s -%s %s',
$option->getName(), $option->getShortName(), $option->getDescription()
), 'light_green'));
}
} | [
"protected",
"function",
"renderActionHelp",
"(",
")",
"{",
"$",
"action",
"=",
"$",
"this",
"->",
"actions",
"[",
"$",
"this",
"->",
"actionName",
"]",
";",
"//puts name of action",
"$",
"this",
"->",
"appendLine",
"(",
"$",
"this",
"->",
"getColoredString"... | Renders help for task action | [
"Renders",
"help",
"for",
"task",
"action"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L298-L322 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.renderTaskHelp | protected function renderTaskHelp()
{
$this->appendLine($this->getColoredString('Available actions', 'dark_gray'));
$this->appendLine(PHP_EOL);
foreach ($this->actions as $action) {
$this->appendLine(sprintf(
' %s %s',
$this->getColoredString($action->getName(), 'light_green'),
$this->getColoredString($action->getDescription(), 'green'))
);
}
} | php | protected function renderTaskHelp()
{
$this->appendLine($this->getColoredString('Available actions', 'dark_gray'));
$this->appendLine(PHP_EOL);
foreach ($this->actions as $action) {
$this->appendLine(sprintf(
' %s %s',
$this->getColoredString($action->getName(), 'light_green'),
$this->getColoredString($action->getDescription(), 'green'))
);
}
} | [
"protected",
"function",
"renderTaskHelp",
"(",
")",
"{",
"$",
"this",
"->",
"appendLine",
"(",
"$",
"this",
"->",
"getColoredString",
"(",
"'Available actions'",
",",
"'dark_gray'",
")",
")",
";",
"$",
"this",
"->",
"appendLine",
"(",
"PHP_EOL",
")",
";",
... | Renders help for task | [
"Renders",
"help",
"for",
"task"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L327-L338 | train |
vegas-cmf/core | src/Cli/TaskAbstract.php | TaskAbstract.validate | protected function validate()
{
$args = $this->dispatcher->getParam('args');
if (isset($this->actions[$this->actionName])) {
$action = $this->actions[$this->actionName];
$action->validate($args);
}
} | php | protected function validate()
{
$args = $this->dispatcher->getParam('args');
if (isset($this->actions[$this->actionName])) {
$action = $this->actions[$this->actionName];
$action->validate($args);
}
} | [
"protected",
"function",
"validate",
"(",
")",
"{",
"$",
"args",
"=",
"$",
"this",
"->",
"dispatcher",
"->",
"getParam",
"(",
"'args'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"actions",
"[",
"$",
"this",
"->",
"actionName",
"]",
")",
... | Validates action options | [
"Validates",
"action",
"options"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Cli/TaskAbstract.php#L343-L350 | train |
czim/laravel-cms-auth | src/Http/Controllers/AuthController.php | AuthController.storeIntendedUrl | protected function storeIntendedUrl()
{
// Do not store the URL if it was the login itself
$previousUrl = url()->previous();
$loginUrl = url()->route($this->core->prefixRoute(NamedRoute::AUTH_LOGIN));
if ($previousUrl == $loginUrl) return;
session()->put('url.intended', $previousUrl);
} | php | protected function storeIntendedUrl()
{
// Do not store the URL if it was the login itself
$previousUrl = url()->previous();
$loginUrl = url()->route($this->core->prefixRoute(NamedRoute::AUTH_LOGIN));
if ($previousUrl == $loginUrl) return;
session()->put('url.intended', $previousUrl);
} | [
"protected",
"function",
"storeIntendedUrl",
"(",
")",
"{",
"// Do not store the URL if it was the login itself",
"$",
"previousUrl",
"=",
"url",
"(",
")",
"->",
"previous",
"(",
")",
";",
"$",
"loginUrl",
"=",
"url",
"(",
")",
"->",
"route",
"(",
"$",
"this",... | Stores the intended URL to redirect to after succesful login. | [
"Stores",
"the",
"intended",
"URL",
"to",
"redirect",
"to",
"after",
"succesful",
"login",
"."
] | dbd7fecc69e891f8befdd6039244037a42c4b10f | https://github.com/czim/laravel-cms-auth/blob/dbd7fecc69e891f8befdd6039244037a42c4b10f/src/Http/Controllers/AuthController.php#L87-L96 | train |
moon-php/moon | src/Matchable/MatchableRequest.php | MatchableRequest.toRegex | private function toRegex(string $pattern): string
{
while (\preg_match(self::OPTIONAL_PLACEHOLDER_REGEX, $pattern)) {
$pattern = \preg_replace(self::OPTIONAL_PLACEHOLDER_REGEX, '($1)?', $pattern);
}
$pattern = \preg_replace_callback(self::REQUIRED_PLACEHOLDER_REGEX, function (array $match = []) {
$match = \array_pop($match);
$pos = \mb_strpos($match, self::REGEX_PREFIX);
if (false !== $pos) {
$parameterName = \mb_substr($match, 0, $pos);
$parameterRegex = \mb_substr($match, $pos + 2);
return "(?<$parameterName>$parameterRegex)";
}
return "(?<$match>[^/]+)";
}, $pattern);
return $pattern;
} | php | private function toRegex(string $pattern): string
{
while (\preg_match(self::OPTIONAL_PLACEHOLDER_REGEX, $pattern)) {
$pattern = \preg_replace(self::OPTIONAL_PLACEHOLDER_REGEX, '($1)?', $pattern);
}
$pattern = \preg_replace_callback(self::REQUIRED_PLACEHOLDER_REGEX, function (array $match = []) {
$match = \array_pop($match);
$pos = \mb_strpos($match, self::REGEX_PREFIX);
if (false !== $pos) {
$parameterName = \mb_substr($match, 0, $pos);
$parameterRegex = \mb_substr($match, $pos + 2);
return "(?<$parameterName>$parameterRegex)";
}
return "(?<$match>[^/]+)";
}, $pattern);
return $pattern;
} | [
"private",
"function",
"toRegex",
"(",
"string",
"$",
"pattern",
")",
":",
"string",
"{",
"while",
"(",
"\\",
"preg_match",
"(",
"self",
"::",
"OPTIONAL_PLACEHOLDER_REGEX",
",",
"$",
"pattern",
")",
")",
"{",
"$",
"pattern",
"=",
"\\",
"preg_replace",
"(",... | Transform a pattern into a regex. | [
"Transform",
"a",
"pattern",
"into",
"a",
"regex",
"."
] | 25a6be494b829528f6181f544a21cda95d1226a2 | https://github.com/moon-php/moon/blob/25a6be494b829528f6181f544a21cda95d1226a2/src/Matchable/MatchableRequest.php#L98-L118 | train |
softberg/quantum-core | src/Routes/Route.php | Route.add | public function add($uri, $method, $controller, $action) {
$this->currentRoute = [
'uri' => $uri,
'method' => $method,
'controller' => $controller,
'action' => $action,
'module' => $this->module,
];
if ($this->currentGroupName) {
$this->virtualRoutes[$this->currentGroupName][] = $this->currentRoute;
} else {
$this->virtualRoutes['*'][] = $this->currentRoute;
}
return $this;
} | php | public function add($uri, $method, $controller, $action) {
$this->currentRoute = [
'uri' => $uri,
'method' => $method,
'controller' => $controller,
'action' => $action,
'module' => $this->module,
];
if ($this->currentGroupName) {
$this->virtualRoutes[$this->currentGroupName][] = $this->currentRoute;
} else {
$this->virtualRoutes['*'][] = $this->currentRoute;
}
return $this;
} | [
"public",
"function",
"add",
"(",
"$",
"uri",
",",
"$",
"method",
",",
"$",
"controller",
",",
"$",
"action",
")",
"{",
"$",
"this",
"->",
"currentRoute",
"=",
"[",
"'uri'",
"=>",
"$",
"uri",
",",
"'method'",
"=>",
"$",
"method",
",",
"'controller'",... | Adds new route entry to routes
@param string $uri
@param string $method
@param string $controller
@param string $action
@param array $middlewares
@return $this | [
"Adds",
"new",
"route",
"entry",
"to",
"routes"
] | 081d42a4ce4197ac8687d438c571914473ade9da | https://github.com/softberg/quantum-core/blob/081d42a4ce4197ac8687d438c571914473ade9da/src/Routes/Route.php#L94-L110 | train |
softberg/quantum-core | src/Routes/Route.php | Route.group | public function group(string $groupName, \Closure $callback) {
$this->currentGroupName = $groupName;
$this->isGroupe = TRUE;
$this->isGroupeMiddlewares = FALSE;
$callback($this);
$this->isGroupeMiddlewares = TRUE;
$this->currentGroupName = NULL;
return $this;
} | php | public function group(string $groupName, \Closure $callback) {
$this->currentGroupName = $groupName;
$this->isGroupe = TRUE;
$this->isGroupeMiddlewares = FALSE;
$callback($this);
$this->isGroupeMiddlewares = TRUE;
$this->currentGroupName = NULL;
return $this;
} | [
"public",
"function",
"group",
"(",
"string",
"$",
"groupName",
",",
"\\",
"Closure",
"$",
"callback",
")",
"{",
"$",
"this",
"->",
"currentGroupName",
"=",
"$",
"groupName",
";",
"$",
"this",
"->",
"isGroupe",
"=",
"TRUE",
";",
"$",
"this",
"->",
"isG... | Starts a named group of routes
@param string $groupName
@param \Closure $callback
@return $this | [
"Starts",
"a",
"named",
"group",
"of",
"routes"
] | 081d42a4ce4197ac8687d438c571914473ade9da | https://github.com/softberg/quantum-core/blob/081d42a4ce4197ac8687d438c571914473ade9da/src/Routes/Route.php#L119-L129 | train |
softberg/quantum-core | src/Routes/Route.php | Route.middlewares | public function middlewares(array $middlewares = []) {
if (!$this->isGroupe) {
end($this->virtualRoutes['*']);
$lastKey = key($this->virtualRoutes['*']);
$this->virtualRoutes['*'][$lastKey]['middlewares'] = $middlewares;
} else {
end($this->virtualRoutes);
$lastKeyOfFirstRound = key($this->virtualRoutes);
if (!$this->isGroupeMiddlewares) {
end($this->virtualRoutes[$lastKeyOfFirstRound]);
$lastKeyOfSecondRound = key($this->virtualRoutes[$lastKeyOfFirstRound]);
$this->virtualRoutes[$lastKeyOfFirstRound][$lastKeyOfSecondRound]['middlewares'] = $middlewares;
} else {
$this->isGroupe = FALSE;
foreach ($this->virtualRoutes[$lastKeyOfFirstRound] as &$route) {
$hasMiddleware = end($route);
if (!is_array($hasMiddleware)) {
$route['middlewares'] = $middlewares;
} else {
foreach ($middlewares as $middleware) {
$route['middlewares'][] = $middleware;
}
}
}
}
}
} | php | public function middlewares(array $middlewares = []) {
if (!$this->isGroupe) {
end($this->virtualRoutes['*']);
$lastKey = key($this->virtualRoutes['*']);
$this->virtualRoutes['*'][$lastKey]['middlewares'] = $middlewares;
} else {
end($this->virtualRoutes);
$lastKeyOfFirstRound = key($this->virtualRoutes);
if (!$this->isGroupeMiddlewares) {
end($this->virtualRoutes[$lastKeyOfFirstRound]);
$lastKeyOfSecondRound = key($this->virtualRoutes[$lastKeyOfFirstRound]);
$this->virtualRoutes[$lastKeyOfFirstRound][$lastKeyOfSecondRound]['middlewares'] = $middlewares;
} else {
$this->isGroupe = FALSE;
foreach ($this->virtualRoutes[$lastKeyOfFirstRound] as &$route) {
$hasMiddleware = end($route);
if (!is_array($hasMiddleware)) {
$route['middlewares'] = $middlewares;
} else {
foreach ($middlewares as $middleware) {
$route['middlewares'][] = $middleware;
}
}
}
}
}
} | [
"public",
"function",
"middlewares",
"(",
"array",
"$",
"middlewares",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isGroupe",
")",
"{",
"end",
"(",
"$",
"this",
"->",
"virtualRoutes",
"[",
"'*'",
"]",
")",
";",
"$",
"lastKey",
"=",... | Adds middlewares to routes and route groups
@param array $middlewares
@return void | [
"Adds",
"middlewares",
"to",
"routes",
"and",
"route",
"groups"
] | 081d42a4ce4197ac8687d438c571914473ade9da | https://github.com/softberg/quantum-core/blob/081d42a4ce4197ac8687d438c571914473ade9da/src/Routes/Route.php#L137-L165 | train |
softberg/quantum-core | src/Routes/Route.php | Route.getRuntimeRoutes | public function getRuntimeRoutes() {
$runtimeRoutes = [];
foreach ($this->virtualRoutes as $virtualRoute) {
foreach ($virtualRoute as $route) {
$runtimeRoutes[] = $route;
}
}
return $runtimeRoutes;
} | php | public function getRuntimeRoutes() {
$runtimeRoutes = [];
foreach ($this->virtualRoutes as $virtualRoute) {
foreach ($virtualRoute as $route) {
$runtimeRoutes[] = $route;
}
}
return $runtimeRoutes;
} | [
"public",
"function",
"getRuntimeRoutes",
"(",
")",
"{",
"$",
"runtimeRoutes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"virtualRoutes",
"as",
"$",
"virtualRoute",
")",
"{",
"foreach",
"(",
"$",
"virtualRoute",
"as",
"$",
"route",
")",
"{",... | Gets the runtime routes
@return array | [
"Gets",
"the",
"runtime",
"routes"
] | 081d42a4ce4197ac8687d438c571914473ade9da | https://github.com/softberg/quantum-core/blob/081d42a4ce4197ac8687d438c571914473ade9da/src/Routes/Route.php#L172-L181 | train |
A-Lawrence/laravel-ipboard | src/Ipboard.php | Ipboard.request | private function request($method, $function, $extra = [])
{
$response = null;
try {
$response = $this->httpRequest->{$method}($function, $extra)->getBody();
return json_decode($response, false);
} catch (ClientException $e) {
$this->handleError($e->getResponse());
}
} | php | private function request($method, $function, $extra = [])
{
$response = null;
try {
$response = $this->httpRequest->{$method}($function, $extra)->getBody();
return json_decode($response, false);
} catch (ClientException $e) {
$this->handleError($e->getResponse());
}
} | [
"private",
"function",
"request",
"(",
"$",
"method",
",",
"$",
"function",
",",
"$",
"extra",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"null",
";",
"try",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"httpRequest",
"->",
"{",
"$",
"method",... | Perform the specified request.
@param string $method Either GET, POST, PUT, DELETE, PATCH
@param string $function The endpoint to call.
@param array $extra Any query string information.
@return mixed
@throws Exceptions\IpboardInvalidApiKey
@throws Exceptions\IpboardMemberEmailExists
@throws Exceptions\IpboardMemberIdInvalid
@throws Exceptions\IpboardMemberInvalidGroup
@throws Exceptions\IpboardMemberUsernameExists
@throws Exceptions\IpboardThrottled
@throws \Exception | [
"Perform",
"the",
"specified",
"request",
"."
] | f9a00c3aaf58811583829484fe51c5363c8208e5 | https://github.com/A-Lawrence/laravel-ipboard/blob/f9a00c3aaf58811583829484fe51c5363c8208e5/src/Ipboard.php#L151-L161 | train |
A-Lawrence/laravel-ipboard | src/Ipboard.php | Ipboard.handleError | private function handleError($response)
{
$error = json_decode($response->getBody(), false);
$errorCode = $error->errorCode;
try {
if (array_key_exists($errorCode, $this->error_exceptions)) {
throw new $this->error_exceptions[$errorCode];
}
throw new $this->error_exceptions[$response->getStatusCode()];
} catch (Exception $e) {
throw new \Exception("There was a malformed response from IPBoard.");
}
} | php | private function handleError($response)
{
$error = json_decode($response->getBody(), false);
$errorCode = $error->errorCode;
try {
if (array_key_exists($errorCode, $this->error_exceptions)) {
throw new $this->error_exceptions[$errorCode];
}
throw new $this->error_exceptions[$response->getStatusCode()];
} catch (Exception $e) {
throw new \Exception("There was a malformed response from IPBoard.");
}
} | [
"private",
"function",
"handleError",
"(",
"$",
"response",
")",
"{",
"$",
"error",
"=",
"json_decode",
"(",
"$",
"response",
"->",
"getBody",
"(",
")",
",",
"false",
")",
";",
"$",
"errorCode",
"=",
"$",
"error",
"->",
"errorCode",
";",
"try",
"{",
... | Throw the error specific to the error code that has been returned.
All exceptions are dynamically thrown. Where an exception doesn't exist for an error code, \Exception is thrown.
@param ResponseInterface $response The IPBoard error code.
@throws \Exception
@throws \Alawrence\Ipboard\Exceptions\IpboardInvalidApiKey
@throws \Alawrence\Ipboard\Exceptions\IpboardThrottled
@throws \Alawrence\Ipboard\Exceptions\IpboardMemberIdInvalid
@throws \Alawrence\Ipboard\Exceptions\IpboardMemberInvalidGroup
@throws \Alawrence\Ipboard\Exceptions\IpboardMemberUsernameExists
@throws \Alawrence\Ipboard\Exceptions\IpboardMemberEmailExists | [
"Throw",
"the",
"error",
"specific",
"to",
"the",
"error",
"code",
"that",
"has",
"been",
"returned",
"."
] | f9a00c3aaf58811583829484fe51c5363c8208e5 | https://github.com/A-Lawrence/laravel-ipboard/blob/f9a00c3aaf58811583829484fe51c5363c8208e5/src/Ipboard.php#L178-L192 | train |
Kolyunya/codeception-markup-validator | sources/Module/MarkupValidator.php | MarkupValidator.validateMarkup | public function validateMarkup(array $messageFilterConfiguration = array())
{
$markup = $this->markupProvider->getMarkup();
$messages = $this->markupValidator->validate($markup);
$this->messageFilter->setConfiguration($messageFilterConfiguration);
$filteredMessages = $this->messageFilter->filterMessages($messages);
if (empty($filteredMessages) === false) {
$messagesString = $this->messagePrinter->getMessagesString($filteredMessages);
$this->fail($messagesString);
}
// Validation succeeded.
$this->assertTrue(true);
} | php | public function validateMarkup(array $messageFilterConfiguration = array())
{
$markup = $this->markupProvider->getMarkup();
$messages = $this->markupValidator->validate($markup);
$this->messageFilter->setConfiguration($messageFilterConfiguration);
$filteredMessages = $this->messageFilter->filterMessages($messages);
if (empty($filteredMessages) === false) {
$messagesString = $this->messagePrinter->getMessagesString($filteredMessages);
$this->fail($messagesString);
}
// Validation succeeded.
$this->assertTrue(true);
} | [
"public",
"function",
"validateMarkup",
"(",
"array",
"$",
"messageFilterConfiguration",
"=",
"array",
"(",
")",
")",
"{",
"$",
"markup",
"=",
"$",
"this",
"->",
"markupProvider",
"->",
"getMarkup",
"(",
")",
";",
"$",
"messages",
"=",
"$",
"this",
"->",
... | Validates page markup via a markup validator.
Allows to recongigure message filter component.
@param array $messageFilterConfiguration Message filter configuration. | [
"Validates",
"page",
"markup",
"via",
"a",
"markup",
"validator",
".",
"Allows",
"to",
"recongigure",
"message",
"filter",
"component",
"."
] | 89b5fa5e28602af7e7f2a8ee42686be697dd00a7 | https://github.com/Kolyunya/codeception-markup-validator/blob/89b5fa5e28602af7e7f2a8ee42686be697dd00a7/sources/Module/MarkupValidator.php#L97-L112 | train |
softberg/quantum-core | src/bootstrap.php | Bootstrap.run | public static function run() {
try {
$router = new Router();
(new ModuleLoader())->loadModules($router);
$router->findRoute();
Environment::load();
Config::load();
Helpers::load();
Libraries::load();
$mvcManager = new MvcManager();
$mvcManager->runMvc(Router::$currentRoute);
} catch (\Exception $e) {
echo $e->getMessage();
exit;
}
} | php | public static function run() {
try {
$router = new Router();
(new ModuleLoader())->loadModules($router);
$router->findRoute();
Environment::load();
Config::load();
Helpers::load();
Libraries::load();
$mvcManager = new MvcManager();
$mvcManager->runMvc(Router::$currentRoute);
} catch (\Exception $e) {
echo $e->getMessage();
exit;
}
} | [
"public",
"static",
"function",
"run",
"(",
")",
"{",
"try",
"{",
"$",
"router",
"=",
"new",
"Router",
"(",
")",
";",
"(",
"new",
"ModuleLoader",
"(",
")",
")",
"->",
"loadModules",
"(",
"$",
"router",
")",
";",
"$",
"router",
"->",
"findRoute",
"(... | Initializes the framework.
This method does not accept parameters and does not return anything.
It runs the router, prepare the config values, helpers, libraries and MVC Manager
@return void
@throws Exception if one of these components fails: Router, Config, Helpers, Libraries, MVC MAnager. | [
"Initializes",
"the",
"framework",
"."
] | 081d42a4ce4197ac8687d438c571914473ade9da | https://github.com/softberg/quantum-core/blob/081d42a4ce4197ac8687d438c571914473ade9da/src/bootstrap.php#L43-L62 | train |
lastzero/test-tools | src/Swift/Mailer.php | Mailer.getLastMessage | public function getLastMessage()
{
$filename = $this->getTempFilename();
if (file_exists($filename)) {
$result = unserialize(file_get_contents($filename));
} else {
throw new Swift_IoException('No last message found in "' . $filename . '" - did you call send()?');
}
return $result;
} | php | public function getLastMessage()
{
$filename = $this->getTempFilename();
if (file_exists($filename)) {
$result = unserialize(file_get_contents($filename));
} else {
throw new Swift_IoException('No last message found in "' . $filename . '" - did you call send()?');
}
return $result;
} | [
"public",
"function",
"getLastMessage",
"(",
")",
"{",
"$",
"filename",
"=",
"$",
"this",
"->",
"getTempFilename",
"(",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"filename",
")",
")",
"{",
"$",
"result",
"=",
"unserialize",
"(",
"file_get_contents",
... | Returns the last message sent
@throws Swift_IoException
@return Swift_Mime_Message | [
"Returns",
"the",
"last",
"message",
"sent"
] | 4f5f12e213060930e79c4e6cb9a48d422cd258ce | https://github.com/lastzero/test-tools/blob/4f5f12e213060930e79c4e6cb9a48d422cd258ce/src/Swift/Mailer.php#L60-L71 | train |
vegas-cmf/core | src/Paginator/Adapter/MongoAbstract.php | MongoAbstract.validate | private function validate()
{
if (empty($this->modelName) && empty($this->model)) {
throw new Exception\ModelNotSetException();
}
if (empty($this->model)) {
$this->model = new $this->modelName();
}
if (empty($this->modelName)) {
$this->modelName = get_class($this->model);
}
if (empty($this->db)) {
$this->db = $this->model->getConnection();
}
} | php | private function validate()
{
if (empty($this->modelName) && empty($this->model)) {
throw new Exception\ModelNotSetException();
}
if (empty($this->model)) {
$this->model = new $this->modelName();
}
if (empty($this->modelName)) {
$this->modelName = get_class($this->model);
}
if (empty($this->db)) {
$this->db = $this->model->getConnection();
}
} | [
"private",
"function",
"validate",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"modelName",
")",
"&&",
"empty",
"(",
"$",
"this",
"->",
"model",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"ModelNotSetException",
"(",
")",
";",
"... | Validates model and database
@throws Exception\ModelNotSetException
@internal | [
"Validates",
"model",
"and",
"database"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Paginator/Adapter/MongoAbstract.php#L90-L107 | train |
vegas-cmf/core | src/Paginator/Adapter/MongoAbstract.php | MongoAbstract.getTotalPages | public function getTotalPages()
{
if (empty($this->totalPages)) {
$this->totalPages = (int)ceil($this->getCursor()->count()/$this->limit);
}
return $this->totalPages;
} | php | public function getTotalPages()
{
if (empty($this->totalPages)) {
$this->totalPages = (int)ceil($this->getCursor()->count()/$this->limit);
}
return $this->totalPages;
} | [
"public",
"function",
"getTotalPages",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"totalPages",
")",
")",
"{",
"$",
"this",
"->",
"totalPages",
"=",
"(",
"int",
")",
"ceil",
"(",
"$",
"this",
"->",
"getCursor",
"(",
")",
"->",
"coun... | Returns number of pages
@return int | [
"Returns",
"number",
"of",
"pages"
] | 50fc3f31a6a8fc3cf274efd5b3eb3203d1206100 | https://github.com/vegas-cmf/core/blob/50fc3f31a6a8fc3cf274efd5b3eb3203d1206100/src/Paginator/Adapter/MongoAbstract.php#L142-L149 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.