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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.getParticipants | public function getParticipants($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/participants");
$participants = [];
foreach ($response as $team) {
$participant = new Participant($team->participant);
$participant->tournament_slug = $tournament;
$participants[] = $participant;
}
return $participants;
} | php | public function getParticipants($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/participants");
$participants = [];
foreach ($response as $team) {
$participant = new Participant($team->participant);
$participant->tournament_slug = $tournament;
$participants[] = $participant;
}
return $participants;
} | [
"public",
"function",
"getParticipants",
"(",
"$",
"tournament",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"get",
"(",
"\"tournaments/{$tournament}/participants\"",
")",
";",
"$",
"participants",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"response",
"as",... | Retrieve a tournament's participant list.
@param string $tournament
@return array | [
"Retrieve",
"a",
"tournament",
"s",
"participant",
"list",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L87-L99 | train |
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.randomizeParticipants | public function randomizeParticipants($tournament)
{
$response = Guzzle::post("tournaments/{$tournament}/participants/randomize");
$participants = [];
foreach ($response as $team) {
$participant = new Participant($team->participant);
$participant->tournament_slug = $tournament;
$participants[] = $participant;
}
return $participants;
} | php | public function randomizeParticipants($tournament)
{
$response = Guzzle::post("tournaments/{$tournament}/participants/randomize");
$participants = [];
foreach ($response as $team) {
$participant = new Participant($team->participant);
$participant->tournament_slug = $tournament;
$participants[] = $participant;
}
return $participants;
} | [
"public",
"function",
"randomizeParticipants",
"(",
"$",
"tournament",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"post",
"(",
"\"tournaments/{$tournament}/participants/randomize\"",
")",
";",
"$",
"participants",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"r... | Randomize seeds among participants.
@param string $tournament
@return array | [
"Randomize",
"seeds",
"among",
"participants",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L107-L119 | train |
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.getParticipant | public function getParticipant($tournament, $participant)
{
$response = Guzzle::get("tournaments/{$tournament}/participants/{$participant}");
$participant = new Participant($response->participant);
$participant->tournament_slug = $tournament;
return $participant;
} | php | public function getParticipant($tournament, $participant)
{
$response = Guzzle::get("tournaments/{$tournament}/participants/{$participant}");
$participant = new Participant($response->participant);
$participant->tournament_slug = $tournament;
return $participant;
} | [
"public",
"function",
"getParticipant",
"(",
"$",
"tournament",
",",
"$",
"participant",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"get",
"(",
"\"tournaments/{$tournament}/participants/{$participant}\"",
")",
";",
"$",
"participant",
"=",
"new",
"Participant",... | Retrieve a single participant record for a tournament.
@param string $tournament
@param string $participant
@return array | [
"Retrieve",
"a",
"single",
"participant",
"record",
"for",
"a",
"tournament",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L128-L136 | train |
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.getMatches | public function getMatches($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/matches");
$matches = [];
foreach ($response as $match) {
$matchModel = new Match($match->match);
$matchModel->tournament_slug = $tournament;
$matches[] = $matchModel;
}
return $matches;
} | php | public function getMatches($tournament)
{
$response = Guzzle::get("tournaments/{$tournament}/matches");
$matches = [];
foreach ($response as $match) {
$matchModel = new Match($match->match);
$matchModel->tournament_slug = $tournament;
$matches[] = $matchModel;
}
return $matches;
} | [
"public",
"function",
"getMatches",
"(",
"$",
"tournament",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"get",
"(",
"\"tournaments/{$tournament}/matches\"",
")",
";",
"$",
"matches",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"response",
"as",
"$",
"matc... | Retrieve a tournament's match list.
@param string $tournament
@return array | [
"Retrieve",
"a",
"tournament",
"s",
"match",
"list",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L144-L156 | train |
teamreflex/ChallongePHP | src/Challonge/Challonge.php | Challonge.getMatch | public function getMatch($tournament, $match)
{
$response = Guzzle::get("tournaments/{$tournament}/matches/{$match}");
$match = new Match($response->match);
$match->tournament_slug = $tournament;
return $match;
} | php | public function getMatch($tournament, $match)
{
$response = Guzzle::get("tournaments/{$tournament}/matches/{$match}");
$match = new Match($response->match);
$match->tournament_slug = $tournament;
return $match;
} | [
"public",
"function",
"getMatch",
"(",
"$",
"tournament",
",",
"$",
"match",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"get",
"(",
"\"tournaments/{$tournament}/matches/{$match}\"",
")",
";",
"$",
"match",
"=",
"new",
"Match",
"(",
"$",
"response",
"->"... | Retrieve a single match record for a tournament.
@param string $tournament
@param string $match
@return array | [
"Retrieve",
"a",
"single",
"match",
"record",
"for",
"a",
"tournament",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Challonge.php#L165-L173 | train |
symfony/locale | Stub/StubLocale.php | StubLocale.getCurrenciesData | public static function getCurrenciesData($locale)
{
if (null === self::$currencies) {
self::prepareCurrencies($locale);
}
return self::$currencies;
} | php | public static function getCurrenciesData($locale)
{
if (null === self::$currencies) {
self::prepareCurrencies($locale);
}
return self::$currencies;
} | [
"public",
"static",
"function",
"getCurrenciesData",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"null",
"===",
"self",
"::",
"$",
"currencies",
")",
"{",
"self",
"::",
"prepareCurrencies",
"(",
"$",
"locale",
")",
";",
"}",
"return",
"self",
"::",
"$",
"... | Returns the currencies data.
@param string $locale
@return array The currencies data | [
"Returns",
"the",
"currencies",
"data",
"."
] | c5e50d21e566cb685c1ee6802edadca643e8f83d | https://github.com/symfony/locale/blob/c5e50d21e566cb685c1ee6802edadca643e8f83d/Stub/StubLocale.php#L51-L58 | train |
symfony/locale | Stub/StubLocale.php | StubLocale.getDisplayCurrencies | public static function getDisplayCurrencies($locale)
{
if (null === self::$currenciesNames) {
self::prepareCurrencies($locale);
}
return self::$currenciesNames;
} | php | public static function getDisplayCurrencies($locale)
{
if (null === self::$currenciesNames) {
self::prepareCurrencies($locale);
}
return self::$currenciesNames;
} | [
"public",
"static",
"function",
"getDisplayCurrencies",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"null",
"===",
"self",
"::",
"$",
"currenciesNames",
")",
"{",
"self",
"::",
"prepareCurrencies",
"(",
"$",
"locale",
")",
";",
"}",
"return",
"self",
"::",
... | Returns the currencies names for a locale.
@param string $locale The locale to use for the currencies names
@return array The currencies names with their codes as keys
@throws \InvalidArgumentException When the locale is different than 'en' | [
"Returns",
"the",
"currencies",
"names",
"for",
"a",
"locale",
"."
] | c5e50d21e566cb685c1ee6802edadca643e8f83d | https://github.com/symfony/locale/blob/c5e50d21e566cb685c1ee6802edadca643e8f83d/Stub/StubLocale.php#L69-L76 | train |
bummzack/translatable-dataobject | code/extensions/TranslatedFile.php | TranslatedFile.updateCMSFields | public function updateCMSFields(FieldList $fields)
{
// only apply the update to files (not folders)
if ($this->owner->class != 'Folder') {
// add the tabs from the translatable tab set to the fields
/** @var TabSet $set */
$set = $this->owner->getTranslatableTabSet();
// Remove the tab of the default locale (these are in the "main" tab)
$set->removeByName(Translatable::default_locale());
foreach ($set->FieldList() as $tab) {
$fields->addFieldToTab('Root', $tab);
}
}
} | php | public function updateCMSFields(FieldList $fields)
{
// only apply the update to files (not folders)
if ($this->owner->class != 'Folder') {
// add the tabs from the translatable tab set to the fields
/** @var TabSet $set */
$set = $this->owner->getTranslatableTabSet();
// Remove the tab of the default locale (these are in the "main" tab)
$set->removeByName(Translatable::default_locale());
foreach ($set->FieldList() as $tab) {
$fields->addFieldToTab('Root', $tab);
}
}
} | [
"public",
"function",
"updateCMSFields",
"(",
"FieldList",
"$",
"fields",
")",
"{",
"// only apply the update to files (not folders)",
"if",
"(",
"$",
"this",
"->",
"owner",
"->",
"class",
"!=",
"'Folder'",
")",
"{",
"// add the tabs from the translatable tab set to the f... | Update the field values for the files & images section
@see DataExtension::updateCMSFields()
@inheritdoc | [
"Update",
"the",
"field",
"values",
"for",
"the",
"files",
"&",
"images",
"section"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatedFile.php#L98-L113 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.get_extra_config | public static function get_extra_config($class, $extension, $args)
{
if (!self::is_translatable_installed()) {
// remain silent during a test
if (SapphireTest::is_running_test()) {
return null;
}
// raise an error otherwise
user_error('Translatable module is not installed but required.', E_USER_WARNING);
return null;
}
if ($args) {
self::$arguments[$class] = $args;
}
return array(
'db' => self::collectDBFields($class),
'has_one' => self::collectHasOneRelations($class)
);
} | php | public static function get_extra_config($class, $extension, $args)
{
if (!self::is_translatable_installed()) {
// remain silent during a test
if (SapphireTest::is_running_test()) {
return null;
}
// raise an error otherwise
user_error('Translatable module is not installed but required.', E_USER_WARNING);
return null;
}
if ($args) {
self::$arguments[$class] = $args;
}
return array(
'db' => self::collectDBFields($class),
'has_one' => self::collectHasOneRelations($class)
);
} | [
"public",
"static",
"function",
"get_extra_config",
"(",
"$",
"class",
",",
"$",
"extension",
",",
"$",
"args",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"is_translatable_installed",
"(",
")",
")",
"{",
"// remain silent during a test",
"if",
"(",
"SapphireTest"... | Use table information and locales to dynamically build required table fields
@see DataExtension::get_extra_config()
@inheritdoc | [
"Use",
"table",
"information",
"and",
"locales",
"to",
"dynamically",
"build",
"required",
"table",
"fields"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L51-L71 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.updateCMSFields | public function updateCMSFields(FieldList $fields)
{
parent::updateCMSFields($fields);
if (!isset(self::$collectorCache[$this->owner->class])) {
return;
}
// remove all localized fields from the list (generated through scaffolding)
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
$fields->removeByName($translatableField);
}
// check if we're in a translation
if (Translatable::default_locale() != Translatable::get_current_locale()) {
/** @var TranslatableFormFieldTransformation $transformation */
$transformation = TranslatableFormFieldTransformation::create($this->owner);
// iterate through all localized fields
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
if (strpos($translatableField, Translatable::get_current_locale())) {
$basename = $this->getBasename($translatableField);
if ($field = $this->getLocalizedFormField($basename, Translatable::default_locale())) {
$fields->replaceField($basename, $transformation->transformFormField($field));
}
}
}
}
} | php | public function updateCMSFields(FieldList $fields)
{
parent::updateCMSFields($fields);
if (!isset(self::$collectorCache[$this->owner->class])) {
return;
}
// remove all localized fields from the list (generated through scaffolding)
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
$fields->removeByName($translatableField);
}
// check if we're in a translation
if (Translatable::default_locale() != Translatable::get_current_locale()) {
/** @var TranslatableFormFieldTransformation $transformation */
$transformation = TranslatableFormFieldTransformation::create($this->owner);
// iterate through all localized fields
foreach (self::$collectorCache[$this->owner->class] as $translatableField => $type) {
if (strpos($translatableField, Translatable::get_current_locale())) {
$basename = $this->getBasename($translatableField);
if ($field = $this->getLocalizedFormField($basename, Translatable::default_locale())) {
$fields->replaceField($basename, $transformation->transformFormField($field));
}
}
}
}
} | [
"public",
"function",
"updateCMSFields",
"(",
"FieldList",
"$",
"fields",
")",
"{",
"parent",
"::",
"updateCMSFields",
"(",
"$",
"fields",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"collectorCache",
"[",
"$",
"this",
"->",
"owner",
"->",... | Alter the CMS Fields in order to automatically present the
correct ones based on current language.
@inheritdoc | [
"Alter",
"the",
"CMS",
"Fields",
"in",
"order",
"to",
"automatically",
"present",
"the",
"correct",
"ones",
"based",
"on",
"current",
"language",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L88-L117 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.getLocalizedFormField | public function getLocalizedFormField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$fieldLabels = $this->owner->fieldLabels();
$localizedFieldName = self::localized_field($fieldName, $locale);
$fieldLabel = isset($fieldLabels[$baseName]) ? $fieldLabels[$baseName] : $baseName;
if (!$this->canTranslate(null, $locale)) {
// if not allowed to translate, return the field as Readonly
return ReadonlyField::create($localizedFieldName, $fieldLabel);
}
$dbFields = array();
Config::inst()->get($this->owner->class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $dbFields);
$type = isset($dbFields[$baseName]) ? $dbFields[$baseName] : '';
$typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type;
switch (strtolower($typeClean)) {
case 'varchar':
case 'htmlvarchar':
$field = TextField::create($localizedFieldName, $fieldLabel);
break;
case 'text':
$field = TextareaField::create($localizedFieldName, $fieldLabel);
break;
case 'htmltext':
default:
$field = HtmlEditorField::create($localizedFieldName, $fieldLabel);
break;
}
return $field;
} | php | public function getLocalizedFormField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$fieldLabels = $this->owner->fieldLabels();
$localizedFieldName = self::localized_field($fieldName, $locale);
$fieldLabel = isset($fieldLabels[$baseName]) ? $fieldLabels[$baseName] : $baseName;
if (!$this->canTranslate(null, $locale)) {
// if not allowed to translate, return the field as Readonly
return ReadonlyField::create($localizedFieldName, $fieldLabel);
}
$dbFields = array();
Config::inst()->get($this->owner->class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $dbFields);
$type = isset($dbFields[$baseName]) ? $dbFields[$baseName] : '';
$typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type;
switch (strtolower($typeClean)) {
case 'varchar':
case 'htmlvarchar':
$field = TextField::create($localizedFieldName, $fieldLabel);
break;
case 'text':
$field = TextareaField::create($localizedFieldName, $fieldLabel);
break;
case 'htmltext':
default:
$field = HtmlEditorField::create($localizedFieldName, $fieldLabel);
break;
}
return $field;
} | [
"public",
"function",
"getLocalizedFormField",
"(",
"$",
"fieldName",
",",
"$",
"locale",
")",
"{",
"$",
"baseName",
"=",
"$",
"this",
"->",
"getBasename",
"(",
"$",
"fieldName",
")",
";",
"$",
"fieldLabels",
"=",
"$",
"this",
"->",
"owner",
"->",
"field... | Get a form field for the given field name
@param string $fieldName
@param string $locale
@return FormField | [
"Get",
"a",
"form",
"field",
"for",
"the",
"given",
"field",
"name"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L205-L238 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.getLocalizedRelationField | public function getLocalizedRelationField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$localizedFieldName = self::localized_field($fieldName, $locale);
$field = null;
if ($field = $this->getFieldForRelation($fieldName)) {
$relationField = clone $field;
$relationField->setName($localizedFieldName);
return $relationField;
}
} | php | public function getLocalizedRelationField($fieldName, $locale)
{
$baseName = $this->getBasename($fieldName);
$localizedFieldName = self::localized_field($fieldName, $locale);
$field = null;
if ($field = $this->getFieldForRelation($fieldName)) {
$relationField = clone $field;
$relationField->setName($localizedFieldName);
return $relationField;
}
} | [
"public",
"function",
"getLocalizedRelationField",
"(",
"$",
"fieldName",
",",
"$",
"locale",
")",
"{",
"$",
"baseName",
"=",
"$",
"this",
"->",
"getBasename",
"(",
"$",
"fieldName",
")",
";",
"$",
"localizedFieldName",
"=",
"self",
"::",
"localized_field",
... | Get a form field for the given relation name
@todo default field for has_one?
@param string $fieldName
@param string $locale
@return FormField | [
"Get",
"a",
"form",
"field",
"for",
"the",
"given",
"relation",
"name"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L249-L262 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.updateFieldLabels | public function updateFieldLabels(&$labels)
{
parent::updateFieldLabels($labels);
$statics = self::$collectorCache[$this->ownerBaseClass];
foreach ($statics as $field => $type) {
$parts = explode(TRANSLATABLE_COLUMN_SEPARATOR, $field);
$labels[$field] = FormField::name_to_label($parts[0]) . ' (' . $parts[1] . ')';
}
} | php | public function updateFieldLabels(&$labels)
{
parent::updateFieldLabels($labels);
$statics = self::$collectorCache[$this->ownerBaseClass];
foreach ($statics as $field => $type) {
$parts = explode(TRANSLATABLE_COLUMN_SEPARATOR, $field);
$labels[$field] = FormField::name_to_label($parts[0]) . ' (' . $parts[1] . ')';
}
} | [
"public",
"function",
"updateFieldLabels",
"(",
"&",
"$",
"labels",
")",
"{",
"parent",
"::",
"updateFieldLabels",
"(",
"$",
"labels",
")",
";",
"$",
"statics",
"=",
"self",
"::",
"$",
"collectorCache",
"[",
"$",
"this",
"->",
"ownerBaseClass",
"]",
";",
... | Present translatable form fields in a more readable fashion
@see DataExtension::updateFieldLabels()
@inheritdoc | [
"Present",
"translatable",
"form",
"fields",
"in",
"a",
"more",
"readable",
"fashion"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L294-L303 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.isLocalizedField | public function isLocalizedField($fieldName)
{
$fields = self::get_localized_class_fields($this->ownerBaseClass);
return in_array($fieldName, $fields);
} | php | public function isLocalizedField($fieldName)
{
$fields = self::get_localized_class_fields($this->ownerBaseClass);
return in_array($fieldName, $fields);
} | [
"public",
"function",
"isLocalizedField",
"(",
"$",
"fieldName",
")",
"{",
"$",
"fields",
"=",
"self",
"::",
"get_localized_class_fields",
"(",
"$",
"this",
"->",
"ownerBaseClass",
")",
";",
"return",
"in_array",
"(",
"$",
"fieldName",
",",
"$",
"fields",
")... | Check if the given field name is a localized field
@param string $fieldName the name of the field without any locale extension. Eg. "Title"
@return bool whether or not the given field is localized | [
"Check",
"if",
"the",
"given",
"field",
"name",
"is",
"a",
"localized",
"field"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L310-L314 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.getLocalizedFieldName | public function getLocalizedFieldName($fieldName)
{
if ($this->isLocalizedField($fieldName) || $this->isLocalizedRelation($fieldName)) {
return self::localized_field($fieldName);
}
trigger_error("Field '$fieldName' is not a localized field", E_USER_ERROR);
} | php | public function getLocalizedFieldName($fieldName)
{
if ($this->isLocalizedField($fieldName) || $this->isLocalizedRelation($fieldName)) {
return self::localized_field($fieldName);
}
trigger_error("Field '$fieldName' is not a localized field", E_USER_ERROR);
} | [
"public",
"function",
"getLocalizedFieldName",
"(",
"$",
"fieldName",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isLocalizedField",
"(",
"$",
"fieldName",
")",
"||",
"$",
"this",
"->",
"isLocalizedRelation",
"(",
"$",
"fieldName",
")",
")",
"{",
"return",
"s... | Get the field name in the current reading locale
@param string $fieldName the name of the field without any locale extension. Eg. "Title"
@return null|string | [
"Get",
"the",
"field",
"name",
"in",
"the",
"current",
"reading",
"locale"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L321-L327 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.getLocalizedRelation | public function getLocalizedRelation($fieldName, $strict = true)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
if ($strict) {
return $this->owner->getRelation($localizedField);
}
// if not strict, check localized first and fallback to fieldname
if ($value = $this->owner->getRelation($localizedField)) {
return $value;
}
return $this->owner->getRelation($fieldName);
} | php | public function getLocalizedRelation($fieldName, $strict = true)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
if ($strict) {
return $this->owner->getRelation($localizedField);
}
// if not strict, check localized first and fallback to fieldname
if ($value = $this->owner->getRelation($localizedField)) {
return $value;
}
return $this->owner->getRelation($fieldName);
} | [
"public",
"function",
"getLocalizedRelation",
"(",
"$",
"fieldName",
",",
"$",
"strict",
"=",
"true",
")",
"{",
"$",
"localizedField",
"=",
"$",
"this",
"->",
"getLocalizedFieldName",
"(",
"$",
"fieldName",
")",
";",
"if",
"(",
"$",
"strict",
")",
"{",
"... | Get the localized object for a given relation.
@param string $fieldName the name of the field without any locale extension. Eg. "Title"
@param boolean $strict if false, this will fallback to the master version of the field! | [
"Get",
"the",
"localized",
"object",
"for",
"a",
"given",
"relation",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L344-L358 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.getLocalizedValue | public function getLocalizedValue($fieldName, $strict = true, $parseShortCodes = false)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
// ensure that $strict is a boolean value
$strict = filter_var($strict, FILTER_VALIDATE_BOOLEAN);
/** @var DBField $value */
$value = $this->owner->dbObject($localizedField);
if (!$strict && !$value->exists()) {
$value = $this->owner->dbObject($fieldName);
}
return ($parseShortCodes && $value) ? ShortcodeParser::get_active()->parse($value->getValue()) : $value;
} | php | public function getLocalizedValue($fieldName, $strict = true, $parseShortCodes = false)
{
$localizedField = $this->getLocalizedFieldName($fieldName);
// ensure that $strict is a boolean value
$strict = filter_var($strict, FILTER_VALIDATE_BOOLEAN);
/** @var DBField $value */
$value = $this->owner->dbObject($localizedField);
if (!$strict && !$value->exists()) {
$value = $this->owner->dbObject($fieldName);
}
return ($parseShortCodes && $value) ? ShortcodeParser::get_active()->parse($value->getValue()) : $value;
} | [
"public",
"function",
"getLocalizedValue",
"(",
"$",
"fieldName",
",",
"$",
"strict",
"=",
"true",
",",
"$",
"parseShortCodes",
"=",
"false",
")",
"{",
"$",
"localizedField",
"=",
"$",
"this",
"->",
"getLocalizedFieldName",
"(",
"$",
"fieldName",
")",
";",
... | Get the localized value for a given field.
@param string $fieldName the name of the field without any locale extension. Eg. "Title"
@param boolean $strict if false, this will fallback to the master version of the field!
@param boolean $parseShortCodes whether or not the value should be parsed with the shortcode parser
@return string|DBField | [
"Get",
"the",
"localized",
"value",
"for",
"a",
"given",
"field",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L367-L381 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.onBeforeWrite | public function onBeforeWrite()
{
if (!isset(self::$localizedFields[$this->ownerBaseClass])) {
return;
}
$fields = self::$localizedFields[$this->ownerBaseClass];
foreach ($fields as $field => $localized) {
foreach (self::get_target_locales() as $locale) {
$fieldName = self::localized_field($field, $locale);
if ($this->owner->isChanged($fieldName, 2) && !$this->canTranslate(null, $locale)) {
throw new PermissionFailureException(
"You're not allowed to edit the locale '$locale' for this object");
}
}
}
} | php | public function onBeforeWrite()
{
if (!isset(self::$localizedFields[$this->ownerBaseClass])) {
return;
}
$fields = self::$localizedFields[$this->ownerBaseClass];
foreach ($fields as $field => $localized) {
foreach (self::get_target_locales() as $locale) {
$fieldName = self::localized_field($field, $locale);
if ($this->owner->isChanged($fieldName, 2) && !$this->canTranslate(null, $locale)) {
throw new PermissionFailureException(
"You're not allowed to edit the locale '$locale' for this object");
}
}
}
} | [
"public",
"function",
"onBeforeWrite",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"localizedFields",
"[",
"$",
"this",
"->",
"ownerBaseClass",
"]",
")",
")",
"{",
"return",
";",
"}",
"$",
"fields",
"=",
"self",
"::",
"$",
"locali... | On before write hook.
Check if any translatable field has changed and if permissions are sufficient
@see DataExtension::onBeforeWrite() | [
"On",
"before",
"write",
"hook",
".",
"Check",
"if",
"any",
"translatable",
"field",
"has",
"changed",
"and",
"if",
"permissions",
"are",
"sufficient"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L434-L450 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.get_localized_class_fields | public static function get_localized_class_fields($class)
{
$fieldNames = null;
$ancestry = array_reverse(ClassInfo::ancestry($class));
foreach ($ancestry as $className) {
if (isset(self::$localizedFields[$className])) {
if ($fieldNames === null) {
$fieldNames = array();
}
foreach (self::$localizedFields[$className] as $k => $v) {
$fieldNames[] = $k;
}
}
}
return array_unique($fieldNames);
} | php | public static function get_localized_class_fields($class)
{
$fieldNames = null;
$ancestry = array_reverse(ClassInfo::ancestry($class));
foreach ($ancestry as $className) {
if (isset(self::$localizedFields[$className])) {
if ($fieldNames === null) {
$fieldNames = array();
}
foreach (self::$localizedFields[$className] as $k => $v) {
$fieldNames[] = $k;
}
}
}
return array_unique($fieldNames);
} | [
"public",
"static",
"function",
"get_localized_class_fields",
"(",
"$",
"class",
")",
"{",
"$",
"fieldNames",
"=",
"null",
";",
"$",
"ancestry",
"=",
"array_reverse",
"(",
"ClassInfo",
"::",
"ancestry",
"(",
"$",
"class",
")",
")",
";",
"foreach",
"(",
"$"... | Get an array with all localized fields for the given class
@param string $class the class name to get the fields for
@return array containing all the localized field names | [
"Get",
"an",
"array",
"with",
"all",
"localized",
"fields",
"for",
"the",
"given",
"class"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L487-L502 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.localized_field | public static function localized_field($field, $locale = null)
{
if ($locale === null) {
$locale = Translatable::get_current_locale();
}
if ($locale == Translatable::default_locale()) {
return $field;
}
return $field . TRANSLATABLE_COLUMN_SEPARATOR . $locale;
} | php | public static function localized_field($field, $locale = null)
{
if ($locale === null) {
$locale = Translatable::get_current_locale();
}
if ($locale == Translatable::default_locale()) {
return $field;
}
return $field . TRANSLATABLE_COLUMN_SEPARATOR . $locale;
} | [
"public",
"static",
"function",
"localized_field",
"(",
"$",
"field",
",",
"$",
"locale",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"locale",
"===",
"null",
")",
"{",
"$",
"locale",
"=",
"Translatable",
"::",
"get_current_locale",
"(",
")",
";",
"}",
"if"... | Given a field name and a locale name, create a composite string that represents
the field in the database.
@param string $field The field name or null to use the current locale
@param string|null $locale The locale name or null
@return string | [
"Given",
"a",
"field",
"name",
"and",
"a",
"locale",
"name",
"create",
"a",
"composite",
"string",
"that",
"represents",
"the",
"field",
"in",
"the",
"database",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L512-L521 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.set_locales | public static function set_locales($locales)
{
if (is_array($locales)) {
$list = array();
foreach ($locales as $locale) {
if (i18n::validate_locale($locale)) {
$list[] = $locale;
}
}
$list = array_unique($list);
Config::inst()->update('TranslatableDataObject', 'locales', empty($list) ? null : $list);
} else {
Config::inst()->update('TranslatableDataObject', 'locales', null);
}
} | php | public static function set_locales($locales)
{
if (is_array($locales)) {
$list = array();
foreach ($locales as $locale) {
if (i18n::validate_locale($locale)) {
$list[] = $locale;
}
}
$list = array_unique($list);
Config::inst()->update('TranslatableDataObject', 'locales', empty($list) ? null : $list);
} else {
Config::inst()->update('TranslatableDataObject', 'locales', null);
}
} | [
"public",
"static",
"function",
"set_locales",
"(",
"$",
"locales",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"locales",
")",
")",
"{",
"$",
"list",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"locales",
"as",
"$",
"locale",
")",
"{",
"if",
... | Explicitly set the locales that should be translated.
@example
<code>
// Set locales to en_US and fr_FR
TranslatableDataObject::set_locales(array('en_US', 'fr_FR'));
</code>
Defaults to `null`. In this case, locales are being taken from
Translatable::get_allowed_locales or Translatable::get_existing_content_languages
@param array|null $locales an array of locales or null
@deprecated 2.0 use YAML config `locales` instead | [
"Explicitly",
"set",
"the",
"locales",
"that",
"should",
"be",
"translated",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L572-L586 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.collectDBFields | protected static function collectDBFields($class)
{
if (isset(self::$collectorCache[$class])) {
return self::$collectorCache[$class];
}
if (isset(self::$collectorLock[$class]) && self::$collectorLock[$class]) {
return null;
}
self::$collectorLock[$class] = true;
// Get all DB Fields
$fields = array();
Config::inst()->get($class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $fields);
// Get all arguments
$arguments = self::get_arguments($class);
$locales = self::get_target_locales();
// remove the default locale
if (($index = array_search(Translatable::default_locale(), $locales)) !== false) {
array_splice($locales, $index, 1);
}
// fields that should be translated
$fieldsToTranslate = array();
// validate the arguments
if ($arguments) {
foreach ($arguments as $field) {
// only allow fields that are actually in our field list
if (array_key_exists($field, $fields)) {
$fieldsToTranslate[] = $field;
}
}
} else {
// check for the given default field types and add all fields of that type
foreach ($fields as $field => $type) {
$typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type;
$defaultFields = self::config()->default_field_types;
if (is_array($defaultFields) && in_array($typeClean, $defaultFields)) {
$fieldsToTranslate[] = $field;
}
}
}
// gather all the DB fields
$additionalFields = array();
self::$localizedFields[$class] = array();
foreach ($fieldsToTranslate as $field) {
self::$localizedFields[$class][$field] = array();
foreach ($locales as $locale) {
$localizedName = self::localized_field($field, $locale);
self::$localizedFields[$class][$field][] = $localizedName;
$additionalFields[$localizedName] = $fields[$field];
}
}
self::$collectorCache[$class] = $additionalFields;
self::$collectorLock[$class] = false;
return $additionalFields;
} | php | protected static function collectDBFields($class)
{
if (isset(self::$collectorCache[$class])) {
return self::$collectorCache[$class];
}
if (isset(self::$collectorLock[$class]) && self::$collectorLock[$class]) {
return null;
}
self::$collectorLock[$class] = true;
// Get all DB Fields
$fields = array();
Config::inst()->get($class, 'db', Config::EXCLUDE_EXTRA_SOURCES, $fields);
// Get all arguments
$arguments = self::get_arguments($class);
$locales = self::get_target_locales();
// remove the default locale
if (($index = array_search(Translatable::default_locale(), $locales)) !== false) {
array_splice($locales, $index, 1);
}
// fields that should be translated
$fieldsToTranslate = array();
// validate the arguments
if ($arguments) {
foreach ($arguments as $field) {
// only allow fields that are actually in our field list
if (array_key_exists($field, $fields)) {
$fieldsToTranslate[] = $field;
}
}
} else {
// check for the given default field types and add all fields of that type
foreach ($fields as $field => $type) {
$typeClean = (($p = strpos($type, '(')) !== false) ? substr($type, 0, $p) : $type;
$defaultFields = self::config()->default_field_types;
if (is_array($defaultFields) && in_array($typeClean, $defaultFields)) {
$fieldsToTranslate[] = $field;
}
}
}
// gather all the DB fields
$additionalFields = array();
self::$localizedFields[$class] = array();
foreach ($fieldsToTranslate as $field) {
self::$localizedFields[$class][$field] = array();
foreach ($locales as $locale) {
$localizedName = self::localized_field($field, $locale);
self::$localizedFields[$class][$field][] = $localizedName;
$additionalFields[$localizedName] = $fields[$field];
}
}
self::$collectorCache[$class] = $additionalFields;
self::$collectorLock[$class] = false;
return $additionalFields;
} | [
"protected",
"static",
"function",
"collectDBFields",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"collectorCache",
"[",
"$",
"class",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"collectorCache",
"[",
"$",
"class",
"]... | Collect all additional database fields of the given class.
@param string $class
@return array fieldnames that should be added | [
"Collect",
"all",
"additional",
"database",
"fields",
"of",
"the",
"given",
"class",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L603-L667 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.get_target_locales | protected static function get_target_locales()
{
// if locales are explicitly set, use these
if (is_array(self::config()->locales)) {
return (array)self::config()->locales;
// otherwise check the allowed locales. If these have been set, use these
} else if (is_array(Translatable::get_allowed_locales())) {
return (array)Translatable::get_allowed_locales();
}
// last resort is to take the existing content languages
return array_keys(Translatable::get_existing_content_languages());
} | php | protected static function get_target_locales()
{
// if locales are explicitly set, use these
if (is_array(self::config()->locales)) {
return (array)self::config()->locales;
// otherwise check the allowed locales. If these have been set, use these
} else if (is_array(Translatable::get_allowed_locales())) {
return (array)Translatable::get_allowed_locales();
}
// last resort is to take the existing content languages
return array_keys(Translatable::get_existing_content_languages());
} | [
"protected",
"static",
"function",
"get_target_locales",
"(",
")",
"{",
"// if locales are explicitly set, use these",
"if",
"(",
"is_array",
"(",
"self",
"::",
"config",
"(",
")",
"->",
"locales",
")",
")",
"{",
"return",
"(",
"array",
")",
"self",
"::",
"con... | Get the locales that should be translated
@return array containing the locales to use | [
"Get",
"the",
"locales",
"that",
"should",
"be",
"translated"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L743-L755 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.get_arguments | protected static function get_arguments($class)
{
if (isset(self::$arguments[$class])) {
return self::$arguments[$class];
} else {
if ($staticFields = Config::inst()->get($class, 'translatable_fields', Config::FIRST_SET)) {
if (is_array($staticFields) && !empty($staticFields)) {
return $staticFields;
}
}
}
return null;
} | php | protected static function get_arguments($class)
{
if (isset(self::$arguments[$class])) {
return self::$arguments[$class];
} else {
if ($staticFields = Config::inst()->get($class, 'translatable_fields', Config::FIRST_SET)) {
if (is_array($staticFields) && !empty($staticFields)) {
return $staticFields;
}
}
}
return null;
} | [
"protected",
"static",
"function",
"get_arguments",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"arguments",
"[",
"$",
"class",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"arguments",
"[",
"$",
"class",
"]",
";",
... | Get the custom arguments for a given class. Either directly from how the extension
was defined, or lookup the 'translatable_fields' static variable
@param string $class
@return array|null | [
"Get",
"the",
"custom",
"arguments",
"for",
"a",
"given",
"class",
".",
"Either",
"directly",
"from",
"how",
"the",
"extension",
"was",
"defined",
"or",
"lookup",
"the",
"translatable_fields",
"static",
"variable"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L764-L777 | train |
bummzack/translatable-dataobject | code/extensions/TranslatableDataObject.php | TranslatableDataObject.setFieldForRelation | public function setFieldForRelation($fieldName, FormField $field)
{
if (self::isLocalizedRelation($fieldName)) {
self::$localizedFields[$this->ownerBaseClass . '_has_one'][$fieldName]['FormField'] = $field;
}
} | php | public function setFieldForRelation($fieldName, FormField $field)
{
if (self::isLocalizedRelation($fieldName)) {
self::$localizedFields[$this->ownerBaseClass . '_has_one'][$fieldName]['FormField'] = $field;
}
} | [
"public",
"function",
"setFieldForRelation",
"(",
"$",
"fieldName",
",",
"FormField",
"$",
"field",
")",
"{",
"if",
"(",
"self",
"::",
"isLocalizedRelation",
"(",
"$",
"fieldName",
")",
")",
"{",
"self",
"::",
"$",
"localizedFields",
"[",
"$",
"this",
"->"... | Setter for relation specific FormField. Will be cloned in scaffolding functions
@param string $fieldName
@param FormField $field | [
"Setter",
"for",
"relation",
"specific",
"FormField",
".",
"Will",
"be",
"cloned",
"in",
"scaffolding",
"functions"
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/extensions/TranslatableDataObject.php#L784-L789 | train |
symfony/locale | Locale.php | Locale.getDisplayCountries | public static function getDisplayCountries($locale)
{
if (!isset(self::$countries[$locale])) {
self::$countries[$locale] = Intl::getRegionBundle()->getCountryNames($locale);
}
return self::$countries[$locale];
} | php | public static function getDisplayCountries($locale)
{
if (!isset(self::$countries[$locale])) {
self::$countries[$locale] = Intl::getRegionBundle()->getCountryNames($locale);
}
return self::$countries[$locale];
} | [
"public",
"static",
"function",
"getDisplayCountries",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"countries",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"self",
"::",
"$",
"countries",
"[",
"$",
"locale",
"]",
"=",
... | Returns the country names for a locale.
@param string $locale The locale to use for the country names
@return array The country names with their codes as keys
@throws \RuntimeException When the resource bundles cannot be loaded | [
"Returns",
"the",
"country",
"names",
"for",
"a",
"locale",
"."
] | c5e50d21e566cb685c1ee6802edadca643e8f83d | https://github.com/symfony/locale/blob/c5e50d21e566cb685c1ee6802edadca643e8f83d/Locale.php#L52-L59 | train |
symfony/locale | Locale.php | Locale.getDisplayLanguages | public static function getDisplayLanguages($locale)
{
if (!isset(self::$languages[$locale])) {
self::$languages[$locale] = Intl::getLanguageBundle()->getLanguageNames($locale);
}
return self::$languages[$locale];
} | php | public static function getDisplayLanguages($locale)
{
if (!isset(self::$languages[$locale])) {
self::$languages[$locale] = Intl::getLanguageBundle()->getLanguageNames($locale);
}
return self::$languages[$locale];
} | [
"public",
"static",
"function",
"getDisplayLanguages",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"languages",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"self",
"::",
"$",
"languages",
"[",
"$",
"locale",
"]",
"=",
... | Returns the language names for a locale.
@param string $locale The locale to use for the language names
@return array The language names with their codes as keys
@throws \RuntimeException When the resource bundles cannot be loaded | [
"Returns",
"the",
"language",
"names",
"for",
"a",
"locale",
"."
] | c5e50d21e566cb685c1ee6802edadca643e8f83d | https://github.com/symfony/locale/blob/c5e50d21e566cb685c1ee6802edadca643e8f83d/Locale.php#L82-L89 | train |
symfony/locale | Locale.php | Locale.getDisplayLocales | public static function getDisplayLocales($locale)
{
if (!isset(self::$locales[$locale])) {
self::$locales[$locale] = Intl::getLocaleBundle()->getLocaleNames($locale);
}
return self::$locales[$locale];
} | php | public static function getDisplayLocales($locale)
{
if (!isset(self::$locales[$locale])) {
self::$locales[$locale] = Intl::getLocaleBundle()->getLocaleNames($locale);
}
return self::$locales[$locale];
} | [
"public",
"static",
"function",
"getDisplayLocales",
"(",
"$",
"locale",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"locales",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"self",
"::",
"$",
"locales",
"[",
"$",
"locale",
"]",
"=",
"Intl... | Returns the locale names for a locale.
@param string $locale The locale to use for the locale names
@return array The locale names with their codes as keys
@throws \RuntimeException When the resource bundles cannot be loaded | [
"Returns",
"the",
"locale",
"names",
"for",
"a",
"locale",
"."
] | c5e50d21e566cb685c1ee6802edadca643e8f83d | https://github.com/symfony/locale/blob/c5e50d21e566cb685c1ee6802edadca643e8f83d/Locale.php#L112-L119 | train |
gyselroth/mongodb-php-task-scheduler | src/Queue.php | Queue.exitWorkerManager | public function exitWorkerManager(int $sig, array $pid): void
{
$this->logger->debug('fork manager ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED);
$this->cleanup(SIGTERM);
} | php | public function exitWorkerManager(int $sig, array $pid): void
{
$this->logger->debug('fork manager ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED);
$this->cleanup(SIGTERM);
} | [
"public",
"function",
"exitWorkerManager",
"(",
"int",
"$",
"sig",
",",
"array",
"$",
"pid",
")",
":",
"void",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'fork manager ['",
".",
"$",
"pid",
"[",
"'pid'",
"]",
".",
"'] exit with ['",
".",
"$... | Wait for worker manager. | [
"Wait",
"for",
"worker",
"manager",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Queue.php#L108-L116 | train |
gyselroth/mongodb-php-task-scheduler | src/Queue.php | Queue.initWorkerManager | protected function initWorkerManager()
{
$pid = pcntl_fork();
$this->manager_pid = $pid;
if (-1 === $pid) {
throw new SpawnForkException('failed to spawn fork manager');
}
if (!$pid) {
$manager = $this->factory->buildManager();
$manager->process();
exit();
}
} | php | protected function initWorkerManager()
{
$pid = pcntl_fork();
$this->manager_pid = $pid;
if (-1 === $pid) {
throw new SpawnForkException('failed to spawn fork manager');
}
if (!$pid) {
$manager = $this->factory->buildManager();
$manager->process();
exit();
}
} | [
"protected",
"function",
"initWorkerManager",
"(",
")",
"{",
"$",
"pid",
"=",
"pcntl_fork",
"(",
")",
";",
"$",
"this",
"->",
"manager_pid",
"=",
"$",
"pid",
";",
"if",
"(",
"-",
"1",
"===",
"$",
"pid",
")",
"{",
"throw",
"new",
"SpawnForkException",
... | Fork a worker manager. | [
"Fork",
"a",
"worker",
"manager",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Queue.php#L137-L151 | train |
gyselroth/mongodb-php-task-scheduler | src/Queue.php | Queue.main | protected function main(): void
{
$this->logger->info('start job listener', [
'category' => get_class($this),
]);
$cursor_jobs = $this->jobs->getCursor([
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
],
]);
$cursor_events = $this->events->getCursor([
'timestamp' => ['$gte' => new UTCDateTime()],
'job' => ['$exists' => true],
'status' => ['$gt' => JobInterface::STATUS_POSTPONED],
]);
$this->catchSignal();
while ($this->loop()) {
while ($this->loop()) {
if (null === $cursor_events->current()) {
if ($cursor_events->getInnerIterator()->isDead()) {
$this->logger->error('event queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
$this->main();
break;
}
$this->events->next($cursor_events, function () {
$this->main();
});
}
$event = $cursor_events->current();
$this->events->next($cursor_events, function () {
$this->main();
});
if($event === null) {
break;
}
$this->handleEvent($event);
}
if (null === $cursor_jobs->current()) {
if ($cursor_jobs->getInnerIterator()->isDead()) {
$this->logger->error('job queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->jobs->create();
$this->main();
break;
}
$this->jobs->next($cursor_jobs, function () {
$this->main();
});
continue;
}
$job = $cursor_jobs->current();
$this->jobs->next($cursor_jobs, function () {
$this->main();
});
$this->handleJob($job);
}
} | php | protected function main(): void
{
$this->logger->info('start job listener', [
'category' => get_class($this),
]);
$cursor_jobs = $this->jobs->getCursor([
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
],
]);
$cursor_events = $this->events->getCursor([
'timestamp' => ['$gte' => new UTCDateTime()],
'job' => ['$exists' => true],
'status' => ['$gt' => JobInterface::STATUS_POSTPONED],
]);
$this->catchSignal();
while ($this->loop()) {
while ($this->loop()) {
if (null === $cursor_events->current()) {
if ($cursor_events->getInnerIterator()->isDead()) {
$this->logger->error('event queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
$this->main();
break;
}
$this->events->next($cursor_events, function () {
$this->main();
});
}
$event = $cursor_events->current();
$this->events->next($cursor_events, function () {
$this->main();
});
if($event === null) {
break;
}
$this->handleEvent($event);
}
if (null === $cursor_jobs->current()) {
if ($cursor_jobs->getInnerIterator()->isDead()) {
$this->logger->error('job queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->jobs->create();
$this->main();
break;
}
$this->jobs->next($cursor_jobs, function () {
$this->main();
});
continue;
}
$job = $cursor_jobs->current();
$this->jobs->next($cursor_jobs, function () {
$this->main();
});
$this->handleJob($job);
}
} | [
"protected",
"function",
"main",
"(",
")",
":",
"void",
"{",
"$",
"this",
"->",
"logger",
"->",
"info",
"(",
"'start job listener'",
",",
"[",
"'category'",
"=>",
"get_class",
"(",
"$",
"this",
")",
",",
"]",
")",
";",
"$",
"cursor_jobs",
"=",
"$",
"... | Fork handling, blocking process. | [
"Fork",
"handling",
"blocking",
"process",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Queue.php#L156-L236 | train |
WPupdatePHP/wp-update-php | src/WPUpdatePhp.php | WPUpdatePhp.does_it_meet_required_php_version | public function does_it_meet_required_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->minimum_version, $version ) ) {
return true;
}
$this->load_version_notice( array( $this, 'minimum_admin_notice' ) );
return false;
} | php | public function does_it_meet_required_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->minimum_version, $version ) ) {
return true;
}
$this->load_version_notice( array( $this, 'minimum_admin_notice' ) );
return false;
} | [
"public",
"function",
"does_it_meet_required_php_version",
"(",
"$",
"version",
"=",
"PHP_VERSION",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"version_passes_requirement",
"(",
"$",
"this",
"->",
"minimum_version",
",",
"$",
"version",
")",
")",
"{",
"return",
"... | Check given PHP version against minimum required version.
@param string $version Optional. PHP version to check against.
Default is the current PHP version as a string in
"major.minor.release[extra]" notation.
@return bool True if supplied PHP version meets minimum required version. | [
"Check",
"given",
"PHP",
"version",
"against",
"minimum",
"required",
"version",
"."
] | fa50c343bef4a124142ea859f2096088ace6ce82 | https://github.com/WPupdatePHP/wp-update-php/blob/fa50c343bef4a124142ea859f2096088ace6ce82/src/WPUpdatePhp.php#L50-L57 | train |
WPupdatePHP/wp-update-php | src/WPUpdatePhp.php | WPUpdatePhp.does_it_meet_recommended_php_version | public function does_it_meet_recommended_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->recommended_version, $version ) ) {
return true;
}
$this->load_version_notice( array( $this, 'recommended_admin_notice' ) );
return false;
} | php | public function does_it_meet_recommended_php_version( $version = PHP_VERSION ) {
if ( $this->version_passes_requirement( $this->recommended_version, $version ) ) {
return true;
}
$this->load_version_notice( array( $this, 'recommended_admin_notice' ) );
return false;
} | [
"public",
"function",
"does_it_meet_recommended_php_version",
"(",
"$",
"version",
"=",
"PHP_VERSION",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"version_passes_requirement",
"(",
"$",
"this",
"->",
"recommended_version",
",",
"$",
"version",
")",
")",
"{",
"retur... | Check given PHP version against recommended version.
@param string $version Optional. PHP version to check against.
Default is the current PHP version as a string in
"major.minor.release[extra]" notation.
@return bool True if supplied PHP version meets recommended version. | [
"Check",
"given",
"PHP",
"version",
"against",
"recommended",
"version",
"."
] | fa50c343bef4a124142ea859f2096088ace6ce82 | https://github.com/WPupdatePHP/wp-update-php/blob/fa50c343bef4a124142ea859f2096088ace6ce82/src/WPUpdatePhp.php#L67-L74 | train |
WPupdatePHP/wp-update-php | src/WPUpdatePhp.php | WPUpdatePhp.get_admin_notice | public function get_admin_notice( $level = 'minimum' ) {
if ( 'recommended' === $level ) {
if ( ! empty( $this->plugin_name ) ) {
return '<p>' . $this->plugin_name . ' recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
} else {
return '<p>This plugin recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
}
}
if ( ! empty( $this->plugin_name ) ) {
return '<p>Unfortunately, ' . $this->plugin_name . ' cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
} else {
return '<p>Unfortunately, this plugin cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
}
} | php | public function get_admin_notice( $level = 'minimum' ) {
if ( 'recommended' === $level ) {
if ( ! empty( $this->plugin_name ) ) {
return '<p>' . $this->plugin_name . ' recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
} else {
return '<p>This plugin recommends a PHP version higher than ' . $this->recommended_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
}
}
if ( ! empty( $this->plugin_name ) ) {
return '<p>Unfortunately, ' . $this->plugin_name . ' cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
} else {
return '<p>Unfortunately, this plugin cannot run on PHP versions older than ' . $this->minimum_version . '. Read more information about <a href="http://www.wpupdatephp.com/update/">how you can update</a>.</p>';
}
} | [
"public",
"function",
"get_admin_notice",
"(",
"$",
"level",
"=",
"'minimum'",
")",
"{",
"if",
"(",
"'recommended'",
"===",
"$",
"level",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"plugin_name",
")",
")",
"{",
"return",
"'<p>'",
".",
... | Return the string to be shown in the admin notice.
This is based on the level (`recommended` or default `minimum`) of the
notice. This will also add the plugin name to the notice string, if set.
@param string $level Optional. Admin notice level, `recommended` or `minimum`.
Default is `minimum`.
@return string | [
"Return",
"the",
"string",
"to",
"be",
"shown",
"in",
"the",
"admin",
"notice",
"."
] | fa50c343bef4a124142ea859f2096088ace6ce82 | https://github.com/WPupdatePHP/wp-update-php/blob/fa50c343bef4a124142ea859f2096088ace6ce82/src/WPUpdatePhp.php#L109-L123 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator.php | Navigator.splAutoloader | private static function splAutoloader($class_name) {
if('Treffynnon\\Navigator' === substr(ltrim($class_name, '\\'), 0, 20)) {
$class_path = realpath(__DIR__ . '/..') . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $class_name);
require_once $class_path . '.php';
}
} | php | private static function splAutoloader($class_name) {
if('Treffynnon\\Navigator' === substr(ltrim($class_name, '\\'), 0, 20)) {
$class_path = realpath(__DIR__ . '/..') . '/' . str_replace('\\', DIRECTORY_SEPARATOR, $class_name);
require_once $class_path . '.php';
}
} | [
"private",
"static",
"function",
"splAutoloader",
"(",
"$",
"class_name",
")",
"{",
"if",
"(",
"'Treffynnon\\\\Navigator'",
"===",
"substr",
"(",
"ltrim",
"(",
"$",
"class_name",
",",
"'\\\\'",
")",
",",
"0",
",",
"20",
")",
")",
"{",
"$",
"class_path",
... | Convert class names into file paths for inclusion
@param string $class_name | [
"Convert",
"class",
"names",
"into",
"file",
"paths",
"for",
"inclusion"
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator.php#L44-L49 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator.php | Navigator.distanceFactory | public static function distanceFactory($lat1, $long1, $lat2, $long2) {
$point1 = new L(new C($lat1), new C($long1));
$point2 = new L(new C($lat2), new C($long2));
return new D($point1, $point2);
} | php | public static function distanceFactory($lat1, $long1, $lat2, $long2) {
$point1 = new L(new C($lat1), new C($long1));
$point2 = new L(new C($lat2), new C($long2));
return new D($point1, $point2);
} | [
"public",
"static",
"function",
"distanceFactory",
"(",
"$",
"lat1",
",",
"$",
"long1",
",",
"$",
"lat2",
",",
"$",
"long2",
")",
"{",
"$",
"point1",
"=",
"new",
"L",
"(",
"new",
"C",
"(",
"$",
"lat1",
")",
",",
"new",
"C",
"(",
"$",
"long1",
"... | Get a primed instance of the distance object
@param string|float $lat1
@param string|float $long1
@param string|float $lat2
@param string|float $long2
@return \Treffynnon\Navigator\Distance | [
"Get",
"a",
"primed",
"instance",
"of",
"the",
"distance",
"object"
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator.php#L59-L63 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator.php | Navigator.getDistance | public static function getDistance($lat1, $long1, $lat2, $long2) {
return self::distanceFactory($lat1, $long1, $lat2, $long2)->get();
} | php | public static function getDistance($lat1, $long1, $lat2, $long2) {
return self::distanceFactory($lat1, $long1, $lat2, $long2)->get();
} | [
"public",
"static",
"function",
"getDistance",
"(",
"$",
"lat1",
",",
"$",
"long1",
",",
"$",
"lat2",
",",
"$",
"long2",
")",
"{",
"return",
"self",
"::",
"distanceFactory",
"(",
"$",
"lat1",
",",
"$",
"long1",
",",
"$",
"lat2",
",",
"$",
"long2",
... | Get the distance in metres
@param string|float $lat1
@param string|float $long1
@param string|float $lat2
@param string|float $long2
@return float | [
"Get",
"the",
"distance",
"in",
"metres"
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator.php#L73-L75 | train |
gyselroth/mongodb-php-task-scheduler | src/WorkerManager.php | WorkerManager.exitWorker | public function exitWorker(int $sig, array $pid): self
{
$this->logger->debug('worker ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED);
foreach ($this->forks as $id => $process) {
if ($process === $pid['pid']) {
unset($this->forks[$id]);
if (isset($this->job_map[$id])) {
unset($this->job_map[$id]);
}
}
}
$this->spawnMinimumWorkers();
return $this;
} | php | public function exitWorker(int $sig, array $pid): self
{
$this->logger->debug('worker ['.$pid['pid'].'] exit with ['.$sig.']', [
'category' => get_class($this),
]);
pcntl_waitpid($pid['pid'], $status, WNOHANG | WUNTRACED);
foreach ($this->forks as $id => $process) {
if ($process === $pid['pid']) {
unset($this->forks[$id]);
if (isset($this->job_map[$id])) {
unset($this->job_map[$id]);
}
}
}
$this->spawnMinimumWorkers();
return $this;
} | [
"public",
"function",
"exitWorker",
"(",
"int",
"$",
"sig",
",",
"array",
"$",
"pid",
")",
":",
"self",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'worker ['",
".",
"$",
"pid",
"[",
"'pid'",
"]",
".",
"'] exit with ['",
".",
"$",
"sig",
... | Wait for child and terminate. | [
"Wait",
"for",
"child",
"and",
"terminate",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/WorkerManager.php#L182-L202 | train |
gyselroth/mongodb-php-task-scheduler | src/WorkerManager.php | WorkerManager.spawnInitialWorkers | protected function spawnInitialWorkers()
{
$this->logger->debug('spawn initial ['.$this->min_children.'] workers', [
'category' => get_class($this),
]);
if (self::PM_DYNAMIC === $this->pm || self::PM_STATIC === $this->pm) {
for ($i = $this->count(); $i < $this->min_children; ++$i) {
$this->spawnWorker();
}
}
} | php | protected function spawnInitialWorkers()
{
$this->logger->debug('spawn initial ['.$this->min_children.'] workers', [
'category' => get_class($this),
]);
if (self::PM_DYNAMIC === $this->pm || self::PM_STATIC === $this->pm) {
for ($i = $this->count(); $i < $this->min_children; ++$i) {
$this->spawnWorker();
}
}
} | [
"protected",
"function",
"spawnInitialWorkers",
"(",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'spawn initial ['",
".",
"$",
"this",
"->",
"min_children",
".",
"'] workers'",
",",
"[",
"'category'",
"=>",
"get_class",
"(",
"$",
"this",
")",... | Start initial workers. | [
"Start",
"initial",
"workers",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/WorkerManager.php#L235-L246 | train |
gyselroth/mongodb-php-task-scheduler | src/WorkerManager.php | WorkerManager.spawnMinimumWorkers | protected function spawnMinimumWorkers()
{
$this->logger->debug('verify that the minimum number ['.$this->min_children.'] of workers are running', [
'category' => get_class($this),
]);
for ($i = $this->count(); $i < $this->min_children; ++$i) {
$this->spawnWorker();
}
} | php | protected function spawnMinimumWorkers()
{
$this->logger->debug('verify that the minimum number ['.$this->min_children.'] of workers are running', [
'category' => get_class($this),
]);
for ($i = $this->count(); $i < $this->min_children; ++$i) {
$this->spawnWorker();
}
} | [
"protected",
"function",
"spawnMinimumWorkers",
"(",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"debug",
"(",
"'verify that the minimum number ['",
".",
"$",
"this",
"->",
"min_children",
".",
"'] of workers are running'",
",",
"[",
"'category'",
"=>",
"get_class"... | Start minumum number of workers. | [
"Start",
"minumum",
"number",
"of",
"workers",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/WorkerManager.php#L252-L261 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.getJob | public function getJob(ObjectId $id): Process
{
$result = $this->db->{$this->job_queue}->findOne([
'_id' => $id,
], [
'typeMap' => self::TYPE_MAP,
]);
if (null === $result) {
throw new JobNotFoundException('job '.$id.' was not found');
}
return new Process($result, $this, $this->events);
} | php | public function getJob(ObjectId $id): Process
{
$result = $this->db->{$this->job_queue}->findOne([
'_id' => $id,
], [
'typeMap' => self::TYPE_MAP,
]);
if (null === $result) {
throw new JobNotFoundException('job '.$id.' was not found');
}
return new Process($result, $this, $this->events);
} | [
"public",
"function",
"getJob",
"(",
"ObjectId",
"$",
"id",
")",
":",
"Process",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"db",
"->",
"{",
"$",
"this",
"->",
"job_queue",
"}",
"->",
"findOne",
"(",
"[",
"'_id'",
"=>",
"$",
"id",
",",
"]",
",",... | Get job by Id. | [
"Get",
"job",
"by",
"Id",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L230-L243 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.cancelJob | public function cancelJob(ObjectId $id): bool
{
$result = $this->updateJob($id, JobInterface::STATUS_CANCELED);
if (1 !== $result->getMatchedCount()) {
throw new JobNotFoundException('job '.$id.' was not found');
}
$this->db->{$this->event_queue}->insertOne([
'job' => $id,
'status' => JobInterface::STATUS_CANCELED,
'timestamp' => new UTCDateTime(),
]);
return true;
} | php | public function cancelJob(ObjectId $id): bool
{
$result = $this->updateJob($id, JobInterface::STATUS_CANCELED);
if (1 !== $result->getMatchedCount()) {
throw new JobNotFoundException('job '.$id.' was not found');
}
$this->db->{$this->event_queue}->insertOne([
'job' => $id,
'status' => JobInterface::STATUS_CANCELED,
'timestamp' => new UTCDateTime(),
]);
return true;
} | [
"public",
"function",
"cancelJob",
"(",
"ObjectId",
"$",
"id",
")",
":",
"bool",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"updateJob",
"(",
"$",
"id",
",",
"JobInterface",
"::",
"STATUS_CANCELED",
")",
";",
"if",
"(",
"1",
"!==",
"$",
"result",
"-... | Cancel job. | [
"Cancel",
"job",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L248-L263 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.addJob | public function addJob(string $class, $data, array $options = []): Process
{
$document = $this->prepareInsert($class, $data, $options);
$result = $this->db->{$this->job_queue}->insertOne($document);
$this->logger->debug('queue job ['.$result->getInsertedId().'] added to ['.$class.']', [
'category' => get_class($this),
'params' => $options,
'data' => $data,
]);
$this->db->{$this->event_queue}->insertOne([
'job' => $result->getInsertedId(),
'status' => JobInterface::STATUS_WAITING,
'timestamp' => new UTCDateTime(),
]);
$document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getInsertedId()], [
'typeMap' => self::TYPE_MAP,
]);
$process = new Process($document, $this, $this->events);
return $process;
} | php | public function addJob(string $class, $data, array $options = []): Process
{
$document = $this->prepareInsert($class, $data, $options);
$result = $this->db->{$this->job_queue}->insertOne($document);
$this->logger->debug('queue job ['.$result->getInsertedId().'] added to ['.$class.']', [
'category' => get_class($this),
'params' => $options,
'data' => $data,
]);
$this->db->{$this->event_queue}->insertOne([
'job' => $result->getInsertedId(),
'status' => JobInterface::STATUS_WAITING,
'timestamp' => new UTCDateTime(),
]);
$document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getInsertedId()], [
'typeMap' => self::TYPE_MAP,
]);
$process = new Process($document, $this, $this->events);
return $process;
} | [
"public",
"function",
"addJob",
"(",
"string",
"$",
"class",
",",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Process",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"prepareInsert",
"(",
"$",
"class",
",",
"$",
"data",
","... | Add job to queue. | [
"Add",
"job",
"to",
"queue",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L301-L325 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.addJobOnce | public function addJobOnce(string $class, $data, array $options = []): Process
{
$filter = [
'class' => $class,
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
['status' => JobInterface::STATUS_PROCESSING],
],
];
$requested = $options;
$document = $this->prepareInsert($class, $data, $options);
if (true !== $options[self::OPTION_IGNORE_DATA]) {
$filter = ['data' => $data] + $filter;
}
$result = $this->db->{$this->job_queue}->updateOne($filter, ['$setOnInsert' => $document], [
'upsert' => true,
'$isolated' => true,
]);
if ($result->getMatchedCount() > 0) {
$document = $this->db->{$this->job_queue}->findOne($filter, [
'typeMap' => self::TYPE_MAP,
]);
if (array_intersect_key($document['options'], $requested) !== $requested || ($data !== $document['data'] && true === $options[self::OPTION_IGNORE_DATA])) {
$this->logger->debug('job ['.$document['_id'].'] options/data changed, reschedule new job', [
'category' => get_class($this),
'data' => $data,
]);
$this->cancelJob($document['_id']);
return $this->addJobOnce($class, $data, $options);
}
return new Process($document, $this, $this->events);
}
$this->logger->debug('queue job ['.$result->getUpsertedId().'] added to ['.$class.']', [
'category' => get_class($this),
'params' => $options,
'data' => $data,
]);
$this->db->{$this->event_queue}->insertOne([
'job' => $result->getUpsertedId(),
'status' => JobInterface::STATUS_WAITING,
'timestamp' => new UTCDateTime(),
]);
$document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getUpsertedId()], [
'typeMap' => self::TYPE_MAP,
]);
return new Process($document, $this, $this->events);
} | php | public function addJobOnce(string $class, $data, array $options = []): Process
{
$filter = [
'class' => $class,
'$or' => [
['status' => JobInterface::STATUS_WAITING],
['status' => JobInterface::STATUS_POSTPONED],
['status' => JobInterface::STATUS_PROCESSING],
],
];
$requested = $options;
$document = $this->prepareInsert($class, $data, $options);
if (true !== $options[self::OPTION_IGNORE_DATA]) {
$filter = ['data' => $data] + $filter;
}
$result = $this->db->{$this->job_queue}->updateOne($filter, ['$setOnInsert' => $document], [
'upsert' => true,
'$isolated' => true,
]);
if ($result->getMatchedCount() > 0) {
$document = $this->db->{$this->job_queue}->findOne($filter, [
'typeMap' => self::TYPE_MAP,
]);
if (array_intersect_key($document['options'], $requested) !== $requested || ($data !== $document['data'] && true === $options[self::OPTION_IGNORE_DATA])) {
$this->logger->debug('job ['.$document['_id'].'] options/data changed, reschedule new job', [
'category' => get_class($this),
'data' => $data,
]);
$this->cancelJob($document['_id']);
return $this->addJobOnce($class, $data, $options);
}
return new Process($document, $this, $this->events);
}
$this->logger->debug('queue job ['.$result->getUpsertedId().'] added to ['.$class.']', [
'category' => get_class($this),
'params' => $options,
'data' => $data,
]);
$this->db->{$this->event_queue}->insertOne([
'job' => $result->getUpsertedId(),
'status' => JobInterface::STATUS_WAITING,
'timestamp' => new UTCDateTime(),
]);
$document = $this->db->{$this->job_queue}->findOne(['_id' => $result->getUpsertedId()], [
'typeMap' => self::TYPE_MAP,
]);
return new Process($document, $this, $this->events);
} | [
"public",
"function",
"addJobOnce",
"(",
"string",
"$",
"class",
",",
"$",
"data",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
":",
"Process",
"{",
"$",
"filter",
"=",
"[",
"'class'",
"=>",
"$",
"class",
",",
"'$or'",
"=>",
"[",
"[",
"'status... | Only add job if not in queue yet. | [
"Only",
"add",
"job",
"if",
"not",
"in",
"queue",
"yet",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L330-L389 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.listen | public function listen(Closure $callback, array $query = []): self
{
if (0 === count($query)) {
$query = [
'timestamp' => ['$gte' => new UTCDateTime()],
];
}
$cursor = $this->events->getCursor($query);
while (true) {
if (null === $cursor->current()) {
if ($cursor->getInnerIterator()->isDead()) {
$this->logger->error('events queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
return $this->listen($callback, $query);
}
$this->events->next($cursor, function () use ($callback, $query) {
return $this->listen($callback, $query);
});
continue;
}
$result = $cursor->current();
$this->events->next($cursor, function () use ($callback, $query) {
$this->listen($callback, $query);
});
$process = new Process($result, $this, $this->events);
if (true === $callback($process)) {
return $this;
}
}
} | php | public function listen(Closure $callback, array $query = []): self
{
if (0 === count($query)) {
$query = [
'timestamp' => ['$gte' => new UTCDateTime()],
];
}
$cursor = $this->events->getCursor($query);
while (true) {
if (null === $cursor->current()) {
if ($cursor->getInnerIterator()->isDead()) {
$this->logger->error('events queue cursor is dead, is it a capped collection?', [
'category' => get_class($this),
]);
$this->events->create();
return $this->listen($callback, $query);
}
$this->events->next($cursor, function () use ($callback, $query) {
return $this->listen($callback, $query);
});
continue;
}
$result = $cursor->current();
$this->events->next($cursor, function () use ($callback, $query) {
$this->listen($callback, $query);
});
$process = new Process($result, $this, $this->events);
if (true === $callback($process)) {
return $this;
}
}
} | [
"public",
"function",
"listen",
"(",
"Closure",
"$",
"callback",
",",
"array",
"$",
"query",
"=",
"[",
"]",
")",
":",
"self",
"{",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"query",
")",
")",
"{",
"$",
"query",
"=",
"[",
"'timestamp'",
"=>",
"[",... | Listen for events. | [
"Listen",
"for",
"events",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L453-L492 | train |
gyselroth/mongodb-php-task-scheduler | src/Scheduler.php | Scheduler.prepareInsert | protected function prepareInsert(string $class, $data, array &$options = []): array
{
$defaults = [
self::OPTION_AT => $this->default_at,
self::OPTION_INTERVAL => $this->default_interval,
self::OPTION_RETRY => $this->default_retry,
self::OPTION_RETRY_INTERVAL => $this->default_retry_interval,
self::OPTION_FORCE_SPAWN => false,
self::OPTION_TIMEOUT => $this->default_timeout,
self::OPTION_IGNORE_DATA => false,
];
$options = array_merge($defaults, $options);
$options = SchedulerValidator::validateOptions($options);
$document = [
'class' => $class,
'status' => JobInterface::STATUS_WAITING,
'created' => new UTCDateTime(),
'started' => new UTCDateTime(),
'ended' => new UTCDateTime(),
'worker' => new ObjectId(),
'data' => $data,
];
if (isset($options[self::OPTION_ID])) {
$id = $options[self::OPTION_ID];
unset($options[self::OPTION_ID]);
$document['_id'] = $id;
}
$document['options'] = $options;
return $document;
} | php | protected function prepareInsert(string $class, $data, array &$options = []): array
{
$defaults = [
self::OPTION_AT => $this->default_at,
self::OPTION_INTERVAL => $this->default_interval,
self::OPTION_RETRY => $this->default_retry,
self::OPTION_RETRY_INTERVAL => $this->default_retry_interval,
self::OPTION_FORCE_SPAWN => false,
self::OPTION_TIMEOUT => $this->default_timeout,
self::OPTION_IGNORE_DATA => false,
];
$options = array_merge($defaults, $options);
$options = SchedulerValidator::validateOptions($options);
$document = [
'class' => $class,
'status' => JobInterface::STATUS_WAITING,
'created' => new UTCDateTime(),
'started' => new UTCDateTime(),
'ended' => new UTCDateTime(),
'worker' => new ObjectId(),
'data' => $data,
];
if (isset($options[self::OPTION_ID])) {
$id = $options[self::OPTION_ID];
unset($options[self::OPTION_ID]);
$document['_id'] = $id;
}
$document['options'] = $options;
return $document;
} | [
"protected",
"function",
"prepareInsert",
"(",
"string",
"$",
"class",
",",
"$",
"data",
",",
"array",
"&",
"$",
"options",
"=",
"[",
"]",
")",
":",
"array",
"{",
"$",
"defaults",
"=",
"[",
"self",
"::",
"OPTION_AT",
"=>",
"$",
"this",
"->",
"default... | Prepare insert. | [
"Prepare",
"insert",
"."
] | 40f1620c865bd8d13ee4c951c54f69bfc4933b4b | https://github.com/gyselroth/mongodb-php-task-scheduler/blob/40f1620c865bd8d13ee4c951c54f69bfc4933b4b/src/Scheduler.php#L497-L531 | train |
bummzack/translatable-dataobject | code/TranslatableFormFieldTransformation.php | TranslatableFormFieldTransformation.transformFormField | public function transformFormField(FormField $field)
{
$newfield = $field->performReadOnlyTransformation();
$fieldname = $field->getName();
if ($this->original->isLocalizedField($fieldname)) {
$field->setName($this->original->getLocalizedFieldName($fieldname));
$value = $this->original->getLocalizedValue($fieldname);
if ($value instanceof DBField) {
$field->setValue($value->getValue());
} else {
$field->setValue($value);
}
}
return $this->baseTransform($newfield, $field, $fieldname);
} | php | public function transformFormField(FormField $field)
{
$newfield = $field->performReadOnlyTransformation();
$fieldname = $field->getName();
if ($this->original->isLocalizedField($fieldname)) {
$field->setName($this->original->getLocalizedFieldName($fieldname));
$value = $this->original->getLocalizedValue($fieldname);
if ($value instanceof DBField) {
$field->setValue($value->getValue());
} else {
$field->setValue($value);
}
}
return $this->baseTransform($newfield, $field, $fieldname);
} | [
"public",
"function",
"transformFormField",
"(",
"FormField",
"$",
"field",
")",
"{",
"$",
"newfield",
"=",
"$",
"field",
"->",
"performReadOnlyTransformation",
"(",
")",
";",
"$",
"fieldname",
"=",
"$",
"field",
"->",
"getName",
"(",
")",
";",
"if",
"(",
... | Transform a given form field into a composite field, where the translation is editable and the original value
is added as a read-only field.
@param FormField $field
@return CompositeField | [
"Transform",
"a",
"given",
"form",
"field",
"into",
"a",
"composite",
"field",
"where",
"the",
"translation",
"is",
"editable",
"and",
"the",
"original",
"value",
"is",
"added",
"as",
"a",
"read",
"-",
"only",
"field",
"."
] | a23cdefdb970d3d77c087350489107d3721ec709 | https://github.com/bummzack/translatable-dataobject/blob/a23cdefdb970d3d77c087350489107d3721ec709/code/TranslatableFormFieldTransformation.php#L39-L55 | train |
teamreflex/ChallongePHP | src/Challonge/Models/Tournament.php | Tournament.start | public function start()
{
if ($this->state != 'pending') {
throw new AlreadyStartedException('Tournament is already underway.');
}
$response = Guzzle::post("tournaments/{$this->id}/start");
return $this->updateModel($response->tournament);
} | php | public function start()
{
if ($this->state != 'pending') {
throw new AlreadyStartedException('Tournament is already underway.');
}
$response = Guzzle::post("tournaments/{$this->id}/start");
return $this->updateModel($response->tournament);
} | [
"public",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"state",
"!=",
"'pending'",
")",
"{",
"throw",
"new",
"AlreadyStartedException",
"(",
"'Tournament is already underway.'",
")",
";",
"}",
"$",
"response",
"=",
"Guzzle",
"::",
"post"... | Start a tournament, opening up first round matches for score reporting.
@return Tournament | [
"Start",
"a",
"tournament",
"opening",
"up",
"first",
"round",
"matches",
"for",
"score",
"reporting",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Models/Tournament.php#L18-L26 | train |
teamreflex/ChallongePHP | src/Challonge/Models/Tournament.php | Tournament.finalize | public function finalize()
{
if ($this->state != 'awaiting_review') {
throw new StillRunningException('Tournament is still running.');
}
$response = Guzzle::post("tournaments/{$this->id}/finalize");
return $this->updateModel($response->tournament);
} | php | public function finalize()
{
if ($this->state != 'awaiting_review') {
throw new StillRunningException('Tournament is still running.');
}
$response = Guzzle::post("tournaments/{$this->id}/finalize");
return $this->updateModel($response->tournament);
} | [
"public",
"function",
"finalize",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"state",
"!=",
"'awaiting_review'",
")",
"{",
"throw",
"new",
"StillRunningException",
"(",
"'Tournament is still running.'",
")",
";",
"}",
"$",
"response",
"=",
"Guzzle",
"::",
... | Finalize a tournament that has had all match scores submitted, rendering its results permanent.
@return Tournament | [
"Finalize",
"a",
"tournament",
"that",
"has",
"had",
"all",
"match",
"scores",
"submitted",
"rendering",
"its",
"results",
"permanent",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Models/Tournament.php#L33-L41 | train |
teamreflex/ChallongePHP | src/Challonge/Models/Tournament.php | Tournament.update | public function update($params = [])
{
$response = Guzzle::put("tournaments/{$this->id}", $params);
return $this->updateModel($response->tournament);
} | php | public function update($params = [])
{
$response = Guzzle::put("tournaments/{$this->id}", $params);
return $this->updateModel($response->tournament);
} | [
"public",
"function",
"update",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"put",
"(",
"\"tournaments/{$this->id}\"",
",",
"$",
"params",
")",
";",
"return",
"$",
"this",
"->",
"updateModel",
"(",
"$",
"response",
... | Update a tournament's attributes.
@param array $params
@return Tournament | [
"Update",
"a",
"tournament",
"s",
"attributes",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Models/Tournament.php#L60-L64 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator/Distance.php | Distance.get | public function get(D\Calculator\CalculatorInterface $calculator = null, D\Converter\ConverterInterface $unit_converter = null) {
if (is_null($calculator)) {
$calculator = new D\Calculator\Vincenty;
}
$distance = $calculator->calculate($this->point1, $this->point2);
if (!is_null($unit_converter)) {
$distance = $unit_converter->convert($distance);
}
return $distance;
} | php | public function get(D\Calculator\CalculatorInterface $calculator = null, D\Converter\ConverterInterface $unit_converter = null) {
if (is_null($calculator)) {
$calculator = new D\Calculator\Vincenty;
}
$distance = $calculator->calculate($this->point1, $this->point2);
if (!is_null($unit_converter)) {
$distance = $unit_converter->convert($distance);
}
return $distance;
} | [
"public",
"function",
"get",
"(",
"D",
"\\",
"Calculator",
"\\",
"CalculatorInterface",
"$",
"calculator",
"=",
"null",
",",
"D",
"\\",
"Converter",
"\\",
"ConverterInterface",
"$",
"unit_converter",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"... | Calculate the distance between two points. Defaults to Vincenty if
no calculator is supplied. If no unit converter is supplied then the
formula will return a value in metres.
@param D\Calculator\CalculatorInterface $calculator
@param D\Calculator\ConverterInterface $unit_converter
@return float | [
"Calculate",
"the",
"distance",
"between",
"two",
"points",
".",
"Defaults",
"to",
"Vincenty",
"if",
"no",
"calculator",
"is",
"supplied",
".",
"If",
"no",
"unit",
"converter",
"is",
"supplied",
"then",
"the",
"formula",
"will",
"return",
"a",
"value",
"in",... | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator/Distance.php#L48-L59 | train |
davidbarratt/custom-installer | src/CustomInstaller.php | CustomInstaller.getPackageReplacementTokens | protected function getPackageReplacementTokens(PackageInterface $package)
{
$vars = array(
'{$type}' => $package->getType(),
);
$prettyName = $package->getPrettyName();
if (strpos($prettyName, '/') !== false) {
$pieces = explode('/', $prettyName);
$vars['{$vendor}'] = $pieces[0];
$vars['{$name}'] = $pieces[1];
} else {
$vars['{$vendor}'] = '';
$vars['{$name}'] = $prettyName;
}
return $vars;
} | php | protected function getPackageReplacementTokens(PackageInterface $package)
{
$vars = array(
'{$type}' => $package->getType(),
);
$prettyName = $package->getPrettyName();
if (strpos($prettyName, '/') !== false) {
$pieces = explode('/', $prettyName);
$vars['{$vendor}'] = $pieces[0];
$vars['{$name}'] = $pieces[1];
} else {
$vars['{$vendor}'] = '';
$vars['{$name}'] = $prettyName;
}
return $vars;
} | [
"protected",
"function",
"getPackageReplacementTokens",
"(",
"PackageInterface",
"$",
"package",
")",
"{",
"$",
"vars",
"=",
"array",
"(",
"'{$type}'",
"=>",
"$",
"package",
"->",
"getType",
"(",
")",
",",
")",
";",
"$",
"prettyName",
"=",
"$",
"package",
... | Retrieve replacement tokens for the given package.
@param \Composer\Package\PackageInterface $package
@return array | [
"Retrieve",
"replacement",
"tokens",
"for",
"the",
"given",
"package",
"."
] | 90009113204b8b6257ead91866cc5cddc6876834 | https://github.com/davidbarratt/custom-installer/blob/90009113204b8b6257ead91866cc5cddc6876834/src/CustomInstaller.php#L59-L77 | train |
davidbarratt/custom-installer | src/CustomInstaller.php | CustomInstaller.getPluginConfiguration | protected function getPluginConfiguration()
{
if (!isset($this->configuration)) {
$extra = $this->composer->getPackage()->getExtra();
// We check if we need to support the legacy configuration.
$legacy = false;
if (isset($extra['custom-installer'])) {
// Legacy
$legacy = true;
foreach ($extra['custom-installer'] as $key => $val) {
if (is_array($val)) {
$legacy = false;
break;
}
}
}
if ($legacy) {
$this->configuration = new ConfigurationAlpha1($extra);
} else {
$this->configuration = new Configuration($extra);
}
}
return $this->configuration;
} | php | protected function getPluginConfiguration()
{
if (!isset($this->configuration)) {
$extra = $this->composer->getPackage()->getExtra();
// We check if we need to support the legacy configuration.
$legacy = false;
if (isset($extra['custom-installer'])) {
// Legacy
$legacy = true;
foreach ($extra['custom-installer'] as $key => $val) {
if (is_array($val)) {
$legacy = false;
break;
}
}
}
if ($legacy) {
$this->configuration = new ConfigurationAlpha1($extra);
} else {
$this->configuration = new Configuration($extra);
}
}
return $this->configuration;
} | [
"protected",
"function",
"getPluginConfiguration",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"configuration",
")",
")",
"{",
"$",
"extra",
"=",
"$",
"this",
"->",
"composer",
"->",
"getPackage",
"(",
")",
"->",
"getExtra",
"(",
")... | Retrieve plugin configuration object.
@return \DavidBarratt\CustomInstaller\Configuration | [
"Retrieve",
"plugin",
"configuration",
"object",
"."
] | 90009113204b8b6257ead91866cc5cddc6876834 | https://github.com/davidbarratt/custom-installer/blob/90009113204b8b6257ead91866cc5cddc6876834/src/CustomInstaller.php#L96-L122 | train |
tacowordpress/tacowordpress | src/Term.php | Term.getTaxonomyKey | public function getTaxonomyKey()
{
$called_class_segments = explode('\\', get_called_class());
$class_name = end($called_class_segments);
return (is_null($this->taxonomy_key))
? Str::machine(Str::camelToHuman($class_name), Base::SEPARATOR)
: $this->taxonomy_key;
} | php | public function getTaxonomyKey()
{
$called_class_segments = explode('\\', get_called_class());
$class_name = end($called_class_segments);
return (is_null($this->taxonomy_key))
? Str::machine(Str::camelToHuman($class_name), Base::SEPARATOR)
: $this->taxonomy_key;
} | [
"public",
"function",
"getTaxonomyKey",
"(",
")",
"{",
"$",
"called_class_segments",
"=",
"explode",
"(",
"'\\\\'",
",",
"get_called_class",
"(",
")",
")",
";",
"$",
"class_name",
"=",
"end",
"(",
"$",
"called_class_segments",
")",
";",
"return",
"(",
"is_nu... | Get the taxonomy key | [
"Get",
"the",
"taxonomy",
"key"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L44-L51 | train |
tacowordpress/tacowordpress | src/Term.php | Term.getOptionID | public function getOptionID($term_id = null)
{
return join('_', array(
$this->getTaxonomyKey(),
($term_id) ? $term_id : $this->get(self::ID)
));
} | php | public function getOptionID($term_id = null)
{
return join('_', array(
$this->getTaxonomyKey(),
($term_id) ? $term_id : $this->get(self::ID)
));
} | [
"public",
"function",
"getOptionID",
"(",
"$",
"term_id",
"=",
"null",
")",
"{",
"return",
"join",
"(",
"'_'",
",",
"array",
"(",
"$",
"this",
"->",
"getTaxonomyKey",
"(",
")",
",",
"(",
"$",
"term_id",
")",
"?",
"$",
"term_id",
":",
"$",
"this",
"... | Get the option ID
@param integet $term_id
@return string | [
"Get",
"the",
"option",
"ID"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L278-L284 | train |
tacowordpress/tacowordpress | src/Term.php | Term.renderAdminColumn | public function renderAdminColumn($column_name, $term_id)
{
$this->load($term_id);
parent::renderAdminColumn($column_name, $term_id);
} | php | public function renderAdminColumn($column_name, $term_id)
{
$this->load($term_id);
parent::renderAdminColumn($column_name, $term_id);
} | [
"public",
"function",
"renderAdminColumn",
"(",
"$",
"column_name",
",",
"$",
"term_id",
")",
"{",
"$",
"this",
"->",
"load",
"(",
"$",
"term_id",
")",
";",
"parent",
"::",
"renderAdminColumn",
"(",
"$",
"column_name",
",",
"$",
"term_id",
")",
";",
"}"
... | Render an admin column
Note param order is flipped from parent
@param string $column_name
@param integer $term_id | [
"Render",
"an",
"admin",
"column",
"Note",
"param",
"order",
"is",
"flipped",
"from",
"parent"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L373-L377 | train |
tacowordpress/tacowordpress | src/Term.php | Term.getEditPermalink | public function getEditPermalink($object_type = null)
{
// WordPress get_edit_term_link requires an object_type
// but if this object was created by \Taco\Post::getTerms
// then it will have an object_id, which also works
if (is_null($object_type)) {
$object_type = $this->get('object_id');
if (!$object_type) {
throw new \Exception('No object_type nor object_id');
}
}
return get_edit_term_link(
$this->get('term_id'),
$this->getTaxonomyKey(),
$object_type
);
} | php | public function getEditPermalink($object_type = null)
{
// WordPress get_edit_term_link requires an object_type
// but if this object was created by \Taco\Post::getTerms
// then it will have an object_id, which also works
if (is_null($object_type)) {
$object_type = $this->get('object_id');
if (!$object_type) {
throw new \Exception('No object_type nor object_id');
}
}
return get_edit_term_link(
$this->get('term_id'),
$this->getTaxonomyKey(),
$object_type
);
} | [
"public",
"function",
"getEditPermalink",
"(",
"$",
"object_type",
"=",
"null",
")",
"{",
"// WordPress get_edit_term_link requires an object_type",
"// but if this object was created by \\Taco\\Post::getTerms",
"// then it will have an object_id, which also works",
"if",
"(",
"is_null... | Get the edit permalink
@link http://codex.wordpress.org/Function_Reference/get_edit_term_link
@param string $object_type
@return string | [
"Get",
"the",
"edit",
"permalink"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L396-L412 | train |
tacowordpress/tacowordpress | src/Term.php | Term.getWhere | public static function getWhere($args = array())
{
$instance = Term\Factory::create(get_called_class());
// Allow sorting both by core fields and custom fields
// See: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
$default_args = array(
'orderby' => $instance->getDefaultOrderBy(),
'order' => $instance->getDefaultOrder(),
'hide_empty' => false, // Note: This goes against a WordPress get_terms default. But this seems more practical.
);
$criteria = array_merge($default_args, $args);
// Custom ordering
$orderby = null;
$order = null;
$wordpress_sortable_fields = array('id', 'name', 'count', 'slug', 'term_group', 'none');
if (array_key_exists('orderby', $criteria) && !in_array($criteria['orderby'], $wordpress_sortable_fields)) {
$orderby = $criteria['orderby'];
$order = (array_key_exists('order', $criteria))
? strtoupper($criteria['order'])
: 'ASC';
unset($criteria['orderby']);
unset($criteria['order']);
}
$criteria['taxonomy'] = $instance->getTaxonomyKey();
$terms = Term\Factory::createMultiple(get_terms($criteria));
// We might be done
if (!Arr::iterable($terms)) {
return $terms;
}
if (!$orderby) {
return $terms;
}
// Custom sorting that WordPress can't do
$field = $instance->getField($orderby);
// Make sure we're sorting numerically if appropriate
// because WordPress is storing strings for all vals
if ($field['type'] === 'number') {
foreach ($terms as &$term) {
if (!isset($term->$orderby)) {
continue;
}
if ($term->$orderby === '') {
continue;
}
$term->$orderby = (float) $term->$orderby;
}
}
// Sorting
$sort_flag = ($field['type'] === 'number') ? SORT_NUMERIC : SORT_STRING;
$terms = Collection::sortBy($terms, $orderby, $sort_flag);
if (strtoupper($order) === 'DESC') {
$terms = array_reverse($terms, true);
}
// Convert back to string as WordPress stores it
if ($field['type'] === 'number') {
foreach ($terms as &$term) {
if (!isset($term->$orderby)) {
continue;
}
if ($term->$orderby === '') {
continue;
}
$term->$orderby = (string) $term->$orderby;
}
}
return $terms;
} | php | public static function getWhere($args = array())
{
$instance = Term\Factory::create(get_called_class());
// Allow sorting both by core fields and custom fields
// See: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
$default_args = array(
'orderby' => $instance->getDefaultOrderBy(),
'order' => $instance->getDefaultOrder(),
'hide_empty' => false, // Note: This goes against a WordPress get_terms default. But this seems more practical.
);
$criteria = array_merge($default_args, $args);
// Custom ordering
$orderby = null;
$order = null;
$wordpress_sortable_fields = array('id', 'name', 'count', 'slug', 'term_group', 'none');
if (array_key_exists('orderby', $criteria) && !in_array($criteria['orderby'], $wordpress_sortable_fields)) {
$orderby = $criteria['orderby'];
$order = (array_key_exists('order', $criteria))
? strtoupper($criteria['order'])
: 'ASC';
unset($criteria['orderby']);
unset($criteria['order']);
}
$criteria['taxonomy'] = $instance->getTaxonomyKey();
$terms = Term\Factory::createMultiple(get_terms($criteria));
// We might be done
if (!Arr::iterable($terms)) {
return $terms;
}
if (!$orderby) {
return $terms;
}
// Custom sorting that WordPress can't do
$field = $instance->getField($orderby);
// Make sure we're sorting numerically if appropriate
// because WordPress is storing strings for all vals
if ($field['type'] === 'number') {
foreach ($terms as &$term) {
if (!isset($term->$orderby)) {
continue;
}
if ($term->$orderby === '') {
continue;
}
$term->$orderby = (float) $term->$orderby;
}
}
// Sorting
$sort_flag = ($field['type'] === 'number') ? SORT_NUMERIC : SORT_STRING;
$terms = Collection::sortBy($terms, $orderby, $sort_flag);
if (strtoupper($order) === 'DESC') {
$terms = array_reverse($terms, true);
}
// Convert back to string as WordPress stores it
if ($field['type'] === 'number') {
foreach ($terms as &$term) {
if (!isset($term->$orderby)) {
continue;
}
if ($term->$orderby === '') {
continue;
}
$term->$orderby = (string) $term->$orderby;
}
}
return $terms;
} | [
"public",
"static",
"function",
"getWhere",
"(",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"instance",
"=",
"Term",
"\\",
"Factory",
"::",
"create",
"(",
"get_called_class",
"(",
")",
")",
";",
"// Allow sorting both by core fields and custom fields",
... | Get terms with conditions
@param array $args
@return array | [
"Get",
"terms",
"with",
"conditions"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L504-L582 | train |
tacowordpress/tacowordpress | src/Term.php | Term.getOneWhere | public static function getOneWhere($args = array())
{
$args['number'] = 1;
$result = static::getWhere($args);
return (count($result)) ? current($result) : null;
} | php | public static function getOneWhere($args = array())
{
$args['number'] = 1;
$result = static::getWhere($args);
return (count($result)) ? current($result) : null;
} | [
"public",
"static",
"function",
"getOneWhere",
"(",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"$",
"args",
"[",
"'number'",
"]",
"=",
"1",
";",
"$",
"result",
"=",
"static",
"::",
"getWhere",
"(",
"$",
"args",
")",
";",
"return",
"(",
"count",... | Get one term
@param array $args
@return object | [
"Get",
"one",
"term"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L590-L595 | train |
tacowordpress/tacowordpress | src/Term.php | Term.find | public static function find($term_id)
{
$instance = Post\Factory::create(get_called_class());
$instance->load($term_id);
return $instance;
} | php | public static function find($term_id)
{
$instance = Post\Factory::create(get_called_class());
$instance->load($term_id);
return $instance;
} | [
"public",
"static",
"function",
"find",
"(",
"$",
"term_id",
")",
"{",
"$",
"instance",
"=",
"Post",
"\\",
"Factory",
"::",
"create",
"(",
"get_called_class",
"(",
")",
")",
";",
"$",
"instance",
"->",
"load",
"(",
"$",
"term_id",
")",
";",
"return",
... | Find a term
@param integer $term_id
@return object | [
"Find",
"a",
"term"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Term.php#L843-L848 | train |
tacowordpress/tacowordpress | src/Post/Loader.php | Loader.loadAll | public static function loadAll()
{
global $taxonomies_infos;
// Classes
$subclasses = self::getSubclasses();
foreach ($subclasses as $class) {
$instance = new $class;
$taxonomies_infos = array_merge(
$taxonomies_infos,
$instance->getTaxonomiesInfo()
);
self::load($class);
}
} | php | public static function loadAll()
{
global $taxonomies_infos;
// Classes
$subclasses = self::getSubclasses();
foreach ($subclasses as $class) {
$instance = new $class;
$taxonomies_infos = array_merge(
$taxonomies_infos,
$instance->getTaxonomiesInfo()
);
self::load($class);
}
} | [
"public",
"static",
"function",
"loadAll",
"(",
")",
"{",
"global",
"$",
"taxonomies_infos",
";",
"// Classes",
"$",
"subclasses",
"=",
"self",
"::",
"getSubclasses",
"(",
")",
";",
"foreach",
"(",
"$",
"subclasses",
"as",
"$",
"class",
")",
"{",
"$",
"i... | Load all the posts | [
"Load",
"all",
"the",
"posts"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Post/Loader.php#L29-L44 | train |
tacowordpress/tacowordpress | src/Post/Loader.php | Loader.load | public static function load($class)
{
$instance = new $class;
$post_type = $instance->getPostType();
// WordPress has a limit of 20 characters per
if (strlen($post_type) > 20) {
throw new \Exception('Post Type name exceeds maximum 20 characters: '.$post_type);
}
// This might happen if you're introducing a middle class between your post type and TacoPost
// Ex: Foo extends \ClientTacoPost extends Taco\Post
if (!$post_type) {
return false;
}
//add_action('init', array($instance, 'registerPostType'));
$instance->registerPostType();
add_action('save_post', array($instance, 'addSaveHooks'));
if (is_admin()) {
// If we're in the edit screen, we want the post loaded
// so that TacoPost::getFields knows which post it's working with.
// This helps if you want TacoPost::getFields to use conditional logic
// based on which post is currently being edited.
$is_edit_screen = (
is_array($_SERVER)
&& preg_match('/post.php\?post=[\d]{1,}/i', $_SERVER['REQUEST_URI'])
&& !Arr::iterable($_POST)
);
$is_edit_save = (
preg_match('/post.php/i', $_SERVER['REQUEST_URI'])
&& Arr::iterable($_POST)
);
$post = null;
if ($is_edit_screen && array_key_exists('post', $_GET)) {
$post = get_post($_GET['post']);
} elseif ($is_edit_save) {
$post = get_post($_POST['post_ID']);
}
if ($post && $post->post_type === $instance->getPostType()) {
$instance->load($post);
}
add_action('admin_menu', array($instance, 'addMetaBoxes'));
add_action(sprintf('manage_%s_posts_columns', $post_type), array($instance, 'addAdminColumns'), 10, 2);
add_action(sprintf('manage_%s_posts_custom_column', $post_type), array($instance, 'renderAdminColumn'), 10, 2);
add_filter(sprintf('manage_edit-%s_sortable_columns', $post_type), array($instance, 'makeAdminColumnsSortable'));
add_filter('request', array($instance, 'sortAdminColumns'));
add_filter('posts_clauses', array($instance, 'makeAdminTaxonomyColumnsSortable'), 10, 2);
// Hide the title column in the browse view of the admin UI
$is_browsing_index = (
is_array($_SERVER)
&& preg_match('/edit.php\?post_type='.$post_type.'$/i', $_SERVER['REQUEST_URI'])
);
if ($is_browsing_index && $instance->getHideTitleFromAdminColumns()) {
add_action('admin_init', function () {
wp_register_style('hide_title_column_css', plugins_url('taco/base/hide_title_column.css'));
wp_enqueue_style('hide_title_column_css');
});
}
}
} | php | public static function load($class)
{
$instance = new $class;
$post_type = $instance->getPostType();
// WordPress has a limit of 20 characters per
if (strlen($post_type) > 20) {
throw new \Exception('Post Type name exceeds maximum 20 characters: '.$post_type);
}
// This might happen if you're introducing a middle class between your post type and TacoPost
// Ex: Foo extends \ClientTacoPost extends Taco\Post
if (!$post_type) {
return false;
}
//add_action('init', array($instance, 'registerPostType'));
$instance->registerPostType();
add_action('save_post', array($instance, 'addSaveHooks'));
if (is_admin()) {
// If we're in the edit screen, we want the post loaded
// so that TacoPost::getFields knows which post it's working with.
// This helps if you want TacoPost::getFields to use conditional logic
// based on which post is currently being edited.
$is_edit_screen = (
is_array($_SERVER)
&& preg_match('/post.php\?post=[\d]{1,}/i', $_SERVER['REQUEST_URI'])
&& !Arr::iterable($_POST)
);
$is_edit_save = (
preg_match('/post.php/i', $_SERVER['REQUEST_URI'])
&& Arr::iterable($_POST)
);
$post = null;
if ($is_edit_screen && array_key_exists('post', $_GET)) {
$post = get_post($_GET['post']);
} elseif ($is_edit_save) {
$post = get_post($_POST['post_ID']);
}
if ($post && $post->post_type === $instance->getPostType()) {
$instance->load($post);
}
add_action('admin_menu', array($instance, 'addMetaBoxes'));
add_action(sprintf('manage_%s_posts_columns', $post_type), array($instance, 'addAdminColumns'), 10, 2);
add_action(sprintf('manage_%s_posts_custom_column', $post_type), array($instance, 'renderAdminColumn'), 10, 2);
add_filter(sprintf('manage_edit-%s_sortable_columns', $post_type), array($instance, 'makeAdminColumnsSortable'));
add_filter('request', array($instance, 'sortAdminColumns'));
add_filter('posts_clauses', array($instance, 'makeAdminTaxonomyColumnsSortable'), 10, 2);
// Hide the title column in the browse view of the admin UI
$is_browsing_index = (
is_array($_SERVER)
&& preg_match('/edit.php\?post_type='.$post_type.'$/i', $_SERVER['REQUEST_URI'])
);
if ($is_browsing_index && $instance->getHideTitleFromAdminColumns()) {
add_action('admin_init', function () {
wp_register_style('hide_title_column_css', plugins_url('taco/base/hide_title_column.css'));
wp_enqueue_style('hide_title_column_css');
});
}
}
} | [
"public",
"static",
"function",
"load",
"(",
"$",
"class",
")",
"{",
"$",
"instance",
"=",
"new",
"$",
"class",
";",
"$",
"post_type",
"=",
"$",
"instance",
"->",
"getPostType",
"(",
")",
";",
"// WordPress has a limit of 20 characters per",
"if",
"(",
"strl... | Load a post type
@param string $class | [
"Load",
"a",
"post",
"type"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Post/Loader.php#L51-L114 | train |
tacowordpress/tacowordpress | src/Post/Loader.php | Loader.getSubclasses | public static function getSubclasses()
{
$subclasses = array();
foreach (get_declared_classes() as $class) {
if (method_exists($class, 'isLoadable') && $class::isLoadable() === false) {
continue;
}
if (is_subclass_of($class, 'Taco\Post')) {
$subclasses[] = $class;
}
}
return $subclasses;
} | php | public static function getSubclasses()
{
$subclasses = array();
foreach (get_declared_classes() as $class) {
if (method_exists($class, 'isLoadable') && $class::isLoadable() === false) {
continue;
}
if (is_subclass_of($class, 'Taco\Post')) {
$subclasses[] = $class;
}
}
return $subclasses;
} | [
"public",
"static",
"function",
"getSubclasses",
"(",
")",
"{",
"$",
"subclasses",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"get_declared_classes",
"(",
")",
"as",
"$",
"class",
")",
"{",
"if",
"(",
"method_exists",
"(",
"$",
"class",
",",
"'isLoadab... | Get all subclasses
@return array | [
"Get",
"all",
"subclasses"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Post/Loader.php#L151-L163 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator/Distance/Calculator/Haversine.php | Haversine.calculate | public function calculate(N\LatLong $point1, N\LatLong $point2) {
$celestialBody = $this->getCelestialBody();
$deltaLat = $point2->getLatitude()->get() - $point1->getLatitude()->get();
$deltaLong = $point2->getLongitude()->get() - $point1->getLongitude()->get();
$a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($point1->getLatitude()->get()) * cos($point2->getLatitude()->get()) * sin($deltaLong / 2) * sin($deltaLong / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$d = $celestialBody->volumetricMeanRadius * $c * 1000;
return $d;
} | php | public function calculate(N\LatLong $point1, N\LatLong $point2) {
$celestialBody = $this->getCelestialBody();
$deltaLat = $point2->getLatitude()->get() - $point1->getLatitude()->get();
$deltaLong = $point2->getLongitude()->get() - $point1->getLongitude()->get();
$a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos($point1->getLatitude()->get()) * cos($point2->getLatitude()->get()) * sin($deltaLong / 2) * sin($deltaLong / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$d = $celestialBody->volumetricMeanRadius * $c * 1000;
return $d;
} | [
"public",
"function",
"calculate",
"(",
"N",
"\\",
"LatLong",
"$",
"point1",
",",
"N",
"\\",
"LatLong",
"$",
"point2",
")",
"{",
"$",
"celestialBody",
"=",
"$",
"this",
"->",
"getCelestialBody",
"(",
")",
";",
"$",
"deltaLat",
"=",
"$",
"point2",
"->",... | Calculate the distance between two
points using the Haversine formula.
Supply instances of the coordinate class.
http://en.wikipedia.org/wiki/Haversine_formula
@param Treffynnon\Navigator\Coordinate $point1
@param Treffynnon\Navigator\Coordinate $point2
@return float | [
"Calculate",
"the",
"distance",
"between",
"two",
"points",
"using",
"the",
"Haversine",
"formula",
"."
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator/Distance/Calculator/Haversine.php#L33-L41 | train |
teamreflex/ChallongePHP | src/Challonge/Models/Participant.php | Participant.update | public function update($params = [])
{
$response = Guzzle::put("tournaments/{$this->tournament_slug}/participants/{$this->id}", $params);
return $this->updateModel($response->participant);
} | php | public function update($params = [])
{
$response = Guzzle::put("tournaments/{$this->tournament_slug}/participants/{$this->id}", $params);
return $this->updateModel($response->participant);
} | [
"public",
"function",
"update",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"response",
"=",
"Guzzle",
"::",
"put",
"(",
"\"tournaments/{$this->tournament_slug}/participants/{$this->id}\"",
",",
"$",
"params",
")",
";",
"return",
"$",
"this",
"->",
"upda... | Update the attributes of a tournament participant.
@param array $params
@return Participant | [
"Update",
"the",
"attributes",
"of",
"a",
"tournament",
"participant",
"."
] | a99d7df3c51d39a5b193556b4614389f9c045f8b | https://github.com/teamreflex/ChallongePHP/blob/a99d7df3c51d39a5b193556b4614389f9c045f8b/src/Challonge/Models/Participant.php#L15-L19 | train |
logaretm/transformers | src/Transformer.php | Transformer.transform | public function transform($object)
{
if (($collection = $this->normalize($object)) instanceof Collection) {
return $this->transformCollection($collection);
}
// If there are relations setup, transform it along with the object.
if ($this->relatedCount) {
return $this->transformWithRelated($object);
}
// If another transformation method was requested, use that instead.
if (is_callable($this->transformationMethod)) {
return $this->getAlternateTransformation($object);
}
return $this->getTransformation($object);
} | php | public function transform($object)
{
if (($collection = $this->normalize($object)) instanceof Collection) {
return $this->transformCollection($collection);
}
// If there are relations setup, transform it along with the object.
if ($this->relatedCount) {
return $this->transformWithRelated($object);
}
// If another transformation method was requested, use that instead.
if (is_callable($this->transformationMethod)) {
return $this->getAlternateTransformation($object);
}
return $this->getTransformation($object);
} | [
"public",
"function",
"transform",
"(",
"$",
"object",
")",
"{",
"if",
"(",
"(",
"$",
"collection",
"=",
"$",
"this",
"->",
"normalize",
"(",
"$",
"object",
")",
")",
"instanceof",
"Collection",
")",
"{",
"return",
"$",
"this",
"->",
"transformCollection... | Transforms the object.
Called recursively when transforming a collection or a relation.
@param $object
@return array|mixed | [
"Transforms",
"the",
"object",
".",
"Called",
"recursively",
"when",
"transforming",
"a",
"collection",
"or",
"a",
"relation",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L38-L55 | train |
logaretm/transformers | src/Transformer.php | Transformer.normalize | protected function normalize($object)
{
// If its a paginator instance, create a collection with its items.
if ($object instanceof Paginator) {
return collect($object->items());
} elseif (is_array($object)) {
// If its an array, package it in a collection.
return collect($object);
}
return $object;
} | php | protected function normalize($object)
{
// If its a paginator instance, create a collection with its items.
if ($object instanceof Paginator) {
return collect($object->items());
} elseif (is_array($object)) {
// If its an array, package it in a collection.
return collect($object);
}
return $object;
} | [
"protected",
"function",
"normalize",
"(",
"$",
"object",
")",
"{",
"// If its a paginator instance, create a collection with its items.",
"if",
"(",
"$",
"object",
"instanceof",
"Paginator",
")",
"{",
"return",
"collect",
"(",
"$",
"object",
"->",
"items",
"(",
")"... | Normalizes the object to a collection if it is some sort of a container to multiple items.
@param $object
@return Collection | [
"Normalizes",
"the",
"object",
"to",
"a",
"collection",
"if",
"it",
"is",
"some",
"sort",
"of",
"a",
"container",
"to",
"multiple",
"items",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L63-L74 | train |
logaretm/transformers | src/Transformer.php | Transformer.transformWithRelated | public function transformWithRelated($item)
{
$transformedItem = $this->getTransformation($item);
return $this->transformRelated($transformedItem, $item);
} | php | public function transformWithRelated($item)
{
$transformedItem = $this->getTransformation($item);
return $this->transformRelated($transformedItem, $item);
} | [
"public",
"function",
"transformWithRelated",
"(",
"$",
"item",
")",
"{",
"$",
"transformedItem",
"=",
"$",
"this",
"->",
"getTransformation",
"(",
"$",
"item",
")",
";",
"return",
"$",
"this",
"->",
"transformRelated",
"(",
"$",
"transformedItem",
",",
"$",... | Transforms the item with its related models.
@param $item
@return array | [
"Transforms",
"the",
"item",
"with",
"its",
"related",
"models",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L99-L104 | train |
logaretm/transformers | src/Transformer.php | Transformer.with | public function with($relation)
{
$this->reset();
if (func_num_args() > 1) {
return $this->with(func_get_args());
}
if (is_array($relation)) {
$this->related = array_merge($this->related, $relation);
} else {
$this->related[] = $relation;
}
$this->relatedCount = count($this->related);
return $this;
} | php | public function with($relation)
{
$this->reset();
if (func_num_args() > 1) {
return $this->with(func_get_args());
}
if (is_array($relation)) {
$this->related = array_merge($this->related, $relation);
} else {
$this->related[] = $relation;
}
$this->relatedCount = count($this->related);
return $this;
} | [
"public",
"function",
"with",
"(",
"$",
"relation",
")",
"{",
"$",
"this",
"->",
"reset",
"(",
")",
";",
"if",
"(",
"func_num_args",
"(",
")",
">",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"with",
"(",
"func_get_args",
"(",
")",
")",
";",
"}",... | Adds a relation to the transformer.
@param $relation
@return $this | [
"Adds",
"a",
"relation",
"to",
"the",
"transformer",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L112-L129 | train |
logaretm/transformers | src/Transformer.php | Transformer.setTransformation | public function setTransformation($transformation)
{
if (is_callable($transformation)) {
$this->transformationMethod = $transformation;
return $this;
}
// replace just to avoid wrongly passing the name containing "Transformation".
$methodName = str_replace('Transformation', '', $transformation) . "Transformation";
if (! method_exists($this, $methodName)) {
throw new TransformerException("No such transformation as $methodName defined.");
}
$this->transformationMethod = [$this, $methodName];
return $this;
} | php | public function setTransformation($transformation)
{
if (is_callable($transformation)) {
$this->transformationMethod = $transformation;
return $this;
}
// replace just to avoid wrongly passing the name containing "Transformation".
$methodName = str_replace('Transformation', '', $transformation) . "Transformation";
if (! method_exists($this, $methodName)) {
throw new TransformerException("No such transformation as $methodName defined.");
}
$this->transformationMethod = [$this, $methodName];
return $this;
} | [
"public",
"function",
"setTransformation",
"(",
"$",
"transformation",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"transformation",
")",
")",
"{",
"$",
"this",
"->",
"transformationMethod",
"=",
"$",
"transformation",
";",
"return",
"$",
"this",
";",
"}",... | Sets the current transformation.
@param $transformation
@return $this
@throws TransformerException | [
"Sets",
"the",
"current",
"transformation",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L138-L156 | train |
logaretm/transformers | src/Transformer.php | Transformer.transformRelated | protected function transformRelated($itemTransformation, $item)
{
foreach ($this->related as $relation) {
// get direct relation name.
$relationName = explode('.', $relation, 2)[0];
$itemTransformation[$relationName] = $this->getRelatedTransformation($item, $relation);
}
return $itemTransformation;
} | php | protected function transformRelated($itemTransformation, $item)
{
foreach ($this->related as $relation) {
// get direct relation name.
$relationName = explode('.', $relation, 2)[0];
$itemTransformation[$relationName] = $this->getRelatedTransformation($item, $relation);
}
return $itemTransformation;
} | [
"protected",
"function",
"transformRelated",
"(",
"$",
"itemTransformation",
",",
"$",
"item",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"related",
"as",
"$",
"relation",
")",
"{",
"// get direct relation name.",
"$",
"relationName",
"=",
"explode",
"(",
"'... | Transforms the related item, and adds it to the transformation array.
@param $itemTransformation
@param $item
@return array | [
"Transforms",
"the",
"related",
"item",
"and",
"adds",
"it",
"to",
"the",
"transformation",
"array",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L178-L187 | train |
logaretm/transformers | src/Transformer.php | Transformer.getRelatedTransformation | protected function getRelatedTransformation($item, $relation)
{
// get nested relations separated by the dot notation.
// we only get one relation at a time because recursion handles the remaining relations.
$nestedRelations = explode('.', $relation, 2);
$relation = $nestedRelations[0];
$result = $item->{$relation};
$related = $result;
$transformer = null;
if (! is_object($related)) {
return $related;
}
// if its a collection switch the object to the first item.
if ($related instanceof Collection) {
if ($related->count()) {
$result = $result[0];
} else {
return [];
}
}
$transformer = $this->resolveTransformer($result);
// If no transformer was resolved.
if (! $transformer) {
return $related->toArray();
}
// if it has nested relations (equal to or more than 2 levels)
if (count($nestedRelations) == 2) {
// configure the remaining nested relations to the transformer.
$transformer->with($nestedRelations[1]);
}
return $transformer->transform($related);
} | php | protected function getRelatedTransformation($item, $relation)
{
// get nested relations separated by the dot notation.
// we only get one relation at a time because recursion handles the remaining relations.
$nestedRelations = explode('.', $relation, 2);
$relation = $nestedRelations[0];
$result = $item->{$relation};
$related = $result;
$transformer = null;
if (! is_object($related)) {
return $related;
}
// if its a collection switch the object to the first item.
if ($related instanceof Collection) {
if ($related->count()) {
$result = $result[0];
} else {
return [];
}
}
$transformer = $this->resolveTransformer($result);
// If no transformer was resolved.
if (! $transformer) {
return $related->toArray();
}
// if it has nested relations (equal to or more than 2 levels)
if (count($nestedRelations) == 2) {
// configure the remaining nested relations to the transformer.
$transformer->with($nestedRelations[1]);
}
return $transformer->transform($related);
} | [
"protected",
"function",
"getRelatedTransformation",
"(",
"$",
"item",
",",
"$",
"relation",
")",
"{",
"// get nested relations separated by the dot notation.",
"// we only get one relation at a time because recursion handles the remaining relations.",
"$",
"nestedRelations",
"=",
"e... | Resolves the transformation for the related model.
@param $item
@param $relation
@return mixed | [
"Resolves",
"the",
"transformation",
"for",
"the",
"related",
"model",
"."
] | 90309c08bd722f2cd38a5fea78b9dc2f157d8ecf | https://github.com/logaretm/transformers/blob/90309c08bd722f2cd38a5fea78b9dc2f157d8ecf/src/Transformer.php#L196-L235 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator/Distance/Calculator/GreatCircle.php | GreatCircle.calculate | public function calculate(N\LatLong $point1, N\LatLong $point2) {
$celestialBody = $this->getCelestialBody();
$degrees = acos(sin($point1->getLatitude()->get()) *
sin($point2->getLatitude()->get()) +
cos($point1->getLatitude()->get()) *
cos($point2->getLatitude()->get()) *
cos($point2->getLongitude()->get() -
$point1->getLongitude()->get()));
$d = $degrees * $celestialBody->volumetricMeanRadius;
return $d * 1000;
} | php | public function calculate(N\LatLong $point1, N\LatLong $point2) {
$celestialBody = $this->getCelestialBody();
$degrees = acos(sin($point1->getLatitude()->get()) *
sin($point2->getLatitude()->get()) +
cos($point1->getLatitude()->get()) *
cos($point2->getLatitude()->get()) *
cos($point2->getLongitude()->get() -
$point1->getLongitude()->get()));
$d = $degrees * $celestialBody->volumetricMeanRadius;
return $d * 1000;
} | [
"public",
"function",
"calculate",
"(",
"N",
"\\",
"LatLong",
"$",
"point1",
",",
"N",
"\\",
"LatLong",
"$",
"point2",
")",
"{",
"$",
"celestialBody",
"=",
"$",
"this",
"->",
"getCelestialBody",
"(",
")",
";",
"$",
"degrees",
"=",
"acos",
"(",
"sin",
... | Calculate the distance between two
points using the Great Circle formula.
Supply instances of the coordinate class.
http://www.ga.gov.au/earth-monitoring/geodesy/geodetic-techniques/distance-calculation-algorithms.html#circle
@param Treffynnon\Navigator\Coordinate $point1
@param Treffynnon\Navigator\Coordinate $point2
@return float | [
"Calculate",
"the",
"distance",
"between",
"two",
"points",
"using",
"the",
"Great",
"Circle",
"formula",
"."
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator/Distance/Calculator/GreatCircle.php#L33-L43 | train |
forxer/gravatar | src/Gravatar.php | Gravatar.image | public static function image($sEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false)
{
$gravatarImage = (new Image())
->setEmail($sEmail)
->setSize($iSize)
->setDefaultImage($sDefaultImage, $bForceDefault)
->setMaxRating($sRating)
->setExtension($sExtension);
return $gravatarImage;
} | php | public static function image($sEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false)
{
$gravatarImage = (new Image())
->setEmail($sEmail)
->setSize($iSize)
->setDefaultImage($sDefaultImage, $bForceDefault)
->setMaxRating($sRating)
->setExtension($sExtension);
return $gravatarImage;
} | [
"public",
"static",
"function",
"image",
"(",
"$",
"sEmail",
",",
"$",
"iSize",
"=",
"null",
",",
"$",
"sDefaultImage",
"=",
"null",
",",
"$",
"sRating",
"=",
"null",
",",
"$",
"sExtension",
"=",
"null",
",",
"$",
"bForceDefault",
"=",
"false",
")",
... | Return the Gravatar image based on the provided email address.
@param string $sEmail The email to get the gravatar for.
@param string $iSize The avatar size to use, must be less than 2048 and greater than 0.
@param string $sDefaultImage The default image to use. Use a valid image URL, or a recognized gravatar "default".
@param string $sRating The maximum rating to use for avatars
@param string $sExtension The avatar extension to use
@param boolean $bForceDefault Force the default image to be always load.
@return \forxer\Gravatar\Image | [
"Return",
"the",
"Gravatar",
"image",
"based",
"on",
"the",
"provided",
"email",
"address",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Gravatar.php#L31-L41 | train |
forxer/gravatar | src/Gravatar.php | Gravatar.images | public static function images(array $aEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false)
{
$aImages = [];
foreach ($aEmail as $sEmail) {
$gravatarImage = (new Image())
->setEmail($sEmail)
->setSize($iSize)
->setDefaultImage($sDefaultImage, $bForceDefault)
->setMaxRating($sRating)
->setExtension($sExtension);
$aImages[$sEmail] = $gravatarImage;
}
return $aImages;
} | php | public static function images(array $aEmail, $iSize = null, $sDefaultImage = null, $sRating = null, $sExtension = null, $bForceDefault = false)
{
$aImages = [];
foreach ($aEmail as $sEmail) {
$gravatarImage = (new Image())
->setEmail($sEmail)
->setSize($iSize)
->setDefaultImage($sDefaultImage, $bForceDefault)
->setMaxRating($sRating)
->setExtension($sExtension);
$aImages[$sEmail] = $gravatarImage;
}
return $aImages;
} | [
"public",
"static",
"function",
"images",
"(",
"array",
"$",
"aEmail",
",",
"$",
"iSize",
"=",
"null",
",",
"$",
"sDefaultImage",
"=",
"null",
",",
"$",
"sRating",
"=",
"null",
",",
"$",
"sExtension",
"=",
"null",
",",
"$",
"bForceDefault",
"=",
"false... | Return multiples Gravatar images based on the provided array of emails addresses.
@param array $aEmail The emails list to get the Gravatar images for.
@param string $iSize The avatar size to use, must be less than 2048 and greater than 0.
@param string $sDefaultImage The default image to use. Use a valid image URL, or a recognized gravatar "default".
@param string $sRating The maximum rating to use for avatars.
@param string $sExtension The avatar extension to use.
@param boolean $bForceDefault Force the default image to be always load.
@return array | [
"Return",
"multiples",
"Gravatar",
"images",
"based",
"on",
"the",
"provided",
"array",
"of",
"emails",
"addresses",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Gravatar.php#L54-L70 | train |
forxer/gravatar | src/Gravatar.php | Gravatar.profiles | public static function profiles(array $aEmail, $sFormat = null)
{
$aProfils = [];
foreach ($aEmail as $sEmail) {
$gravatarProfil = (new Profile())
->setEmail($sEmail)
->setFormat($sFormat);
$aProfils[$sEmail] = $gravatarProfil;
}
return $aProfils;
} | php | public static function profiles(array $aEmail, $sFormat = null)
{
$aProfils = [];
foreach ($aEmail as $sEmail) {
$gravatarProfil = (new Profile())
->setEmail($sEmail)
->setFormat($sFormat);
$aProfils[$sEmail] = $gravatarProfil;
}
return $aProfils;
} | [
"public",
"static",
"function",
"profiles",
"(",
"array",
"$",
"aEmail",
",",
"$",
"sFormat",
"=",
"null",
")",
"{",
"$",
"aProfils",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"aEmail",
"as",
"$",
"sEmail",
")",
"{",
"$",
"gravatarProfil",
"=",
"(",
... | Return multiples Gravatar profiles based on the provided array of emails addresses.
@param array $aEmail The emails list to get the Gravatar profiles for.
@param string $sFormat The profile format to use.
@return array | [
"Return",
"multiples",
"Gravatar",
"profiles",
"based",
"on",
"the",
"provided",
"array",
"of",
"emails",
"addresses",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Gravatar.php#L93-L106 | train |
forxer/gravatar | src/Gravatar.php | Gravatar.email | public function email($sEmail = null)
{
if (null === $sEmail) {
return $this->getEmail();
}
return $this->setEmail($sEmail);
} | php | public function email($sEmail = null)
{
if (null === $sEmail) {
return $this->getEmail();
}
return $this->setEmail($sEmail);
} | [
"public",
"function",
"email",
"(",
"$",
"sEmail",
"=",
"null",
")",
"{",
"if",
"(",
"null",
"===",
"$",
"sEmail",
")",
"{",
"return",
"$",
"this",
"->",
"getEmail",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"setEmail",
"(",
"$",
"sEmail",
... | Get or set the address email to be used.
@param string $sEmail
@return number|\forxer\Gravatar\Gravatar | [
"Get",
"or",
"set",
"the",
"address",
"email",
"to",
"be",
"used",
"."
] | 634e7e6a033c0c500a552e675d6367bd9ff1a743 | https://github.com/forxer/gravatar/blob/634e7e6a033c0c500a552e675d6367bd9ff1a743/src/Gravatar.php#L114-L121 | train |
tacowordpress/tacowordpress | src/Post/Factory.php | Factory.create | public static function create($post, $load_terms = true)
{
// Ex: Taco\Post\Factory::create('Video')
if (is_string($post) && class_exists($post)) {
return new $post;
}
$original_post = $post;
if (!is_object($post)) {
$post = get_post($post);
}
if (!is_object($post)) {
throw new \Exception(sprintf('Post %s not found in the database', json_encode($original_post)));
}
// TODO Refactor how this works to be more explicit and less guess
$class = str_replace(' ', '', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type)));
if (!class_exists($class)) {
$class = str_replace(' ', '\\', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type)));
}
$instance = new $class;
$instance->load($post, $load_terms);
return $instance;
} | php | public static function create($post, $load_terms = true)
{
// Ex: Taco\Post\Factory::create('Video')
if (is_string($post) && class_exists($post)) {
return new $post;
}
$original_post = $post;
if (!is_object($post)) {
$post = get_post($post);
}
if (!is_object($post)) {
throw new \Exception(sprintf('Post %s not found in the database', json_encode($original_post)));
}
// TODO Refactor how this works to be more explicit and less guess
$class = str_replace(' ', '', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type)));
if (!class_exists($class)) {
$class = str_replace(' ', '\\', ucwords(str_replace(Base::SEPARATOR, ' ', $post->post_type)));
}
$instance = new $class;
$instance->load($post, $load_terms);
return $instance;
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"post",
",",
"$",
"load_terms",
"=",
"true",
")",
"{",
"// Ex: Taco\\Post\\Factory::create('Video')",
"if",
"(",
"is_string",
"(",
"$",
"post",
")",
"&&",
"class_exists",
"(",
"$",
"post",
")",
")",
"{",
... | Create an instance based on a WP post
This basically autoloads the meta data
@param object $post
@param bool $load_terms
@return object | [
"Create",
"an",
"instance",
"based",
"on",
"a",
"WP",
"post",
"This",
"basically",
"autoloads",
"the",
"meta",
"data"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Post/Factory.php#L28-L52 | train |
tacowordpress/tacowordpress | src/Post/Factory.php | Factory.createMultiple | public static function createMultiple($posts, $load_terms = true)
{
if (!Arr::iterable($posts)) {
return $posts;
}
$out = array();
foreach ($posts as $k => $post) {
if (!get_post_status($post)) {
continue;
}
$record = self::create($post, $load_terms);
$out[$k] = $record;
}
return $out;
} | php | public static function createMultiple($posts, $load_terms = true)
{
if (!Arr::iterable($posts)) {
return $posts;
}
$out = array();
foreach ($posts as $k => $post) {
if (!get_post_status($post)) {
continue;
}
$record = self::create($post, $load_terms);
$out[$k] = $record;
}
return $out;
} | [
"public",
"static",
"function",
"createMultiple",
"(",
"$",
"posts",
",",
"$",
"load_terms",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"Arr",
"::",
"iterable",
"(",
"$",
"posts",
")",
")",
"{",
"return",
"$",
"posts",
";",
"}",
"$",
"out",
"=",
"array... | Create multiple instances based on WP posts
This basically autoloads the meta data
@param array $posts
@param bool $load_terms
@return array | [
"Create",
"multiple",
"instances",
"based",
"on",
"WP",
"posts",
"This",
"basically",
"autoloads",
"the",
"meta",
"data"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Post/Factory.php#L62-L77 | train |
demouth/DmImage | src/Dm/Image.php | Dm_Image.draw | public function draw(Dm_Image $image,$x=0,$y=0,$width=null,$height=null)
{
$srcImageResource = $image->getImageResource();
if (is_null($width)) $width = $image->getWidth();
if (is_null($height)) $height = $image->getHeight();
return imagecopy(
$this->getImageResource(),
$srcImageResource,
$x,
$y,
0,
0,
$width,
$height
);
} | php | public function draw(Dm_Image $image,$x=0,$y=0,$width=null,$height=null)
{
$srcImageResource = $image->getImageResource();
if (is_null($width)) $width = $image->getWidth();
if (is_null($height)) $height = $image->getHeight();
return imagecopy(
$this->getImageResource(),
$srcImageResource,
$x,
$y,
0,
0,
$width,
$height
);
} | [
"public",
"function",
"draw",
"(",
"Dm_Image",
"$",
"image",
",",
"$",
"x",
"=",
"0",
",",
"$",
"y",
"=",
"0",
",",
"$",
"width",
"=",
"null",
",",
"$",
"height",
"=",
"null",
")",
"{",
"$",
"srcImageResource",
"=",
"$",
"image",
"->",
"getImageR... | Copy and merge part of an image
@param DmImage
@param int x-coordinate of source point.
@param int y-coordinate of source point.
@param int Source width.
@param int Source height.
@return bool Returns TRUE on success or FALSE on failure. | [
"Copy",
"and",
"merge",
"part",
"of",
"an",
"image"
] | cf14053c5a57fc001eb124802f0e824bf0f19803 | https://github.com/demouth/DmImage/blob/cf14053c5a57fc001eb124802f0e824bf0f19803/src/Dm/Image.php#L150-L165 | train |
demouth/DmImage | src/Dm/Image.php | Dm_Image.saveTo | public function saveTo($path , $type='png', $quality=null)
{
if (!$path) return false;
return $this->outputTo($path, $type, $quality);
} | php | public function saveTo($path , $type='png', $quality=null)
{
if (!$path) return false;
return $this->outputTo($path, $type, $quality);
} | [
"public",
"function",
"saveTo",
"(",
"$",
"path",
",",
"$",
"type",
"=",
"'png'",
",",
"$",
"quality",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"path",
")",
"return",
"false",
";",
"return",
"$",
"this",
"->",
"outputTo",
"(",
"$",
"path",
","... | The path to save the file to.
@param string
@param string filetype 'png' 'jpg' 'jpeg' 'gif'
@return bool | [
"The",
"path",
"to",
"save",
"the",
"file",
"to",
"."
] | cf14053c5a57fc001eb124802f0e824bf0f19803 | https://github.com/demouth/DmImage/blob/cf14053c5a57fc001eb124802f0e824bf0f19803/src/Dm/Image.php#L173-L177 | train |
demouth/DmImage | src/Dm/Image.php | Dm_Image.destroy | public function destroy()
{
imagedestroy($this->_imageResource);
$this->graphics->destroy();
$this->graphics = null;
$this->textGraphics->destroy();
$this->textGraphics = null;
} | php | public function destroy()
{
imagedestroy($this->_imageResource);
$this->graphics->destroy();
$this->graphics = null;
$this->textGraphics->destroy();
$this->textGraphics = null;
} | [
"public",
"function",
"destroy",
"(",
")",
"{",
"imagedestroy",
"(",
"$",
"this",
"->",
"_imageResource",
")",
";",
"$",
"this",
"->",
"graphics",
"->",
"destroy",
"(",
")",
";",
"$",
"this",
"->",
"graphics",
"=",
"null",
";",
"$",
"this",
"->",
"te... | Destroy an image.
@return void | [
"Destroy",
"an",
"image",
"."
] | cf14053c5a57fc001eb124802f0e824bf0f19803 | https://github.com/demouth/DmImage/blob/cf14053c5a57fc001eb124802f0e824bf0f19803/src/Dm/Image.php#L227-L234 | train |
demouth/DmImage | src/Dm/Image.php | Dm_Image.toDataSchemeURI | public function toDataSchemeURI()
{
$md5 = md5(microtime(1).rand(10000, 99999));
$filePath = $this->tempDirPath() . DIRECTORY_SEPARATOR . "temp".$md5.".png";
$this->saveTo($filePath);
$uri = 'data:' . mime_content_type($filePath) . ';base64,';
$uri .= base64_encode(file_get_contents($filePath));
unlink($filePath);
return $uri;
} | php | public function toDataSchemeURI()
{
$md5 = md5(microtime(1).rand(10000, 99999));
$filePath = $this->tempDirPath() . DIRECTORY_SEPARATOR . "temp".$md5.".png";
$this->saveTo($filePath);
$uri = 'data:' . mime_content_type($filePath) . ';base64,';
$uri .= base64_encode(file_get_contents($filePath));
unlink($filePath);
return $uri;
} | [
"public",
"function",
"toDataSchemeURI",
"(",
")",
"{",
"$",
"md5",
"=",
"md5",
"(",
"microtime",
"(",
"1",
")",
".",
"rand",
"(",
"10000",
",",
"99999",
")",
")",
";",
"$",
"filePath",
"=",
"$",
"this",
"->",
"tempDirPath",
"(",
")",
".",
"DIRECTO... | Return data scheme URI.
@example
data:image/png;base64,iVBORw0KGgoAAAANSUhEU...
@return string | [
"Return",
"data",
"scheme",
"URI",
"."
] | cf14053c5a57fc001eb124802f0e824bf0f19803 | https://github.com/demouth/DmImage/blob/cf14053c5a57fc001eb124802f0e824bf0f19803/src/Dm/Image.php#L243-L255 | train |
kaystrobach/TYPO3.dyncss_scss | Resources/Private/Php/scss/example/Server.php | Server.serve | public function serve($salt = '')
{
$protocol = isset($_SERVER['SERVER_PROTOCOL'])
? $_SERVER['SERVER_PROTOCOL']
: 'HTTP/1.0';
if ($input = $this->findInput()) {
$output = $this->cacheName($salt . $input);
$etag = $noneMatch = trim($this->getIfNoneMatchHeader(), '"');
if ($this->needsCompile($output, $etag)) {
try {
list($css, $etag) = $this->compile($input, $output);
$lastModified = gmdate('D, d M Y H:i:s', filemtime($output)) . ' GMT';
header('Last-Modified: ' . $lastModified);
header('Content-type: text/css');
header('ETag: "' . $etag . '"');
echo $css;
} catch (\Exception $e) {
if ($this->showErrorsAsCSS) {
header('Content-type: text/css');
echo $this->createErrorCSS($e);
} else {
header($protocol . ' 500 Internal Server Error');
header('Content-type: text/plain');
echo 'Parse error: ' . $e->getMessage() . "\n";
}
}
return;
}
header('X-SCSS-Cache: true');
header('Content-type: text/css');
header('ETag: "' . $etag . '"');
if ($etag === $noneMatch) {
header($protocol . ' 304 Not Modified');
return;
}
$modifiedSince = $this->getIfModifiedSinceHeader();
$mtime = filemtime($output);
if (strtotime($modifiedSince) === $mtime) {
header($protocol . ' 304 Not Modified');
return;
}
$lastModified = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
header('Last-Modified: ' . $lastModified);
echo file_get_contents($output);
return;
}
header($protocol . ' 404 Not Found');
header('Content-type: text/plain');
$v = Version::VERSION;
echo "/* INPUT NOT FOUND scss $v */\n";
} | php | public function serve($salt = '')
{
$protocol = isset($_SERVER['SERVER_PROTOCOL'])
? $_SERVER['SERVER_PROTOCOL']
: 'HTTP/1.0';
if ($input = $this->findInput()) {
$output = $this->cacheName($salt . $input);
$etag = $noneMatch = trim($this->getIfNoneMatchHeader(), '"');
if ($this->needsCompile($output, $etag)) {
try {
list($css, $etag) = $this->compile($input, $output);
$lastModified = gmdate('D, d M Y H:i:s', filemtime($output)) . ' GMT';
header('Last-Modified: ' . $lastModified);
header('Content-type: text/css');
header('ETag: "' . $etag . '"');
echo $css;
} catch (\Exception $e) {
if ($this->showErrorsAsCSS) {
header('Content-type: text/css');
echo $this->createErrorCSS($e);
} else {
header($protocol . ' 500 Internal Server Error');
header('Content-type: text/plain');
echo 'Parse error: ' . $e->getMessage() . "\n";
}
}
return;
}
header('X-SCSS-Cache: true');
header('Content-type: text/css');
header('ETag: "' . $etag . '"');
if ($etag === $noneMatch) {
header($protocol . ' 304 Not Modified');
return;
}
$modifiedSince = $this->getIfModifiedSinceHeader();
$mtime = filemtime($output);
if (strtotime($modifiedSince) === $mtime) {
header($protocol . ' 304 Not Modified');
return;
}
$lastModified = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
header('Last-Modified: ' . $lastModified);
echo file_get_contents($output);
return;
}
header($protocol . ' 404 Not Found');
header('Content-type: text/plain');
$v = Version::VERSION;
echo "/* INPUT NOT FOUND scss $v */\n";
} | [
"public",
"function",
"serve",
"(",
"$",
"salt",
"=",
"''",
")",
"{",
"$",
"protocol",
"=",
"isset",
"(",
"$",
"_SERVER",
"[",
"'SERVER_PROTOCOL'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'SERVER_PROTOCOL'",
"]",
":",
"'HTTP/1.0'",
";",
"if",
"(",
"$",
... | Compile requested scss and serve css. Outputs HTTP response.
@param string $salt Prefix a string to the filename for creating the cache name hash | [
"Compile",
"requested",
"scss",
"and",
"serve",
"css",
".",
"Outputs",
"HTTP",
"response",
"."
] | 1234332542351eacfbdbada5c42b12c15bb087e4 | https://github.com/kaystrobach/TYPO3.dyncss_scss/blob/1234332542351eacfbdbada5c42b12c15bb087e4/Resources/Private/Php/scss/example/Server.php#L318-L387 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getPrefixGroupedMetaBoxes | public function getPrefixGroupedMetaBoxes()
{
$fields = $this->getFields();
// Just group by the field key prefix
// Ex: home_foo would go in the Home section by default
$groups = array();
foreach ($fields as $k => $field) {
$prefix = current(explode('_', $k));
if (!array_key_exists($prefix, $groups)) {
$groups[$prefix] = array();
}
$groups[$prefix][] = $k;
}
return $groups;
} | php | public function getPrefixGroupedMetaBoxes()
{
$fields = $this->getFields();
// Just group by the field key prefix
// Ex: home_foo would go in the Home section by default
$groups = array();
foreach ($fields as $k => $field) {
$prefix = current(explode('_', $k));
if (!array_key_exists($prefix, $groups)) {
$groups[$prefix] = array();
}
$groups[$prefix][] = $k;
}
return $groups;
} | [
"public",
"function",
"getPrefixGroupedMetaBoxes",
"(",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"getFields",
"(",
")",
";",
"// Just group by the field key prefix",
"// Ex: home_foo would go in the Home section by default",
"$",
"groups",
"=",
"array",
"(",
")"... | Get meta boxes grouped by prefix
@return array | [
"Get",
"meta",
"boxes",
"grouped",
"by",
"prefix"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L55-L72 | train |
tacowordpress/tacowordpress | src/Base.php | Base.replaceMetaBoxGroupMatches | public function replaceMetaBoxGroupMatches($meta_boxes)
{
if (!Arr::iterable($meta_boxes)) {
return $meta_boxes;
}
foreach ($meta_boxes as $k => $group) {
$group = (is_array($group)) ? $group : array($group);
if (array_key_exists('fields', $group)) {
continue;
}
$fields = $this->getFields();
$new_group = array();
foreach ($group as $pattern_key => $pattern) {
if (!preg_match('/\*$/', $pattern)) {
$new_group[] = $pattern;
continue;
}
$prefix = preg_replace('/\*$/', '', $pattern);
$regex = sprintf('/^%s/', $prefix);
foreach ($fields as $field_key => $field) {
if (!preg_match($regex, $field_key)) {
continue;
}
$new_group[] = $field_key;
}
}
$meta_boxes[$k] = $new_group;
}
return $meta_boxes;
} | php | public function replaceMetaBoxGroupMatches($meta_boxes)
{
if (!Arr::iterable($meta_boxes)) {
return $meta_boxes;
}
foreach ($meta_boxes as $k => $group) {
$group = (is_array($group)) ? $group : array($group);
if (array_key_exists('fields', $group)) {
continue;
}
$fields = $this->getFields();
$new_group = array();
foreach ($group as $pattern_key => $pattern) {
if (!preg_match('/\*$/', $pattern)) {
$new_group[] = $pattern;
continue;
}
$prefix = preg_replace('/\*$/', '', $pattern);
$regex = sprintf('/^%s/', $prefix);
foreach ($fields as $field_key => $field) {
if (!preg_match($regex, $field_key)) {
continue;
}
$new_group[] = $field_key;
}
}
$meta_boxes[$k] = $new_group;
}
return $meta_boxes;
} | [
"public",
"function",
"replaceMetaBoxGroupMatches",
"(",
"$",
"meta_boxes",
")",
"{",
"if",
"(",
"!",
"Arr",
"::",
"iterable",
"(",
"$",
"meta_boxes",
")",
")",
"{",
"return",
"$",
"meta_boxes",
";",
"}",
"foreach",
"(",
"$",
"meta_boxes",
"as",
"$",
"k"... | Replace any meta box group matches
@param array $meta_boxes
@return array | [
"Replace",
"any",
"meta",
"box",
"group",
"matches"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L80-L115 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getMetaBoxConfig | public function getMetaBoxConfig($config, $key = null)
{
// allow shorthand
if (!array_key_exists('fields', $config)) {
$fields = array();
foreach ($config as $field) {
// Arbitrary HTML is allowed
if (preg_match('/^\</', $field) && preg_match('/\>$/', $field)) {
$fields[md5(mt_rand())] = array(
'type'=>'html',
'label'=>null,
'value'=>$field,
);
continue;
}
$fields[$field] = $this->getField($field);
}
$config = array('fields'=>$fields);
}
if (Arr::iterable($config['fields'])) {
$fields = array();
foreach ($config['fields'] as $k => $v) {
if (is_array($v)) {
$fields[$k] = $v;
} else {
$fields[$v] = $this->getField($v);
}
}
$config['fields'] = $fields;
}
// defaults
$config['title'] = (array_key_exists('title', $config)) ? $config['title'] : $this->getMetaBoxTitle($key);
$config['context'] = (array_key_exists('context', $config)) ? $config['context'] : 'normal';
$config['priority'] = (array_key_exists('priority', $config)) ? $config['priority'] : 'high';
return $config;
} | php | public function getMetaBoxConfig($config, $key = null)
{
// allow shorthand
if (!array_key_exists('fields', $config)) {
$fields = array();
foreach ($config as $field) {
// Arbitrary HTML is allowed
if (preg_match('/^\</', $field) && preg_match('/\>$/', $field)) {
$fields[md5(mt_rand())] = array(
'type'=>'html',
'label'=>null,
'value'=>$field,
);
continue;
}
$fields[$field] = $this->getField($field);
}
$config = array('fields'=>$fields);
}
if (Arr::iterable($config['fields'])) {
$fields = array();
foreach ($config['fields'] as $k => $v) {
if (is_array($v)) {
$fields[$k] = $v;
} else {
$fields[$v] = $this->getField($v);
}
}
$config['fields'] = $fields;
}
// defaults
$config['title'] = (array_key_exists('title', $config)) ? $config['title'] : $this->getMetaBoxTitle($key);
$config['context'] = (array_key_exists('context', $config)) ? $config['context'] : 'normal';
$config['priority'] = (array_key_exists('priority', $config)) ? $config['priority'] : 'high';
return $config;
} | [
"public",
"function",
"getMetaBoxConfig",
"(",
"$",
"config",
",",
"$",
"key",
"=",
"null",
")",
"{",
"// allow shorthand",
"if",
"(",
"!",
"array_key_exists",
"(",
"'fields'",
",",
"$",
"config",
")",
")",
"{",
"$",
"fields",
"=",
"array",
"(",
")",
"... | Get a meta box config handling defaults
@param array $config
@param string $key
@return array | [
"Get",
"a",
"meta",
"box",
"config",
"handling",
"defaults"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L124-L161 | train |
tacowordpress/tacowordpress | src/Base.php | Base.assign | public function assign($vals)
{
if (count($vals) === 0) {
return 0;
}
$n = 0;
foreach ($vals as $k => $v) {
if ($this->set($k, $v)) {
$n++;
}
}
return $n;
} | php | public function assign($vals)
{
if (count($vals) === 0) {
return 0;
}
$n = 0;
foreach ($vals as $k => $v) {
if ($this->set($k, $v)) {
$n++;
}
}
return $n;
} | [
"public",
"function",
"assign",
"(",
"$",
"vals",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"vals",
")",
"===",
"0",
")",
"{",
"return",
"0",
";",
"}",
"$",
"n",
"=",
"0",
";",
"foreach",
"(",
"$",
"vals",
"as",
"$",
"k",
"=>",
"$",
"v",
")",... | Set multiple fields
@param array
@return integer Number of fields assigned | [
"Set",
"multiple",
"fields"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L169-L183 | train |
tacowordpress/tacowordpress | src/Base.php | Base.isValid | public function isValid($vals)
{
$fields = $this->getFields();
if (!Arr::iterable($fields)) {
return true;
}
$result = true;
// validate each field
foreach ($fields as $k => $field) {
// check if required
if ($this->isRequired($field)) {
if (!array_key_exists($k, $vals)
|| is_null($vals[$k])
|| $vals[$k] === ''
|| $vals[$k] === false
|| ($field['type'] === 'checkbox' && empty($vals[$k]))
) {
$result = false;
$this->_messages[$k] = $this->getFieldRequiredMessage($k);
continue;
}
}
// check maxlength
if (array_key_exists('maxlength', $field)) {
if (strlen($vals[$k]) > $field['maxlength']) {
$result = false;
$this->_messages[$k] = 'Value too long';
continue;
}
}
// after this point, we're only checking values based on type
if (!array_key_exists($k, $vals)) {
continue;
}
if (!array_key_exists('type', $field)) {
continue;
}
// Select
if ($field['type'] === 'select') {
if (!array_key_exists($vals[$k], $field['options'])) {
$result = false;
$this->_messages[$k] = 'Invalid option';
}
continue;
}
// Email
if ($field['type'] === 'email') {
if (!filter_var($vals[$k], FILTER_VALIDATE_EMAIL)) {
$result = false;
$this->_messages[$k] = 'Invalid email address';
}
continue;
}
// URL
if ($field['type'] === 'url') {
if (!filter_var($vals[$k], FILTER_VALIDATE_URL)) {
$result = false;
$this->_messages[$k] = 'Invalid URL';
}
continue;
}
// Color
// http://www.w3.org/TR/html-markup/input.color.html#input.color.attrs.value
if ($field['type'] === 'color') {
if (!preg_match('/^#[0-9a-f]{6}$/i', $vals[$k])) {
$result = false;
$this->_messages[$k] = 'Invalid color';
}
continue;
}
}
return $result;
} | php | public function isValid($vals)
{
$fields = $this->getFields();
if (!Arr::iterable($fields)) {
return true;
}
$result = true;
// validate each field
foreach ($fields as $k => $field) {
// check if required
if ($this->isRequired($field)) {
if (!array_key_exists($k, $vals)
|| is_null($vals[$k])
|| $vals[$k] === ''
|| $vals[$k] === false
|| ($field['type'] === 'checkbox' && empty($vals[$k]))
) {
$result = false;
$this->_messages[$k] = $this->getFieldRequiredMessage($k);
continue;
}
}
// check maxlength
if (array_key_exists('maxlength', $field)) {
if (strlen($vals[$k]) > $field['maxlength']) {
$result = false;
$this->_messages[$k] = 'Value too long';
continue;
}
}
// after this point, we're only checking values based on type
if (!array_key_exists($k, $vals)) {
continue;
}
if (!array_key_exists('type', $field)) {
continue;
}
// Select
if ($field['type'] === 'select') {
if (!array_key_exists($vals[$k], $field['options'])) {
$result = false;
$this->_messages[$k] = 'Invalid option';
}
continue;
}
// Email
if ($field['type'] === 'email') {
if (!filter_var($vals[$k], FILTER_VALIDATE_EMAIL)) {
$result = false;
$this->_messages[$k] = 'Invalid email address';
}
continue;
}
// URL
if ($field['type'] === 'url') {
if (!filter_var($vals[$k], FILTER_VALIDATE_URL)) {
$result = false;
$this->_messages[$k] = 'Invalid URL';
}
continue;
}
// Color
// http://www.w3.org/TR/html-markup/input.color.html#input.color.attrs.value
if ($field['type'] === 'color') {
if (!preg_match('/^#[0-9a-f]{6}$/i', $vals[$k])) {
$result = false;
$this->_messages[$k] = 'Invalid color';
}
continue;
}
}
return $result;
} | [
"public",
"function",
"isValid",
"(",
"$",
"vals",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"getFields",
"(",
")",
";",
"if",
"(",
"!",
"Arr",
"::",
"iterable",
"(",
"$",
"fields",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"result",... | Is this a valid entry?
@param array $vals
@return bool | [
"Is",
"this",
"a",
"valid",
"entry?"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L289-L369 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getMetaBoxTitle | public function getMetaBoxTitle($key = null)
{
return ($key) ? Str::human($key) : sprintf('%s', $this->getSingular());
} | php | public function getMetaBoxTitle($key = null)
{
return ($key) ? Str::human($key) : sprintf('%s', $this->getSingular());
} | [
"public",
"function",
"getMetaBoxTitle",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"return",
"(",
"$",
"key",
")",
"?",
"Str",
"::",
"human",
"(",
"$",
"key",
")",
":",
"sprintf",
"(",
"'%s'",
",",
"$",
"this",
"->",
"getSingular",
"(",
")",
")",
"... | Get the meta box title
@param string $key
@return string | [
"Get",
"the",
"meta",
"box",
"title"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L408-L411 | train |
tacowordpress/tacowordpress | src/Base.php | Base.scrubAttributes | private static function scrubAttributes($field, $type = null)
{
$invalid_keys = [
'default',
'description',
'label',
'options',
];
if ($type && $type ==='textarea') {
$invalid_keys[] = 'value';
}
foreach ($invalid_keys as $invalid_key) {
if (array_key_exists($invalid_key, $field)) {
unset($field[$invalid_key]);
}
}
return $field;
} | php | private static function scrubAttributes($field, $type = null)
{
$invalid_keys = [
'default',
'description',
'label',
'options',
];
if ($type && $type ==='textarea') {
$invalid_keys[] = 'value';
}
foreach ($invalid_keys as $invalid_key) {
if (array_key_exists($invalid_key, $field)) {
unset($field[$invalid_key]);
}
}
return $field;
} | [
"private",
"static",
"function",
"scrubAttributes",
"(",
"$",
"field",
",",
"$",
"type",
"=",
"null",
")",
"{",
"$",
"invalid_keys",
"=",
"[",
"'default'",
",",
"'description'",
",",
"'label'",
",",
"'options'",
",",
"]",
";",
"if",
"(",
"$",
"type",
"... | Remove invalid HTML attribute keys from field definition
@param array $field
@return array | [
"Remove",
"invalid",
"HTML",
"attribute",
"keys",
"from",
"field",
"definition"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L514-L533 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getCheckboxDisplay | public function getCheckboxDisplay($column_name)
{
$displays = $this->getCheckboxDisplays();
if (array_key_exists($column_name, $displays)) {
return $displays[$column_name];
}
if (array_key_exists('default', $displays)) {
return $displays['default'];
}
return array('Yes', 'No');
} | php | public function getCheckboxDisplay($column_name)
{
$displays = $this->getCheckboxDisplays();
if (array_key_exists($column_name, $displays)) {
return $displays[$column_name];
}
if (array_key_exists('default', $displays)) {
return $displays['default'];
}
return array('Yes', 'No');
} | [
"public",
"function",
"getCheckboxDisplay",
"(",
"$",
"column_name",
")",
"{",
"$",
"displays",
"=",
"$",
"this",
"->",
"getCheckboxDisplays",
"(",
")",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"column_name",
",",
"$",
"displays",
")",
")",
"{",
"retu... | Get checkbox display for a specific admin column
@param string $column_name
@return array | [
"Get",
"checkbox",
"display",
"for",
"a",
"specific",
"admin",
"column"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L581-L591 | train |
tacowordpress/tacowordpress | src/Base.php | Base.renderAdminColumn | public function renderAdminColumn($column_name, $item_id)
{
$columns = $this->getAdminColumns();
if (!in_array($column_name, $columns)) {
return;
}
$field = $this->getField($column_name);
if (is_array($field)) {
$class = get_called_class();
$entry = new $class;
$entry->load($item_id);
$out = $entry->get($column_name);
if (isset($field['type'])) {
switch ($field['type']) {
case 'checkbox':
$checkbox_display = $entry->getCheckboxDisplay($column_name);
$out = ($entry->get($column_name))
? reset($checkbox_display)
: end($checkbox_display);
break;
case 'image':
$out = Html::image($entry->get($column_name), $entry->get($column_name), array('class'=>'thumbnail'));
break;
case 'select':
$out = array_key_exists($entry->get($column_name), $field['options'])
? $field['options'][$entry->get($column_name)]
: null;
break;
}
}
// Hide the title field if necessary.
// But since the title field is the link to the edit page
// we are instead going to link the first custom field column.
if (method_exists($this, 'getHideTitleFromAdminColumns')
&& $this->getHideTitleFromAdminColumns()
&& method_exists($this, 'getEditPermalink')
&& array_search($column_name, array_values($columns)) === 0
) {
$out = sprintf('<a href="%s">%s</a>', $this->getEditPermalink(), $out);
}
echo $out;
return;
}
if (Arr::iterable($this->getTaxonomies())) {
$taxonomy_key = $this->getTaxonomyKey($column_name);
if ($taxonomy_key) {
echo get_the_term_list($item_id, $taxonomy_key, null, ', ');
return;
}
}
} | php | public function renderAdminColumn($column_name, $item_id)
{
$columns = $this->getAdminColumns();
if (!in_array($column_name, $columns)) {
return;
}
$field = $this->getField($column_name);
if (is_array($field)) {
$class = get_called_class();
$entry = new $class;
$entry->load($item_id);
$out = $entry->get($column_name);
if (isset($field['type'])) {
switch ($field['type']) {
case 'checkbox':
$checkbox_display = $entry->getCheckboxDisplay($column_name);
$out = ($entry->get($column_name))
? reset($checkbox_display)
: end($checkbox_display);
break;
case 'image':
$out = Html::image($entry->get($column_name), $entry->get($column_name), array('class'=>'thumbnail'));
break;
case 'select':
$out = array_key_exists($entry->get($column_name), $field['options'])
? $field['options'][$entry->get($column_name)]
: null;
break;
}
}
// Hide the title field if necessary.
// But since the title field is the link to the edit page
// we are instead going to link the first custom field column.
if (method_exists($this, 'getHideTitleFromAdminColumns')
&& $this->getHideTitleFromAdminColumns()
&& method_exists($this, 'getEditPermalink')
&& array_search($column_name, array_values($columns)) === 0
) {
$out = sprintf('<a href="%s">%s</a>', $this->getEditPermalink(), $out);
}
echo $out;
return;
}
if (Arr::iterable($this->getTaxonomies())) {
$taxonomy_key = $this->getTaxonomyKey($column_name);
if ($taxonomy_key) {
echo get_the_term_list($item_id, $taxonomy_key, null, ', ');
return;
}
}
} | [
"public",
"function",
"renderAdminColumn",
"(",
"$",
"column_name",
",",
"$",
"item_id",
")",
"{",
"$",
"columns",
"=",
"$",
"this",
"->",
"getAdminColumns",
"(",
")",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"column_name",
",",
"$",
"columns",
")",
... | Render an admin column
@param string $column_name
@param integer $item_id | [
"Render",
"an",
"admin",
"column"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L611-L665 | train |
tacowordpress/tacowordpress | src/Base.php | Base.makeAdminColumnsSortable | public function makeAdminColumnsSortable($columns)
{
$admin_columns = $this->getAdminColumns();
if (!Arr::iterable($admin_columns)) {
return $columns;
}
foreach ($admin_columns as $k) {
$columns[$k] = $k;
}
return $columns;
} | php | public function makeAdminColumnsSortable($columns)
{
$admin_columns = $this->getAdminColumns();
if (!Arr::iterable($admin_columns)) {
return $columns;
}
foreach ($admin_columns as $k) {
$columns[$k] = $k;
}
return $columns;
} | [
"public",
"function",
"makeAdminColumnsSortable",
"(",
"$",
"columns",
")",
"{",
"$",
"admin_columns",
"=",
"$",
"this",
"->",
"getAdminColumns",
"(",
")",
";",
"if",
"(",
"!",
"Arr",
"::",
"iterable",
"(",
"$",
"admin_columns",
")",
")",
"{",
"return",
... | Make the admin columns sortable
@param array $columns
@return array | [
"Make",
"the",
"admin",
"columns",
"sortable"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L673-L684 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getPlural | public function getPlural()
{
$singular = $this->getSingular();
if (preg_match('/y$/', $singular)) {
return preg_replace('/y$/', 'ies', $singular);
}
return (is_null($this->plural))
? Str::human($singular) . 's'
: $this->plural;
} | php | public function getPlural()
{
$singular = $this->getSingular();
if (preg_match('/y$/', $singular)) {
return preg_replace('/y$/', 'ies', $singular);
}
return (is_null($this->plural))
? Str::human($singular) . 's'
: $this->plural;
} | [
"public",
"function",
"getPlural",
"(",
")",
"{",
"$",
"singular",
"=",
"$",
"this",
"->",
"getSingular",
"(",
")",
";",
"if",
"(",
"preg_match",
"(",
"'/y$/'",
",",
"$",
"singular",
")",
")",
"{",
"return",
"preg_replace",
"(",
"'/y$/'",
",",
"'ies'",... | Get the plural name
@return string | [
"Get",
"the",
"plural",
"name"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L703-L712 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getThe | public function getThe($key, $convert_value = false, $return_wrapped = true)
{
if ($return_wrapped) {
return apply_filters('the_content', $this->get($key, $convert_value));
}
// Apply the_content filter without wrapping lines in <p> tags
remove_filter('the_content', 'wpautop');
$value = apply_filters('the_content', $this->get($key, $convert_value));
add_filter('the_content', 'wpautop');
return $value;
} | php | public function getThe($key, $convert_value = false, $return_wrapped = true)
{
if ($return_wrapped) {
return apply_filters('the_content', $this->get($key, $convert_value));
}
// Apply the_content filter without wrapping lines in <p> tags
remove_filter('the_content', 'wpautop');
$value = apply_filters('the_content', $this->get($key, $convert_value));
add_filter('the_content', 'wpautop');
return $value;
} | [
"public",
"function",
"getThe",
"(",
"$",
"key",
",",
"$",
"convert_value",
"=",
"false",
",",
"$",
"return_wrapped",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"return_wrapped",
")",
"{",
"return",
"apply_filters",
"(",
"'the_content'",
",",
"$",
"this",
"-... | Get any value run through the_content filter
@param string $key
@param bool $convert_value Convert the value (for select fields)
@param bool $return_wrapped Wrap lines in <p> tags
@return string HTML | [
"Get",
"any",
"value",
"run",
"through",
"the_content",
"filter"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L722-L733 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getLabelText | public function getLabelText($field_key)
{
$field = $this->getField($field_key);
if (!is_array($field)) {
return null;
}
return (array_key_exists('label', $field))
? $field['label']
: Str::human(str_replace('-', ' ', preg_replace('/_id$/i', '', $field_key)));
} | php | public function getLabelText($field_key)
{
$field = $this->getField($field_key);
if (!is_array($field)) {
return null;
}
return (array_key_exists('label', $field))
? $field['label']
: Str::human(str_replace('-', ' ', preg_replace('/_id$/i', '', $field_key)));
} | [
"public",
"function",
"getLabelText",
"(",
"$",
"field_key",
")",
"{",
"$",
"field",
"=",
"$",
"this",
"->",
"getField",
"(",
"$",
"field_key",
")",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"field",
")",
")",
"{",
"return",
"null",
";",
"}",
"ret... | Get the label text for a field
@param mixed $field_key Alternatively, you can pass in the field array
@return string | [
"Get",
"the",
"label",
"text",
"for",
"a",
"field"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L773-L783 | train |
tacowordpress/tacowordpress | src/Base.php | Base.getRenderLabel | public function getRenderLabel($field_key, $required_mark = ' <span class="required">*</span>')
{
return sprintf(
'<label for="%s">%s%s</label>',
$field_key,
$this->getLabelText($field_key),
($required_mark && $this->isRequired($field_key)) ? $required_mark : null
);
} | php | public function getRenderLabel($field_key, $required_mark = ' <span class="required">*</span>')
{
return sprintf(
'<label for="%s">%s%s</label>',
$field_key,
$this->getLabelText($field_key),
($required_mark && $this->isRequired($field_key)) ? $required_mark : null
);
} | [
"public",
"function",
"getRenderLabel",
"(",
"$",
"field_key",
",",
"$",
"required_mark",
"=",
"' <span class=\"required\">*</span>'",
")",
"{",
"return",
"sprintf",
"(",
"'<label for=\"%s\">%s%s</label>'",
",",
"$",
"field_key",
",",
"$",
"this",
"->",
"getLabelText"... | Get the label HTML for a field
@param string $field_key
@param mixed $required_mark Pass null if you don't want required fields to be marked
@return string | [
"Get",
"the",
"label",
"HTML",
"for",
"a",
"field"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L792-L800 | train |
tacowordpress/tacowordpress | src/Base.php | Base.isRequired | public function isRequired($field_key)
{
$field = (is_array($field_key)) ? $field_key : $this->getField($field_key);
return (is_array($field) && array_key_exists('required', $field) && $field['required']);
} | php | public function isRequired($field_key)
{
$field = (is_array($field_key)) ? $field_key : $this->getField($field_key);
return (is_array($field) && array_key_exists('required', $field) && $field['required']);
} | [
"public",
"function",
"isRequired",
"(",
"$",
"field_key",
")",
"{",
"$",
"field",
"=",
"(",
"is_array",
"(",
"$",
"field_key",
")",
")",
"?",
"$",
"field_key",
":",
"$",
"this",
"->",
"getField",
"(",
"$",
"field_key",
")",
";",
"return",
"(",
"is_a... | Is the field required?
@param mixed $field_key Alternatively, you can pass in the field array
@return bool | [
"Is",
"the",
"field",
"required?"
] | eedcc0df5ec5293b9c1b62a698ba3d9f9230b528 | https://github.com/tacowordpress/tacowordpress/blob/eedcc0df5ec5293b9c1b62a698ba3d9f9230b528/src/Base.php#L808-L812 | train |
treffynnon/Navigator | lib/Treffynnon/Navigator/Coordinate/DmsParser.php | DmsParser.parse | public function parse($coord) {
$coordinate = null;
$matches = array();
preg_match($this->input_format, $coord, $matches);
if (count($matches) == 5) {
$degrees = $matches[1];
$minutes = $matches[2] * (1 / 60);
$seconds = $matches[3] * (1 / 60 * 1 / 60);
$coordinate = '';
if (isset($matches[4])) {
if ($matches[4] == 'S' or $matches[4] == 'W') {
$coordinate = '-';
}
}
$coordinate .= $degrees + $minutes + $seconds;
}
if (is_numeric($coordinate)) {
return deg2rad((float) $coordinate);
}
throw new E\InvalidCoordinateFormatException('The format of "' . $coord . '" cannot be parsed');
} | php | public function parse($coord) {
$coordinate = null;
$matches = array();
preg_match($this->input_format, $coord, $matches);
if (count($matches) == 5) {
$degrees = $matches[1];
$minutes = $matches[2] * (1 / 60);
$seconds = $matches[3] * (1 / 60 * 1 / 60);
$coordinate = '';
if (isset($matches[4])) {
if ($matches[4] == 'S' or $matches[4] == 'W') {
$coordinate = '-';
}
}
$coordinate .= $degrees + $minutes + $seconds;
}
if (is_numeric($coordinate)) {
return deg2rad((float) $coordinate);
}
throw new E\InvalidCoordinateFormatException('The format of "' . $coord . '" cannot be parsed');
} | [
"public",
"function",
"parse",
"(",
"$",
"coord",
")",
"{",
"$",
"coordinate",
"=",
"null",
";",
"$",
"matches",
"=",
"array",
"(",
")",
";",
"preg_match",
"(",
"$",
"this",
"->",
"input_format",
",",
"$",
"coord",
",",
"$",
"matches",
")",
";",
"i... | Used when setting a value in the Coordinate class.
@example parse('10° 5\' 30"N');
@example parse('10 5 30N');
@param string $coord
@return float | [
"Used",
"when",
"setting",
"a",
"value",
"in",
"the",
"Coordinate",
"class",
"."
] | 329e01700e5e3f62361ed328437c524444c9c645 | https://github.com/treffynnon/Navigator/blob/329e01700e5e3f62361ed328437c524444c9c645/lib/Treffynnon/Navigator/Coordinate/DmsParser.php#L41-L63 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.