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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
vanilla/garden-db | src/TableDef.php | TableDef.createColumnDef | private function createColumnDef($dbtype, $nullDefault = false) {
$column = Db::typeDef($dbtype);
if ($column === null) {
throw new \InvalidArgumentException("Unknown type '$dbtype'.", 500);
}
if ($column['dbtype'] === 'bool' && in_array($nullDefault, [true, false], true)) {
// Booleans have a special meaning.
$column['allowNull'] = false;
$column['default'] = $nullDefault;
} elseif ($column['dbtype'] === 'timestamp' && empty($column['default'])) {
$column['default'] = 'current_timestamp';
} elseif ($nullDefault === null || $nullDefault === true) {
$column['allowNull'] = true;
} elseif ($nullDefault === false) {
$column['allowNull'] = false;
} else {
$column['allowNull'] = false;
$column['default'] = $nullDefault;
}
return $column;
} | php | private function createColumnDef($dbtype, $nullDefault = false) {
$column = Db::typeDef($dbtype);
if ($column === null) {
throw new \InvalidArgumentException("Unknown type '$dbtype'.", 500);
}
if ($column['dbtype'] === 'bool' && in_array($nullDefault, [true, false], true)) {
// Booleans have a special meaning.
$column['allowNull'] = false;
$column['default'] = $nullDefault;
} elseif ($column['dbtype'] === 'timestamp' && empty($column['default'])) {
$column['default'] = 'current_timestamp';
} elseif ($nullDefault === null || $nullDefault === true) {
$column['allowNull'] = true;
} elseif ($nullDefault === false) {
$column['allowNull'] = false;
} else {
$column['allowNull'] = false;
$column['default'] = $nullDefault;
}
return $column;
} | [
"private",
"function",
"createColumnDef",
"(",
"$",
"dbtype",
",",
"$",
"nullDefault",
"=",
"false",
")",
"{",
"$",
"column",
"=",
"Db",
"::",
"typeDef",
"(",
"$",
"dbtype",
")",
";",
"if",
"(",
"$",
"column",
"===",
"null",
")",
"{",
"throw",
"new",... | Get an array column def from a structured function call.
@param string $dbtype The database type of the column.
@param mixed $nullDefault Whether or not to allow null or the default value.
null|true
: The column is not required.
false
: The column is required.
Anything else
: The column is required and this is its default.
@return array Returns the column def as an array. | [
"Get",
"an",
"array",
"column",
"def",
"from",
"a",
"structured",
"function",
"call",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/TableDef.php#L94-L117 | train |
vanilla/garden-db | src/TableDef.php | TableDef.setPrimaryKey | public function setPrimaryKey($name, $type = 'int') {
$column = $this->createColumnDef($type, false);
$column['autoIncrement'] = true;
$column['primary'] = true;
$this->columns[$name] = $column;
// Add the pk index.
$this->addIndex(Db::INDEX_PK, $name);
return $this;
} | php | public function setPrimaryKey($name, $type = 'int') {
$column = $this->createColumnDef($type, false);
$column['autoIncrement'] = true;
$column['primary'] = true;
$this->columns[$name] = $column;
// Add the pk index.
$this->addIndex(Db::INDEX_PK, $name);
return $this;
} | [
"public",
"function",
"setPrimaryKey",
"(",
"$",
"name",
",",
"$",
"type",
"=",
"'int'",
")",
"{",
"$",
"column",
"=",
"$",
"this",
"->",
"createColumnDef",
"(",
"$",
"type",
",",
"false",
")",
";",
"$",
"column",
"[",
"'autoIncrement'",
"]",
"=",
"t... | Define the primary key in the database.
@param string $name The name of the column.
@param string $type The datatype for the column.
@return TableDef | [
"Define",
"the",
"primary",
"key",
"in",
"the",
"database",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/TableDef.php#L126-L137 | train |
vanilla/garden-db | src/TableDef.php | TableDef.addIndex | public function addIndex($type, ...$columns) {
if (empty($columns)) {
throw new \InvalidArgumentException("An index must contain at least one column.", 500);
}
$type = strtolower($type);
// Look for a current index row.
$currentIndex = null;
foreach ($this->indexes as $i => $index) {
if ($type !== $index['type']) {
continue;
}
if ($type === Db::INDEX_PK || array_diff($index['columns'], $columns) == []) {
$currentIndex =& $this->indexes[$i];
break;
}
}
if ($currentIndex) {
$currentIndex['columns'] = $columns;
} else {
$indexDef = [
'type' => $type,
'columns' => $columns,
];
$this->indexes[] = $indexDef;
}
return $this;
} | php | public function addIndex($type, ...$columns) {
if (empty($columns)) {
throw new \InvalidArgumentException("An index must contain at least one column.", 500);
}
$type = strtolower($type);
// Look for a current index row.
$currentIndex = null;
foreach ($this->indexes as $i => $index) {
if ($type !== $index['type']) {
continue;
}
if ($type === Db::INDEX_PK || array_diff($index['columns'], $columns) == []) {
$currentIndex =& $this->indexes[$i];
break;
}
}
if ($currentIndex) {
$currentIndex['columns'] = $columns;
} else {
$indexDef = [
'type' => $type,
'columns' => $columns,
];
$this->indexes[] = $indexDef;
}
return $this;
} | [
"public",
"function",
"addIndex",
"(",
"$",
"type",
",",
"...",
"$",
"columns",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"columns",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"An index must contain at least one column.\"",
",",
"500... | Add or update an index.
@param string $type One of the `Db::INDEX_*` constants.
@param string ...$columns The columns in the index.
@return $this | [
"Add",
"or",
"update",
"an",
"index",
"."
] | 2634229fb7a161f649ad371e59a973ccbbe72247 | https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/TableDef.php#L146-L177 | train |
s9e/RegexpBuilder | src/Passes/PromoteSingleStrings.php | PromoteSingleStrings.promoteSingleStrings | protected function promoteSingleStrings(array $string)
{
$newString = [];
foreach ($string as $element)
{
if (is_array($element) && count($element) === 1)
{
$newString = array_merge($newString, $element[0]);
}
else
{
$newString[] = $element;
}
}
return $newString;
} | php | protected function promoteSingleStrings(array $string)
{
$newString = [];
foreach ($string as $element)
{
if (is_array($element) && count($element) === 1)
{
$newString = array_merge($newString, $element[0]);
}
else
{
$newString[] = $element;
}
}
return $newString;
} | [
"protected",
"function",
"promoteSingleStrings",
"(",
"array",
"$",
"string",
")",
"{",
"$",
"newString",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"string",
"as",
"$",
"element",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"element",
")",
"&&",
"count",... | Promote single strings found inside given string
@param array $string Original string
@return array Modified string | [
"Promote",
"single",
"strings",
"found",
"inside",
"given",
"string"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/PromoteSingleStrings.php#L30-L46 | train |
nails/module-auth | admin/controllers/Accounts.php | Accounts.indexCheckboxFilters | protected function indexCheckboxFilters(): array
{
$oGroupModel = Factory::model('UserGroup', 'nails/module-auth');
$aGroups = $oGroupModel->getAll();
return array_merge(
parent::indexCheckboxFilters(),
[
Factory::factory('IndexFilter', 'nails/module-admin')
->setLabel('Group')
->setColumn('group_id')
->addOptions(array_map(function ($oGroup) {
return Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel($oGroup->label)
->setValue($oGroup->id)
->setIsSelected(true);
}, $aGroups)),
Factory::factory('IndexFilter', 'nails/module-admin')
->setLabel('Suspended')
->setColumn('is_suspended')
->addOptions([
Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel('Yes')
->setValue(true),
Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel('No')
->setValue(false)
->setIsSelected(true),
]),
]
);
} | php | protected function indexCheckboxFilters(): array
{
$oGroupModel = Factory::model('UserGroup', 'nails/module-auth');
$aGroups = $oGroupModel->getAll();
return array_merge(
parent::indexCheckboxFilters(),
[
Factory::factory('IndexFilter', 'nails/module-admin')
->setLabel('Group')
->setColumn('group_id')
->addOptions(array_map(function ($oGroup) {
return Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel($oGroup->label)
->setValue($oGroup->id)
->setIsSelected(true);
}, $aGroups)),
Factory::factory('IndexFilter', 'nails/module-admin')
->setLabel('Suspended')
->setColumn('is_suspended')
->addOptions([
Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel('Yes')
->setValue(true),
Factory::factory('IndexFilterOption', 'nails/module-admin')
->setLabel('No')
->setValue(false)
->setIsSelected(true),
]),
]
);
} | [
"protected",
"function",
"indexCheckboxFilters",
"(",
")",
":",
"array",
"{",
"$",
"oGroupModel",
"=",
"Factory",
"::",
"model",
"(",
"'UserGroup'",
",",
"'nails/module-auth'",
")",
";",
"$",
"aGroups",
"=",
"$",
"oGroupModel",
"->",
"getAll",
"(",
")",
";",... | Returns the available checkbox filters
@return array
@throws \Nails\Common\Exception\FactoryException | [
"Returns",
"the",
"available",
"checkbox",
"filters"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/admin/controllers/Accounts.php#L287-L318 | train |
nails/module-auth | admin/controllers/Accounts.php | Accounts.suspend | public function suspend(): void
{
if (!userHasPermission('admin:auth:accounts:suspend')) {
unauthorised();
}
// --------------------------------------------------------------------------
// Get the user's details
$oUri = Factory::service('Uri');
$oInput = Factory::service('Input');
$oSession = Factory::service('Session', 'nails/module-auth');
$oUserModel = Factory::model('User', 'nails/module-auth');
$iUserId = $oUri->segment(5);
$oUser = $oUserModel->getById($iUserId);
$bOldValue = $oUser->is_suspended;
// --------------------------------------------------------------------------
// Non-superusers editing superusers is not cool
if (!isSuperuser() && userHasPermission('superuser', $oUser)) {
$oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
$this->returnToIndex();
}
// --------------------------------------------------------------------------
// Suspend user
$oUserModel->suspend($iUserId);
// --------------------------------------------------------------------------
// Get the user's details, again
$oUser = $oUserModel->getById($iUserId);
$bNewValue = $oUser->is_suspended;
// --------------------------------------------------------------------------
// Define messages
if (!$oUser->is_suspended) {
$oSession->setFlashData(
'error',
lang('accounts_suspend_error', title_case($oUser->first_name . ' ' . $oUser->last_name))
);
} else {
$oSession->setFlashData(
'success',
lang('accounts_suspend_success', title_case($oUser->first_name . ' ' . $oUser->last_name))
);
}
// --------------------------------------------------------------------------
// Update admin changelog
$this->oChangeLogModel->add(
'suspended',
'a',
'user',
$iUserId,
'#' . number_format($iUserId) . ' ' . $oUser->first_name . ' ' . $oUser->last_name,
'admin/auth/accounts/edit/' . $iUserId,
'is_suspended',
$bOldValue,
$bNewValue,
false
);
// --------------------------------------------------------------------------
$this->returnToIndex();
} | php | public function suspend(): void
{
if (!userHasPermission('admin:auth:accounts:suspend')) {
unauthorised();
}
// --------------------------------------------------------------------------
// Get the user's details
$oUri = Factory::service('Uri');
$oInput = Factory::service('Input');
$oSession = Factory::service('Session', 'nails/module-auth');
$oUserModel = Factory::model('User', 'nails/module-auth');
$iUserId = $oUri->segment(5);
$oUser = $oUserModel->getById($iUserId);
$bOldValue = $oUser->is_suspended;
// --------------------------------------------------------------------------
// Non-superusers editing superusers is not cool
if (!isSuperuser() && userHasPermission('superuser', $oUser)) {
$oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
$this->returnToIndex();
}
// --------------------------------------------------------------------------
// Suspend user
$oUserModel->suspend($iUserId);
// --------------------------------------------------------------------------
// Get the user's details, again
$oUser = $oUserModel->getById($iUserId);
$bNewValue = $oUser->is_suspended;
// --------------------------------------------------------------------------
// Define messages
if (!$oUser->is_suspended) {
$oSession->setFlashData(
'error',
lang('accounts_suspend_error', title_case($oUser->first_name . ' ' . $oUser->last_name))
);
} else {
$oSession->setFlashData(
'success',
lang('accounts_suspend_success', title_case($oUser->first_name . ' ' . $oUser->last_name))
);
}
// --------------------------------------------------------------------------
// Update admin changelog
$this->oChangeLogModel->add(
'suspended',
'a',
'user',
$iUserId,
'#' . number_format($iUserId) . ' ' . $oUser->first_name . ' ' . $oUser->last_name,
'admin/auth/accounts/edit/' . $iUserId,
'is_suspended',
$bOldValue,
$bNewValue,
false
);
// --------------------------------------------------------------------------
$this->returnToIndex();
} | [
"public",
"function",
"suspend",
"(",
")",
":",
"void",
"{",
"if",
"(",
"!",
"userHasPermission",
"(",
"'admin:auth:accounts:suspend'",
")",
")",
"{",
"unauthorised",
"(",
")",
";",
"}",
"// --------------------------------------------------------------------------",
"/... | Suspend a user
@throws \Nails\Common\Exception\FactoryException
@throws \Nails\Common\Exception\ModelException | [
"Suspend",
"a",
"user"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/admin/controllers/Accounts.php#L1069-L1139 | train |
nails/module-auth | admin/controllers/Accounts.php | Accounts.delete_profile_img | public function delete_profile_img(): void
{
$oUri = Factory::service('Uri');
if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
$oSession = Factory::service('Session', 'nails/module-auth');
$oUserModel = Factory::model('User', 'nails/module-auth');
$iUserId = $oUri->segment(5);
$oUser = $oUserModel->getById($iUserId);
$sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/auth/accounts/edit/' . $iUserId;
// --------------------------------------------------------------------------
if (!$oUser) {
$oSession->setFlashData('error', lang('accounts_delete_img_error_noid'));
redirect('admin/auth/accounts');
} else {
// Non-superusers editing superusers is not cool
if (!isSuperuser() && userHasPermission('superuser', $oUser)) {
$oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
redirect($sReturnTo);
}
// --------------------------------------------------------------------------
if ($oUser->profile_img) {
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
if ($oCdn->objectDelete($oUser->profile_img, 'profile-images')) {
// Update the user
$oUserModel->update($iUserId, ['profile_img' => null]);
$sStatus = 'notice';
$sMessage = lang('accounts_delete_img_success');
} else {
$sStatus = 'error';
$sMessage = lang('accounts_delete_img_error', implode('", "', $oCdn->getErrors()));
}
} else {
$sStatus = 'notice';
$sMessage = lang('accounts_delete_img_error_noimg');
}
$oSession->setFlashData($sStatus, $sMessage);
// --------------------------------------------------------------------------
redirect($sReturnTo);
}
} | php | public function delete_profile_img(): void
{
$oUri = Factory::service('Uri');
if ($oUri->segment(5) != activeUser('id') && !userHasPermission('admin:auth:accounts:editOthers')) {
unauthorised();
}
// --------------------------------------------------------------------------
$oInput = Factory::service('Input');
$oSession = Factory::service('Session', 'nails/module-auth');
$oUserModel = Factory::model('User', 'nails/module-auth');
$iUserId = $oUri->segment(5);
$oUser = $oUserModel->getById($iUserId);
$sReturnTo = $oInput->get('return_to') ? $oInput->get('return_to') : 'admin/auth/accounts/edit/' . $iUserId;
// --------------------------------------------------------------------------
if (!$oUser) {
$oSession->setFlashData('error', lang('accounts_delete_img_error_noid'));
redirect('admin/auth/accounts');
} else {
// Non-superusers editing superusers is not cool
if (!isSuperuser() && userHasPermission('superuser', $oUser)) {
$oSession->setFlashData('error', lang('accounts_edit_error_noteditable'));
redirect($sReturnTo);
}
// --------------------------------------------------------------------------
if ($oUser->profile_img) {
$oCdn = Factory::service('Cdn', 'nails/module-cdn');
if ($oCdn->objectDelete($oUser->profile_img, 'profile-images')) {
// Update the user
$oUserModel->update($iUserId, ['profile_img' => null]);
$sStatus = 'notice';
$sMessage = lang('accounts_delete_img_success');
} else {
$sStatus = 'error';
$sMessage = lang('accounts_delete_img_error', implode('", "', $oCdn->getErrors()));
}
} else {
$sStatus = 'notice';
$sMessage = lang('accounts_delete_img_error_noimg');
}
$oSession->setFlashData($sStatus, $sMessage);
// --------------------------------------------------------------------------
redirect($sReturnTo);
}
} | [
"public",
"function",
"delete_profile_img",
"(",
")",
":",
"void",
"{",
"$",
"oUri",
"=",
"Factory",
"::",
"service",
"(",
"'Uri'",
")",
";",
"if",
"(",
"$",
"oUri",
"->",
"segment",
"(",
"5",
")",
"!=",
"activeUser",
"(",
"'id'",
")",
"&&",
"!",
"... | Delete a user's profile image
@throws \Nails\Common\Exception\FactoryException | [
"Delete",
"a",
"user",
"s",
"profile",
"image"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/admin/controllers/Accounts.php#L1226-L1287 | train |
mirko-pagliai/me-cms | src/Command/GroupsCommand.php | GroupsCommand.execute | public function execute(Arguments $args, ConsoleIo $io)
{
$this->loadModel('MeCms.UsersGroups');
$groups = $this->UsersGroups->find()->map(function (UsersGroup $group) {
return $group->extract(['id', 'name', 'label', 'user_count']);
});
//Checks for user groups
if ($groups->isEmpty()) {
$io->error(__d('me_cms', 'There are no user groups'));
return null;
}
//Sets header and prints as table
$header = [I18N_ID, I18N_NAME, I18N_LABEL, I18N_USERS];
$io->helper('table')->output(array_merge([$header], $groups->toList()));
return null;
} | php | public function execute(Arguments $args, ConsoleIo $io)
{
$this->loadModel('MeCms.UsersGroups');
$groups = $this->UsersGroups->find()->map(function (UsersGroup $group) {
return $group->extract(['id', 'name', 'label', 'user_count']);
});
//Checks for user groups
if ($groups->isEmpty()) {
$io->error(__d('me_cms', 'There are no user groups'));
return null;
}
//Sets header and prints as table
$header = [I18N_ID, I18N_NAME, I18N_LABEL, I18N_USERS];
$io->helper('table')->output(array_merge([$header], $groups->toList()));
return null;
} | [
"public",
"function",
"execute",
"(",
"Arguments",
"$",
"args",
",",
"ConsoleIo",
"$",
"io",
")",
"{",
"$",
"this",
"->",
"loadModel",
"(",
"'MeCms.UsersGroups'",
")",
";",
"$",
"groups",
"=",
"$",
"this",
"->",
"UsersGroups",
"->",
"find",
"(",
")",
"... | Lists user groups
@param Arguments $args The command arguments
@param ConsoleIo $io The console io
@return null|int The exit code or null for success | [
"Lists",
"user",
"groups"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/GroupsCommand.php#L43-L63 | train |
mirko-pagliai/me-cms | src/Controller/Traits/CheckLastSearchTrait.php | CheckLastSearchTrait.checkLastSearch | protected function checkLastSearch($id = false)
{
$interval = getConfig('security.search_interval');
if (!$interval) {
return true;
}
$id = $id ? md5($id) : false;
$lastSearch = $this->request->getSession()->read('last_search');
if ($lastSearch) {
//Checks if it's the same search
if ($id && !empty($lastSearch['id']) && $id === $lastSearch['id']) {
return true;
//Checks if the interval has not yet expired
} elseif (($lastSearch['time'] + $interval) > time()) {
return false;
}
}
$this->request->getSession()->write('last_search', compact('id') + ['time' => time()]);
return true;
} | php | protected function checkLastSearch($id = false)
{
$interval = getConfig('security.search_interval');
if (!$interval) {
return true;
}
$id = $id ? md5($id) : false;
$lastSearch = $this->request->getSession()->read('last_search');
if ($lastSearch) {
//Checks if it's the same search
if ($id && !empty($lastSearch['id']) && $id === $lastSearch['id']) {
return true;
//Checks if the interval has not yet expired
} elseif (($lastSearch['time'] + $interval) > time()) {
return false;
}
}
$this->request->getSession()->write('last_search', compact('id') + ['time' => time()]);
return true;
} | [
"protected",
"function",
"checkLastSearch",
"(",
"$",
"id",
"=",
"false",
")",
"{",
"$",
"interval",
"=",
"getConfig",
"(",
"'security.search_interval'",
")",
";",
"if",
"(",
"!",
"$",
"interval",
")",
"{",
"return",
"true",
";",
"}",
"$",
"id",
"=",
"... | Checks if the latest search has been executed out of the minimum
interval
@param string $id Query ID
@return bool | [
"Checks",
"if",
"the",
"latest",
"search",
"has",
"been",
"executed",
"out",
"of",
"the",
"minimum",
"interval"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Traits/CheckLastSearchTrait.php#L28-L52 | train |
gregorybesson/PlaygroundUser | src/DataFixtures/ORM/LoadRoleData.php | LoadRoleData.load | public function load(ObjectManager $manager)
{
$userRole = new Role();
$userRole->setRoleId('user');
$manager->persist($userRole);
$manager->flush();
$adminRole = new Role();
$adminRole->setRoleId('admin');
$adminRole->setParent($userRole);
$manager->persist($adminRole);
$manager->flush();
$supervisorRole = new Role();
$supervisorRole->setRoleId('supervisor');
$supervisorRole->setParent($userRole);
$manager->persist($supervisorRole);
$manager->flush();
$gameManagerRole = new Role();
$gameManagerRole->setRoleId('game-manager');
$gameManagerRole->setParent($supervisorRole);
$manager->persist($gameManagerRole);
$manager->flush();
// store reference to admin role for User relation to Role
$this->addReference('admin-role', $adminRole);
$this->addReference('supervisor-role', $supervisorRole);
$this->addReference('game-role', $gameManagerRole);
} | php | public function load(ObjectManager $manager)
{
$userRole = new Role();
$userRole->setRoleId('user');
$manager->persist($userRole);
$manager->flush();
$adminRole = new Role();
$adminRole->setRoleId('admin');
$adminRole->setParent($userRole);
$manager->persist($adminRole);
$manager->flush();
$supervisorRole = new Role();
$supervisorRole->setRoleId('supervisor');
$supervisorRole->setParent($userRole);
$manager->persist($supervisorRole);
$manager->flush();
$gameManagerRole = new Role();
$gameManagerRole->setRoleId('game-manager');
$gameManagerRole->setParent($supervisorRole);
$manager->persist($gameManagerRole);
$manager->flush();
// store reference to admin role for User relation to Role
$this->addReference('admin-role', $adminRole);
$this->addReference('supervisor-role', $supervisorRole);
$this->addReference('game-role', $gameManagerRole);
} | [
"public",
"function",
"load",
"(",
"ObjectManager",
"$",
"manager",
")",
"{",
"$",
"userRole",
"=",
"new",
"Role",
"(",
")",
";",
"$",
"userRole",
"->",
"setRoleId",
"(",
"'user'",
")",
";",
"$",
"manager",
"->",
"persist",
"(",
"$",
"userRole",
")",
... | Load Role types
@param \Doctrine\Common\Persistence\ObjectManager $manager | [
"Load",
"Role",
"types"
] | b07c9969b5da1c173001fbba343f0a006d87eb8e | https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/DataFixtures/ORM/LoadRoleData.php#L23-L56 | train |
PitonCMS/Engine | app/Controllers/FrontController.php | FrontController.submitMessage | public function submitMessage()
{
$messageMapper = ($this->container->dataMapper)('MessageMapper');
$email = $this->container->emailHandler;
// Check honepot and if clean, then submit message
if ('alt@example.com' === $this->request->getParsedBodyParam('alt-email')) {
$message = $messageMapper->make();
$message->name = $this->request->getParsedBodyParam('name');
$message->email = $this->request->getParsedBodyParam('email');
$message->message = $this->request->getParsedBodyParam('message');
$messageMapper->save($message);
// Send message to workflow email
$siteName = empty($this->siteSettings['displayName']) ? 'PitonCMS' : $this->siteSettings['displayName'];
$email->setTo($this->siteSettings['contactFormEmail'], '')
->setSubject("New Contact Message to $siteName")
->setMessage("From: {$message->email}\n\n{$message->message}")
->send();
}
// Set the response type and return
$r = $this->response->withHeader('Content-Type', 'application/json');
return $r->write(json_encode(["response" => $this->siteSettings['contactFormAcknowledgement']]));
} | php | public function submitMessage()
{
$messageMapper = ($this->container->dataMapper)('MessageMapper');
$email = $this->container->emailHandler;
// Check honepot and if clean, then submit message
if ('alt@example.com' === $this->request->getParsedBodyParam('alt-email')) {
$message = $messageMapper->make();
$message->name = $this->request->getParsedBodyParam('name');
$message->email = $this->request->getParsedBodyParam('email');
$message->message = $this->request->getParsedBodyParam('message');
$messageMapper->save($message);
// Send message to workflow email
$siteName = empty($this->siteSettings['displayName']) ? 'PitonCMS' : $this->siteSettings['displayName'];
$email->setTo($this->siteSettings['contactFormEmail'], '')
->setSubject("New Contact Message to $siteName")
->setMessage("From: {$message->email}\n\n{$message->message}")
->send();
}
// Set the response type and return
$r = $this->response->withHeader('Content-Type', 'application/json');
return $r->write(json_encode(["response" => $this->siteSettings['contactFormAcknowledgement']]));
} | [
"public",
"function",
"submitMessage",
"(",
")",
"{",
"$",
"messageMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'MessageMapper'",
")",
";",
"$",
"email",
"=",
"$",
"this",
"->",
"container",
"->",
"emailHandler",
";",
... | Submit Contact Message
@param POST array | [
"Submit",
"Contact",
"Message"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/FrontController.php#L57-L81 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.add | public function add($char, $expr)
{
$split = $this->input->split($char);
if (count($split) !== 1)
{
throw new InvalidArgumentException('Meta-characters must be represented by exactly one character');
}
if (@preg_match('(' . $expr . ')u', '') === false)
{
throw new InvalidArgumentException("Invalid expression '" . $expr . "'");
}
$inputValue = $split[0];
$metaValue = $this->computeValue($expr);
$this->exprs[$metaValue] = $expr;
$this->meta[$inputValue] = $metaValue;
} | php | public function add($char, $expr)
{
$split = $this->input->split($char);
if (count($split) !== 1)
{
throw new InvalidArgumentException('Meta-characters must be represented by exactly one character');
}
if (@preg_match('(' . $expr . ')u', '') === false)
{
throw new InvalidArgumentException("Invalid expression '" . $expr . "'");
}
$inputValue = $split[0];
$metaValue = $this->computeValue($expr);
$this->exprs[$metaValue] = $expr;
$this->meta[$inputValue] = $metaValue;
} | [
"public",
"function",
"add",
"(",
"$",
"char",
",",
"$",
"expr",
")",
"{",
"$",
"split",
"=",
"$",
"this",
"->",
"input",
"->",
"split",
"(",
"$",
"char",
")",
";",
"if",
"(",
"count",
"(",
"$",
"split",
")",
"!==",
"1",
")",
"{",
"throw",
"n... | Add a meta-character to the list
@param string $char Meta-character
@param string $expr Regular expression
@return void | [
"Add",
"a",
"meta",
"-",
"character",
"to",
"the",
"list"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L56-L73 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.getExpression | public function getExpression($metaValue)
{
if (!isset($this->exprs[$metaValue]))
{
throw new InvalidArgumentException('Invalid meta value ' . $metaValue);
}
return $this->exprs[$metaValue];
} | php | public function getExpression($metaValue)
{
if (!isset($this->exprs[$metaValue]))
{
throw new InvalidArgumentException('Invalid meta value ' . $metaValue);
}
return $this->exprs[$metaValue];
} | [
"public",
"function",
"getExpression",
"(",
"$",
"metaValue",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"exprs",
"[",
"$",
"metaValue",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Invalid meta value '",
".",
"$",... | Get the expression associated with a meta value
@param integer $metaValue
@return string | [
"Get",
"the",
"expression",
"associated",
"with",
"a",
"meta",
"value"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L81-L89 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.replaceMeta | public function replaceMeta(array $strings)
{
foreach ($strings as &$string)
{
foreach ($string as &$value)
{
if (isset($this->meta[$value]))
{
$value = $this->meta[$value];
}
}
}
return $strings;
} | php | public function replaceMeta(array $strings)
{
foreach ($strings as &$string)
{
foreach ($string as &$value)
{
if (isset($this->meta[$value]))
{
$value = $this->meta[$value];
}
}
}
return $strings;
} | [
"public",
"function",
"replaceMeta",
"(",
"array",
"$",
"strings",
")",
"{",
"foreach",
"(",
"$",
"strings",
"as",
"&",
"$",
"string",
")",
"{",
"foreach",
"(",
"$",
"string",
"as",
"&",
"$",
"value",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",... | Replace values from meta-characters in a list of strings with their meta value
@param array[] $strings
@return array[] | [
"Replace",
"values",
"from",
"meta",
"-",
"characters",
"in",
"a",
"list",
"of",
"strings",
"with",
"their",
"meta",
"value"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L119-L133 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.computeValue | protected function computeValue($expr)
{
$properties = [
'exprIsChar' => self::IS_CHAR,
'exprIsQuantifiable' => self::IS_QUANTIFIABLE
];
$value = (1 + count($this->meta)) * -pow(2, count($properties));
foreach ($properties as $methodName => $bitValue)
{
if ($this->$methodName($expr))
{
$value |= $bitValue;
}
}
return $value;
} | php | protected function computeValue($expr)
{
$properties = [
'exprIsChar' => self::IS_CHAR,
'exprIsQuantifiable' => self::IS_QUANTIFIABLE
];
$value = (1 + count($this->meta)) * -pow(2, count($properties));
foreach ($properties as $methodName => $bitValue)
{
if ($this->$methodName($expr))
{
$value |= $bitValue;
}
}
return $value;
} | [
"protected",
"function",
"computeValue",
"(",
"$",
"expr",
")",
"{",
"$",
"properties",
"=",
"[",
"'exprIsChar'",
"=>",
"self",
"::",
"IS_CHAR",
",",
"'exprIsQuantifiable'",
"=>",
"self",
"::",
"IS_QUANTIFIABLE",
"]",
";",
"$",
"value",
"=",
"(",
"1",
"+",... | Compute and return a value for given expression
Values are meant to be a unique negative integer. The last 2 bits indicate whether the
expression is quantifiable and/or represents a single character.
@param string $expr Regular expression
@return integer | [
"Compute",
"and",
"return",
"a",
"value",
"for",
"given",
"expression"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L144-L160 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.exprIsQuantifiable | protected function exprIsQuantifiable($expr)
{
$regexps = [
// A dot or \R
'(^(?:\\.|\\\\R)$)D',
// A character class
'(^\\[\\^?(?:([^\\\\\\]]|\\\\.)(?:-(?-1))?)++\\]$)D'
];
return $this->matchesAny($expr, $regexps) || $this->exprIsChar($expr);
} | php | protected function exprIsQuantifiable($expr)
{
$regexps = [
// A dot or \R
'(^(?:\\.|\\\\R)$)D',
// A character class
'(^\\[\\^?(?:([^\\\\\\]]|\\\\.)(?:-(?-1))?)++\\]$)D'
];
return $this->matchesAny($expr, $regexps) || $this->exprIsChar($expr);
} | [
"protected",
"function",
"exprIsQuantifiable",
"(",
"$",
"expr",
")",
"{",
"$",
"regexps",
"=",
"[",
"// A dot or \\R",
"'(^(?:\\\\.|\\\\\\\\R)$)D'",
",",
"// A character class",
"'(^\\\\[\\\\^?(?:([^\\\\\\\\\\\\]]|\\\\\\\\.)(?:-(?-1))?)++\\\\]$)D'",
"]",
";",
"return",
"$",
... | Test whether given expression is quantifiable
@param string $expr
@return bool | [
"Test",
"whether",
"given",
"expression",
"is",
"quantifiable"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L190-L201 | train |
s9e/RegexpBuilder | src/MetaCharacters.php | MetaCharacters.matchesAny | protected function matchesAny($expr, array $regexps)
{
foreach ($regexps as $regexp)
{
if (preg_match($regexp, $expr))
{
return true;
}
}
return false;
} | php | protected function matchesAny($expr, array $regexps)
{
foreach ($regexps as $regexp)
{
if (preg_match($regexp, $expr))
{
return true;
}
}
return false;
} | [
"protected",
"function",
"matchesAny",
"(",
"$",
"expr",
",",
"array",
"$",
"regexps",
")",
"{",
"foreach",
"(",
"$",
"regexps",
"as",
"$",
"regexp",
")",
"{",
"if",
"(",
"preg_match",
"(",
"$",
"regexp",
",",
"$",
"expr",
")",
")",
"{",
"return",
... | Test whether given expression matches any of the given regexps
@param string $expr
@param string[] $regexps
@return bool | [
"Test",
"whether",
"given",
"expression",
"matches",
"any",
"of",
"the",
"given",
"regexps"
] | 59d0167a909659d718f53964f7653d2c83a5f8fe | https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/MetaCharacters.php#L210-L221 | train |
drdplusinfo/tables | DrdPlus/Tables/Theurgist/Spells/Formula.php | Formula.getCurrentRealmsAffections | public function getCurrentRealmsAffections(): array
{
$realmsAffections = [];
foreach ($this->getRealmsAffectionsSum() as $periodName => $periodSum) {
$realmsAffections[$periodName] = new RealmsAffection([$periodSum, $periodName]);
}
return $realmsAffections;
} | php | public function getCurrentRealmsAffections(): array
{
$realmsAffections = [];
foreach ($this->getRealmsAffectionsSum() as $periodName => $periodSum) {
$realmsAffections[$periodName] = new RealmsAffection([$periodSum, $periodName]);
}
return $realmsAffections;
} | [
"public",
"function",
"getCurrentRealmsAffections",
"(",
")",
":",
"array",
"{",
"$",
"realmsAffections",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getRealmsAffectionsSum",
"(",
")",
"as",
"$",
"periodName",
"=>",
"$",
"periodSum",
")",
"{",
... | Daily, monthly and lifetime affections of realms
@return array|RealmsAffection[] | [
"Daily",
"monthly",
"and",
"lifetime",
"affections",
"of",
"realms"
] | 7a577ddbd1748369eec4e84effcc92ffcb54d1f3 | https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Theurgist/Spells/Formula.php#L245-L253 | train |
drdplusinfo/tables | DrdPlus/Tables/Theurgist/Spells/Formula.php | Formula.getCurrentSpellRadius | public function getCurrentSpellRadius(): ?SpellRadius
{
$radiusWithAddition = $this->getRadiusWithAddition();
if (!$radiusWithAddition) {
return null;
}
$radiusModifiersChange = $this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_RADIUS);
if (!$radiusModifiersChange) {
return new SpellRadius([$radiusWithAddition->getValue(), 0], $this->tables);
}
return new SpellRadius([$radiusWithAddition->getValue() + $radiusModifiersChange, 0], $this->tables);
} | php | public function getCurrentSpellRadius(): ?SpellRadius
{
$radiusWithAddition = $this->getRadiusWithAddition();
if (!$radiusWithAddition) {
return null;
}
$radiusModifiersChange = $this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_RADIUS);
if (!$radiusModifiersChange) {
return new SpellRadius([$radiusWithAddition->getValue(), 0], $this->tables);
}
return new SpellRadius([$radiusWithAddition->getValue() + $radiusModifiersChange, 0], $this->tables);
} | [
"public",
"function",
"getCurrentSpellRadius",
"(",
")",
":",
"?",
"SpellRadius",
"{",
"$",
"radiusWithAddition",
"=",
"$",
"this",
"->",
"getRadiusWithAddition",
"(",
")",
";",
"if",
"(",
"!",
"$",
"radiusWithAddition",
")",
"{",
"return",
"null",
";",
"}",... | Final radius including direct formula change and all its active traits and modifiers.
@return SpellRadius|null | [
"Final",
"radius",
"including",
"direct",
"formula",
"change",
"and",
"all",
"its",
"active",
"traits",
"and",
"modifiers",
"."
] | 7a577ddbd1748369eec4e84effcc92ffcb54d1f3 | https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Theurgist/Spells/Formula.php#L312-L325 | train |
drdplusinfo/tables | DrdPlus/Tables/Theurgist/Spells/Formula.php | Formula.getRadiusWithAddition | private function getRadiusWithAddition(): ?SpellRadius
{
$baseSpellRadius = $this->tables->getFormulasTable()->getSpellRadius($this->formulaCode);
if ($baseSpellRadius === null) {
return null;
}
return $baseSpellRadius->getWithAddition($this->formulaSpellParameterChanges[FormulaMutableSpellParameterCode::SPELL_RADIUS]);
} | php | private function getRadiusWithAddition(): ?SpellRadius
{
$baseSpellRadius = $this->tables->getFormulasTable()->getSpellRadius($this->formulaCode);
if ($baseSpellRadius === null) {
return null;
}
return $baseSpellRadius->getWithAddition($this->formulaSpellParameterChanges[FormulaMutableSpellParameterCode::SPELL_RADIUS]);
} | [
"private",
"function",
"getRadiusWithAddition",
"(",
")",
":",
"?",
"SpellRadius",
"{",
"$",
"baseSpellRadius",
"=",
"$",
"this",
"->",
"tables",
"->",
"getFormulasTable",
"(",
")",
"->",
"getSpellRadius",
"(",
"$",
"this",
"->",
"formulaCode",
")",
";",
"if... | Formula radius extended by direct formula change
@return SpellRadius|null | [
"Formula",
"radius",
"extended",
"by",
"direct",
"formula",
"change"
] | 7a577ddbd1748369eec4e84effcc92ffcb54d1f3 | https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Theurgist/Spells/Formula.php#L332-L340 | train |
drdplusinfo/tables | DrdPlus/Tables/Theurgist/Spells/Formula.php | Formula.getCurrentSpellAttack | public function getCurrentSpellAttack(): ?SpellAttack
{
$spellAttackWithAddition = $this->getSpellAttackWithAddition();
if (!$spellAttackWithAddition) {
return null;
}
return new SpellAttack(
[
$spellAttackWithAddition->getValue()
+ (int)$this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_ATTACK),
0 // no addition
],
Tables::getIt()
);
} | php | public function getCurrentSpellAttack(): ?SpellAttack
{
$spellAttackWithAddition = $this->getSpellAttackWithAddition();
if (!$spellAttackWithAddition) {
return null;
}
return new SpellAttack(
[
$spellAttackWithAddition->getValue()
+ (int)$this->getParameterBonusFromModifiers(ModifierMutableSpellParameterCode::SPELL_ATTACK),
0 // no addition
],
Tables::getIt()
);
} | [
"public",
"function",
"getCurrentSpellAttack",
"(",
")",
":",
"?",
"SpellAttack",
"{",
"$",
"spellAttackWithAddition",
"=",
"$",
"this",
"->",
"getSpellAttackWithAddition",
"(",
")",
";",
"if",
"(",
"!",
"$",
"spellAttackWithAddition",
")",
"{",
"return",
"null"... | Attack can be only increased, not added.
@return SpellAttack|null | [
"Attack",
"can",
"be",
"only",
"increased",
"not",
"added",
"."
] | 7a577ddbd1748369eec4e84effcc92ffcb54d1f3 | https://github.com/drdplusinfo/tables/blob/7a577ddbd1748369eec4e84effcc92ffcb54d1f3/DrdPlus/Tables/Theurgist/Spells/Formula.php#L423-L438 | train |
ommu/mod-core | models/OmmuMenuCategory.php | OmmuMenuCategory.getCategory | public static function getCategory($publish=null, $array=true)
{
$criteria=new CDbCriteria;
if($publish != null)
$criteria->compare('t.publish', $publish);
$model = self::model()->findAll($criteria);
if($array == true) {
$items = array();
if($model != null) {
foreach($model as $key => $val) {
$items[$val->cat_id] = $val->title->message;
}
return $items;
} else
return false;
} else
return $model;
} | php | public static function getCategory($publish=null, $array=true)
{
$criteria=new CDbCriteria;
if($publish != null)
$criteria->compare('t.publish', $publish);
$model = self::model()->findAll($criteria);
if($array == true) {
$items = array();
if($model != null) {
foreach($model as $key => $val) {
$items[$val->cat_id] = $val->title->message;
}
return $items;
} else
return false;
} else
return $model;
} | [
"public",
"static",
"function",
"getCategory",
"(",
"$",
"publish",
"=",
"null",
",",
"$",
"array",
"=",
"true",
")",
"{",
"$",
"criteria",
"=",
"new",
"CDbCriteria",
";",
"if",
"(",
"$",
"publish",
"!=",
"null",
")",
"$",
"criteria",
"->",
"compare",
... | getCategory
0 = unpublish
1 = publish | [
"getCategory",
"0",
"=",
"unpublish",
"1",
"=",
"publish"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/models/OmmuMenuCategory.php#L348-L367 | train |
k3ssen/GeneratorBundle | MetaData/MetaEntityFactory.php | MetaEntityFactory.addMissingProperty | public function addMissingProperty(MetaEntityInterface $metaEntity, RelationMetaPropertyInterface $property)
{
$inversedBy = $property->getInversedBy();
$mappedBy = $property->getMappedBy();
if ($newPropertyName = $mappedBy ?: $inversedBy) {
$inversedType = MetaPropertyFactory::getInversedType($property->getOrmType());
/** @var RelationMetaPropertyInterface $newProperty */
$newProperty = $this->metaPropertyFactory->createMetaProperty(
$metaEntity,
$inversedType,
$newPropertyName
);
$newProperty->setTargetEntity($property->getMetaEntity());
if ($inversedBy) {
$newProperty->setMappedBy($property->getName());
} else {
$newProperty->setInversedBy($property->getName());
}
}
} | php | public function addMissingProperty(MetaEntityInterface $metaEntity, RelationMetaPropertyInterface $property)
{
$inversedBy = $property->getInversedBy();
$mappedBy = $property->getMappedBy();
if ($newPropertyName = $mappedBy ?: $inversedBy) {
$inversedType = MetaPropertyFactory::getInversedType($property->getOrmType());
/** @var RelationMetaPropertyInterface $newProperty */
$newProperty = $this->metaPropertyFactory->createMetaProperty(
$metaEntity,
$inversedType,
$newPropertyName
);
$newProperty->setTargetEntity($property->getMetaEntity());
if ($inversedBy) {
$newProperty->setMappedBy($property->getName());
} else {
$newProperty->setInversedBy($property->getName());
}
}
} | [
"public",
"function",
"addMissingProperty",
"(",
"MetaEntityInterface",
"$",
"metaEntity",
",",
"RelationMetaPropertyInterface",
"$",
"property",
")",
"{",
"$",
"inversedBy",
"=",
"$",
"property",
"->",
"getInversedBy",
"(",
")",
";",
"$",
"mappedBy",
"=",
"$",
... | Adds missing field for inversedBy or mappedBy | [
"Adds",
"missing",
"field",
"for",
"inversedBy",
"or",
"mappedBy"
] | 2229b54d69ab7782eb722ee483607886f94849c8 | https://github.com/k3ssen/GeneratorBundle/blob/2229b54d69ab7782eb722ee483607886f94849c8/MetaData/MetaEntityFactory.php#L165-L184 | train |
mirko-pagliai/me-cms | src/View/Helper/AuthHelper.php | AuthHelper.user | public function user($key = null)
{
if (empty($this->user)) {
return null;
}
return $key ? Hash::get($this->user, $key) : $this->user;
} | php | public function user($key = null)
{
if (empty($this->user)) {
return null;
}
return $key ? Hash::get($this->user, $key) : $this->user;
} | [
"public",
"function",
"user",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"user",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"key",
"?",
"Hash",
"::",
"get",
"(",
"$",
"this",
"->",
"user",... | Get the current user from storage
@param string|null $key Field to retrieve. Leave null to get entire User
record
@return mixed|null Either User record or null if no user is logged in,
or retrieved field if key is specified
@uses $user | [
"Get",
"the",
"current",
"user",
"from",
"storage"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/AuthHelper.php#L102-L109 | train |
mirko-pagliai/me-cms | src/Controller/AppController.php | AppController.isAuthorized | public function isAuthorized($user = null)
{
//Any registered user can access public functions
if (!$this->request->getParam('prefix')) {
return true;
}
//Only admin and managers can access all admin actions
if ($this->request->isAdmin()) {
return $this->Auth->isGroup(['admin', 'manager']);
}
//Default deny
return false;
} | php | public function isAuthorized($user = null)
{
//Any registered user can access public functions
if (!$this->request->getParam('prefix')) {
return true;
}
//Only admin and managers can access all admin actions
if ($this->request->isAdmin()) {
return $this->Auth->isGroup(['admin', 'manager']);
}
//Default deny
return false;
} | [
"public",
"function",
"isAuthorized",
"(",
"$",
"user",
"=",
"null",
")",
"{",
"//Any registered user can access public functions",
"if",
"(",
"!",
"$",
"this",
"->",
"request",
"->",
"getParam",
"(",
"'prefix'",
")",
")",
"{",
"return",
"true",
";",
"}",
"/... | Checks if the user is authorized for the request
@param array $user The user to check the authorization of. If empty
the user in the session will be used
@return bool `true` if the user is authorized, otherwise `false`
@uses MeCms\Controller\Component\AuthComponent::isGroup() | [
"Checks",
"if",
"the",
"user",
"is",
"authorized",
"for",
"the",
"request"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/AppController.php#L120-L134 | train |
mirko-pagliai/me-cms | src/Controller/AppController.php | AppController.setUploadError | protected function setUploadError($error)
{
$this->response = $this->response->withStatus(500);
$this->set(compact('error'));
$this->set('_serialize', ['error']);
} | php | protected function setUploadError($error)
{
$this->response = $this->response->withStatus(500);
$this->set(compact('error'));
$this->set('_serialize', ['error']);
} | [
"protected",
"function",
"setUploadError",
"(",
"$",
"error",
")",
"{",
"$",
"this",
"->",
"response",
"=",
"$",
"this",
"->",
"response",
"->",
"withStatus",
"(",
"500",
")",
";",
"$",
"this",
"->",
"set",
"(",
"compact",
"(",
"'error'",
")",
")",
"... | Internal method to set an upload error.
It saves the error as view var that `JsonView` should serialize and sets
the response status code to 500.
@param string $error Error message
@return void
@since 2.18.1 | [
"Internal",
"method",
"to",
"set",
"an",
"upload",
"error",
"."
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/AppController.php#L165-L171 | train |
PitonCMS/Engine | app/Controllers/AdminPageController.php | AdminPageController.newElementForm | public function newElementForm()
{
$parsedBody = $this->request->getParsedBody();
$form['block_key'] = $parsedBody['blockKey'];
$form['definition'] = $parsedBody['elementType'];
$form['element_sort'] = 1;
// Only include element type options if the string is not empty
if (!empty($parsedBody['elementTypeOptions'])) {
$form['elementTypeOptions'] = explode(',', $parsedBody['elementTypeOptions']);
}
$template = '{% import "@admin/editElementMacro.html" as form %}';
$template .= ' {{ form.elementForm(element, element.block_key, element.elementTypeOptions) }}';
$elementFormHtml = $this->container->view->fetchFromString($template, ['element' => $form]);
// Set the response type
$r = $this->response->withHeader('Content-Type', 'application/json');
return $r->write(json_encode(["html" => $elementFormHtml]));
} | php | public function newElementForm()
{
$parsedBody = $this->request->getParsedBody();
$form['block_key'] = $parsedBody['blockKey'];
$form['definition'] = $parsedBody['elementType'];
$form['element_sort'] = 1;
// Only include element type options if the string is not empty
if (!empty($parsedBody['elementTypeOptions'])) {
$form['elementTypeOptions'] = explode(',', $parsedBody['elementTypeOptions']);
}
$template = '{% import "@admin/editElementMacro.html" as form %}';
$template .= ' {{ form.elementForm(element, element.block_key, element.elementTypeOptions) }}';
$elementFormHtml = $this->container->view->fetchFromString($template, ['element' => $form]);
// Set the response type
$r = $this->response->withHeader('Content-Type', 'application/json');
return $r->write(json_encode(["html" => $elementFormHtml]));
} | [
"public",
"function",
"newElementForm",
"(",
")",
"{",
"$",
"parsedBody",
"=",
"$",
"this",
"->",
"request",
"->",
"getParsedBody",
"(",
")",
";",
"$",
"form",
"[",
"'block_key'",
"]",
"=",
"$",
"parsedBody",
"[",
"'blockKey'",
"]",
";",
"$",
"form",
"... | New Element Form
Renders new element form with initial values, and returns via Ajax to browser.
At a minimum, the element form is expecting these values:
- blockKey
- elementTypeDefault
- elementSort
- elementTypeOptions | optional, comma separated list of approved element types | [
"New",
"Element",
"Form"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminPageController.php#L263-L284 | train |
nails/module-auth | src/Model/User/AccessToken.php | AccessToken.revoke | public function revoke($iUserId, $mToken)
{
if (is_string($mToken)) {
$oToken = $this->getByToken($mToken);
} else {
$oToken = $mToken;
}
if ($oToken) {
if ($oToken->user_id === $iUserId) {
return $this->delete($oToken->id);
} else {
$this->setError('Not authorised to revoke that token.');
return false;
}
} else {
return false;
}
} | php | public function revoke($iUserId, $mToken)
{
if (is_string($mToken)) {
$oToken = $this->getByToken($mToken);
} else {
$oToken = $mToken;
}
if ($oToken) {
if ($oToken->user_id === $iUserId) {
return $this->delete($oToken->id);
} else {
$this->setError('Not authorised to revoke that token.');
return false;
}
} else {
return false;
}
} | [
"public",
"function",
"revoke",
"(",
"$",
"iUserId",
",",
"$",
"mToken",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"mToken",
")",
")",
"{",
"$",
"oToken",
"=",
"$",
"this",
"->",
"getByToken",
"(",
"$",
"mToken",
")",
";",
"}",
"else",
"{",
"$"... | Revoke an access token for a user
@param integer $iUserId The ID of the user the token belongs to
@param mixed $mToken The token object, or a token ID
@return boolean | [
"Revoke",
"an",
"access",
"token",
"for",
"a",
"user"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/AccessToken.php#L165-L185 | train |
nails/module-auth | src/Model/User/AccessToken.php | AccessToken.hasScope | public function hasScope($mToken, $sScope)
{
if (is_numeric($mToken)) {
$oToken = $this->getById($mToken);
} else {
$oToken = $mToken;
}
if ($oToken) {
return in_array($sScope, $oToken->scope);
} else {
return false;
}
} | php | public function hasScope($mToken, $sScope)
{
if (is_numeric($mToken)) {
$oToken = $this->getById($mToken);
} else {
$oToken = $mToken;
}
if ($oToken) {
return in_array($sScope, $oToken->scope);
} else {
return false;
}
} | [
"public",
"function",
"hasScope",
"(",
"$",
"mToken",
",",
"$",
"sScope",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"mToken",
")",
")",
"{",
"$",
"oToken",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"mToken",
")",
";",
"}",
"else",
"{",
"$",... | Determines whether a token has a given scope
@param mixed $mToken The token object, or a token ID
@param string $sScope The scope(s) to check for
@return boolean | [
"Determines",
"whether",
"a",
"token",
"has",
"a",
"given",
"scope"
] | f9b0b554c1e06399fa8042dd94c5acf86bac5548 | https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User/AccessToken.php#L248-L261 | train |
rotexsoft/leanorm | src/LeanOrm/DBConnector.php | DBConnector.setDb | public static function setDb($db, $connection_name = self::DEFAULT_CONNECTION) {
static::_initDbConfigWithDefaultVals($connection_name);
static::$_db[$connection_name] = $db;
} | php | public static function setDb($db, $connection_name = self::DEFAULT_CONNECTION) {
static::_initDbConfigWithDefaultVals($connection_name);
static::$_db[$connection_name] = $db;
} | [
"public",
"static",
"function",
"setDb",
"(",
"$",
"db",
",",
"$",
"connection_name",
"=",
"self",
"::",
"DEFAULT_CONNECTION",
")",
"{",
"static",
"::",
"_initDbConfigWithDefaultVals",
"(",
"$",
"connection_name",
")",
";",
"static",
"::",
"$",
"_db",
"[",
"... | Set the PDO object used by DBConnector to communicate with the database.
This is public in case the DBConnector should use a ready-instantiated
PDO object as its database connection. Accepts an optional string key
to identify the connection if multiple connections are used.
@param PDO $db
@param string $connection_name Which connection to use | [
"Set",
"the",
"PDO",
"object",
"used",
"by",
"DBConnector",
"to",
"communicate",
"with",
"the",
"database",
".",
"This",
"is",
"public",
"in",
"case",
"the",
"DBConnector",
"should",
"use",
"a",
"ready",
"-",
"instantiated",
"PDO",
"object",
"as",
"its",
"... | 8c630e2470188d436c633cf6f4a50f0ac7f4051e | https://github.com/rotexsoft/leanorm/blob/8c630e2470188d436c633cf6f4a50f0ac7f4051e/src/LeanOrm/DBConnector.php#L338-L342 | train |
rotexsoft/leanorm | src/LeanOrm/DBConnector.php | DBConnector.dbFetchOne | public function dbFetchOne( $select_query, $parameters = array() ) {
$bool_and_statement = static::_execute($select_query, $parameters, true, $this->_connection_name);
$statement = array_pop($bool_and_statement);
return $statement->fetch(\PDO::FETCH_ASSOC);
} | php | public function dbFetchOne( $select_query, $parameters = array() ) {
$bool_and_statement = static::_execute($select_query, $parameters, true, $this->_connection_name);
$statement = array_pop($bool_and_statement);
return $statement->fetch(\PDO::FETCH_ASSOC);
} | [
"public",
"function",
"dbFetchOne",
"(",
"$",
"select_query",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"bool_and_statement",
"=",
"static",
"::",
"_execute",
"(",
"$",
"select_query",
",",
"$",
"parameters",
",",
"true",
",",
"$",
"... | Tell the DBConnector that you are expecting a single result
back from your query, and execute it. Will return
a single instance of the DBConnector class, or false if no
rows were returned.
As a shortcut, you may supply an ID as a parameter
to this method. This will perform a primary key
lookup on the table. | [
"Tell",
"the",
"DBConnector",
"that",
"you",
"are",
"expecting",
"a",
"single",
"result",
"back",
"from",
"your",
"query",
"and",
"execute",
"it",
".",
"Will",
"return",
"a",
"single",
"instance",
"of",
"the",
"DBConnector",
"class",
"or",
"false",
"if",
"... | 8c630e2470188d436c633cf6f4a50f0ac7f4051e | https://github.com/rotexsoft/leanorm/blob/8c630e2470188d436c633cf6f4a50f0ac7f4051e/src/LeanOrm/DBConnector.php#L636-L643 | train |
locomotivemtl/charcoal-email | src/Charcoal/Email/EmailConfig.php | EmailConfig.setSmtpSecurity | public function setSmtpSecurity($security)
{
$security = strtoupper($security);
$validSecurity = [ '', 'TLS', 'SSL' ];
if (!in_array($security, $validSecurity)) {
throw new InvalidArgumentException(
'SMTP Security is not valid. Must be "", "TLS" or "SSL".'
);
}
$this->smtpSecurity = $security;
return $this;
} | php | public function setSmtpSecurity($security)
{
$security = strtoupper($security);
$validSecurity = [ '', 'TLS', 'SSL' ];
if (!in_array($security, $validSecurity)) {
throw new InvalidArgumentException(
'SMTP Security is not valid. Must be "", "TLS" or "SSL".'
);
}
$this->smtpSecurity = $security;
return $this;
} | [
"public",
"function",
"setSmtpSecurity",
"(",
"$",
"security",
")",
"{",
"$",
"security",
"=",
"strtoupper",
"(",
"$",
"security",
")",
";",
"$",
"validSecurity",
"=",
"[",
"''",
",",
"'TLS'",
",",
"'SSL'",
"]",
";",
"if",
"(",
"!",
"in_array",
"(",
... | Set the SMTP security type to be used.
@param string $security The SMTP security type (empty, "TLS", or "SSL").
@throws InvalidArgumentException If the security type is not valid (empty, "TLS", or "SSL").
@return self | [
"Set",
"the",
"SMTP",
"security",
"type",
"to",
"be",
"used",
"."
] | 99ccabcd0a91802e308177e0b6b626eaf0f940da | https://github.com/locomotivemtl/charcoal-email/blob/99ccabcd0a91802e308177e0b6b626eaf0f940da/src/Charcoal/Email/EmailConfig.php#L284-L298 | train |
au-research/ANDS-DOI-Service | src/Validator/URLValidator.php | URLValidator.validDomains | public static function validDomains($url, $domains)
{
$theDomain = parse_url($url);
foreach ($domains as $domain) {
$check = strpos($theDomain['host'], $domain->client_domain);
if ($check || $check === 0) {
return true;
}
}
return false;
} | php | public static function validDomains($url, $domains)
{
$theDomain = parse_url($url);
foreach ($domains as $domain) {
$check = strpos($theDomain['host'], $domain->client_domain);
if ($check || $check === 0) {
return true;
}
}
return false;
} | [
"public",
"static",
"function",
"validDomains",
"(",
"$",
"url",
",",
"$",
"domains",
")",
"{",
"$",
"theDomain",
"=",
"parse_url",
"(",
"$",
"url",
")",
";",
"foreach",
"(",
"$",
"domains",
"as",
"$",
"domain",
")",
"{",
"$",
"check",
"=",
"strpos",... | Check that a URL can belong to a list of available domains
@param $url
@param $domains
@return bool | [
"Check",
"that",
"a",
"URL",
"can",
"belong",
"to",
"a",
"list",
"of",
"available",
"domains"
] | c8e2cc98eca23a0c550af9a45b5c5dee230da1c9 | https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/URLValidator.php#L14-L24 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.postalcodeToCoordinates | public function postalcodeToCoordinates(array $postalData, $shouldRunC2A = false)
{
$this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A;
$this->returnLocationData = array_merge($this->returnLocationData, array_only($postalData, ['street_number', 'postal_code']));
return $this;
} | php | public function postalcodeToCoordinates(array $postalData, $shouldRunC2A = false)
{
$this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A;
$this->returnLocationData = array_merge($this->returnLocationData, array_only($postalData, ['street_number', 'postal_code']));
return $this;
} | [
"public",
"function",
"postalcodeToCoordinates",
"(",
"array",
"$",
"postalData",
",",
"$",
"shouldRunC2A",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"shouldRunC2A",
"=",
"(",
"$",
"this",
"->",
"shouldRunC2A",
")",
"?",
"true",
":",
"$",
"shouldRunC2A",
... | Get the coordinates from a postal code
@param string
@param string/integer
@return $this | [
"Get",
"the",
"coordinates",
"from",
"a",
"postal",
"code"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L122-L128 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.addressToCoordinates | public function addressToCoordinates(array $addressData = [])
{
$this->returnLocationData = array_merge($this->returnLocationData, array_only($addressData, ['country', 'region', 'city', 'street', 'street_number']));
return $this;
} | php | public function addressToCoordinates(array $addressData = [])
{
$this->returnLocationData = array_merge($this->returnLocationData, array_only($addressData, ['country', 'region', 'city', 'street', 'street_number']));
return $this;
} | [
"public",
"function",
"addressToCoordinates",
"(",
"array",
"$",
"addressData",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"returnLocationData",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"returnLocationData",
",",
"array_only",
"(",
"$",
"addressData",
",",... | Get coordinates from an address
@param array
@return $this | [
"Get",
"coordinates",
"from",
"an",
"address"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L136-L140 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.coordinatesToAddress | public function coordinatesToAddress(array $coordinates = [])
{
$this->shouldRunC2A = true;
$this->returnLocationData = array_merge($this->returnLocationData, array_only($coordinates, ['latitude', 'longitude']));
return $this;
} | php | public function coordinatesToAddress(array $coordinates = [])
{
$this->shouldRunC2A = true;
$this->returnLocationData = array_merge($this->returnLocationData, array_only($coordinates, ['latitude', 'longitude']));
return $this;
} | [
"public",
"function",
"coordinatesToAddress",
"(",
"array",
"$",
"coordinates",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"shouldRunC2A",
"=",
"true",
";",
"$",
"this",
"->",
"returnLocationData",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"returnLocation... | Get the address from coordinates
@param array
@return $this | [
"Get",
"the",
"address",
"from",
"coordinates"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L148-L154 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.ipToCoordinates | public function ipToCoordinates($ip = null, $shouldRunC2A = false)
{
$this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A;
if(! $ip) {
$ip = Request::ip();
}
$this->ip = $ip;
return $this;
} | php | public function ipToCoordinates($ip = null, $shouldRunC2A = false)
{
$this->shouldRunC2A = ($this->shouldRunC2A) ? true : $shouldRunC2A;
if(! $ip) {
$ip = Request::ip();
}
$this->ip = $ip;
return $this;
} | [
"public",
"function",
"ipToCoordinates",
"(",
"$",
"ip",
"=",
"null",
",",
"$",
"shouldRunC2A",
"=",
"false",
")",
"{",
"$",
"this",
"->",
"shouldRunC2A",
"=",
"(",
"$",
"this",
"->",
"shouldRunC2A",
")",
"?",
"true",
":",
"$",
"shouldRunC2A",
";",
"if... | Get coordinates from an ip
@param string (ip)
@return $this | [
"Get",
"coordinates",
"from",
"an",
"ip"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L162-L172 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.get | public function get($toObject = false)
{
if(!env('GOOGLE_KEY')) {
throw new Exception("Need an env key for geo request", 401);
}
$this->response = null;
$this->error = null;
if($this->c2a()) {
$response = $this->template($toObject);
}
elseif($this->a2c()) {
$response = $this->template($toObject);
}
elseif($this->i2c()) {
$response = $this->template($toObject);
}
elseif($this->p2c()) {
$response = $this->template($toObject);
}
if($response) {
$this->reset();
return $response;
}
throw new Exception(trans('location::errors.not_enough_data'));
} | php | public function get($toObject = false)
{
if(!env('GOOGLE_KEY')) {
throw new Exception("Need an env key for geo request", 401);
}
$this->response = null;
$this->error = null;
if($this->c2a()) {
$response = $this->template($toObject);
}
elseif($this->a2c()) {
$response = $this->template($toObject);
}
elseif($this->i2c()) {
$response = $this->template($toObject);
}
elseif($this->p2c()) {
$response = $this->template($toObject);
}
if($response) {
$this->reset();
return $response;
}
throw new Exception(trans('location::errors.not_enough_data'));
} | [
"public",
"function",
"get",
"(",
"$",
"toObject",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"env",
"(",
"'GOOGLE_KEY'",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Need an env key for geo request\"",
",",
"401",
")",
";",
"}",
"$",
"this",
"->",
... | Return the results | [
"Return",
"the",
"results"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L177-L205 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.template | private function template($toObject)
{
if($toObject) {
$response = new StdClass;
foreach($this->returnLocationData as $key => $value) {
$response->{$key} = $value;
}
return $response;
}
return $this->returnLocationData;
} | php | private function template($toObject)
{
if($toObject) {
$response = new StdClass;
foreach($this->returnLocationData as $key => $value) {
$response->{$key} = $value;
}
return $response;
}
return $this->returnLocationData;
} | [
"private",
"function",
"template",
"(",
"$",
"toObject",
")",
"{",
"if",
"(",
"$",
"toObject",
")",
"{",
"$",
"response",
"=",
"new",
"StdClass",
";",
"foreach",
"(",
"$",
"this",
"->",
"returnLocationData",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
... | Return the template as array or object
@param bool $toObject
@return mixed | [
"Return",
"the",
"template",
"as",
"array",
"or",
"object"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L221-L232 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.p2c | private function p2c()
{
if($this->returnLocationData['postal_code'] && ! $this->returnLocationData['latitude']) {
$this->method = 'GET';
$this->updateResponseWithResults($this->gateway($this->createAddressUrl()));
if($this->shouldRunC2A) {
$this->c2a();
}
return true;
}
} | php | private function p2c()
{
if($this->returnLocationData['postal_code'] && ! $this->returnLocationData['latitude']) {
$this->method = 'GET';
$this->updateResponseWithResults($this->gateway($this->createAddressUrl()));
if($this->shouldRunC2A) {
$this->c2a();
}
return true;
}
} | [
"private",
"function",
"p2c",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"returnLocationData",
"[",
"'postal_code'",
"]",
"&&",
"!",
"$",
"this",
"->",
"returnLocationData",
"[",
"'latitude'",
"]",
")",
"{",
"$",
"this",
"->",
"method",
"=",
"'GET'",
... | postal code to coordinate
@return bool | [
"postal",
"code",
"to",
"coordinate"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L239-L251 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.i2c | private function i2c()
{
if($this->ip && ! $this->returnLocationData['latitude']) {
$this->method = 'POST';
$this->updateResponseWithResults($this->gateway($this->createGeoUrl()));
if($this->shouldRunC2A) {
$this->c2a();
}
return true;
}
} | php | private function i2c()
{
if($this->ip && ! $this->returnLocationData['latitude']) {
$this->method = 'POST';
$this->updateResponseWithResults($this->gateway($this->createGeoUrl()));
if($this->shouldRunC2A) {
$this->c2a();
}
return true;
}
} | [
"private",
"function",
"i2c",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ip",
"&&",
"!",
"$",
"this",
"->",
"returnLocationData",
"[",
"'latitude'",
"]",
")",
"{",
"$",
"this",
"->",
"method",
"=",
"'POST'",
";",
"$",
"this",
"->",
"updateResponse... | ip to coordinates
@return bool | [
"ip",
"to",
"coordinates"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L277-L291 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.createAddressUrl | private function createAddressUrl()
{
$urlVariables = [
'language' => $this->locale,
];
if(count($this->isos)) {
$urlVariables['components'] = 'country:'.implode(',', $this->isos);
}
// if true it will always be the final stage in getting the address
if($this->returnLocationData['latitude'] && $this->returnLocationData['longitude']) {
$urlVariables['latlng'] = $this->returnLocationData['latitude'].','.$this->returnLocationData['longitude'];
return $this->buildUrl($urlVariables);
}
if($this->returnLocationData['city'] && $this->returnLocationData['country']) {
$urlVariables['address'] = $this->returnLocationData['city'].', '.$this->returnLocationData['country'];
return $this->buildUrl($urlVariables);
}
if($this->returnLocationData['postal_code']) {
$urlVariables['address'] = $this->returnLocationData['postal_code'].(($this->returnLocationData['street_number']) ? ' '.$this->returnLocationData['street_number'] : '');
return $this->buildUrl($urlVariables);
}
} | php | private function createAddressUrl()
{
$urlVariables = [
'language' => $this->locale,
];
if(count($this->isos)) {
$urlVariables['components'] = 'country:'.implode(',', $this->isos);
}
// if true it will always be the final stage in getting the address
if($this->returnLocationData['latitude'] && $this->returnLocationData['longitude']) {
$urlVariables['latlng'] = $this->returnLocationData['latitude'].','.$this->returnLocationData['longitude'];
return $this->buildUrl($urlVariables);
}
if($this->returnLocationData['city'] && $this->returnLocationData['country']) {
$urlVariables['address'] = $this->returnLocationData['city'].', '.$this->returnLocationData['country'];
return $this->buildUrl($urlVariables);
}
if($this->returnLocationData['postal_code']) {
$urlVariables['address'] = $this->returnLocationData['postal_code'].(($this->returnLocationData['street_number']) ? ' '.$this->returnLocationData['street_number'] : '');
return $this->buildUrl($urlVariables);
}
} | [
"private",
"function",
"createAddressUrl",
"(",
")",
"{",
"$",
"urlVariables",
"=",
"[",
"'language'",
"=>",
"$",
"this",
"->",
"locale",
",",
"]",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"isos",
")",
")",
"{",
"$",
"urlVariables",
"[",
"'co... | create the url to connect to for maps api
@return string Url | [
"create",
"the",
"url",
"to",
"connect",
"to",
"for",
"maps",
"api"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L322-L349 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.buildUrl | private function buildUrl($urlVariables)
{
$url = '';
foreach($urlVariables as $variable => $value) {
$url .= '&'.$variable.'='.($value);
}
return config('location.google-maps-url').env('GOOGLE_KEY').$url;
} | php | private function buildUrl($urlVariables)
{
$url = '';
foreach($urlVariables as $variable => $value) {
$url .= '&'.$variable.'='.($value);
}
return config('location.google-maps-url').env('GOOGLE_KEY').$url;
} | [
"private",
"function",
"buildUrl",
"(",
"$",
"urlVariables",
")",
"{",
"$",
"url",
"=",
"''",
";",
"foreach",
"(",
"$",
"urlVariables",
"as",
"$",
"variable",
"=>",
"$",
"value",
")",
"{",
"$",
"url",
".=",
"'&'",
".",
"$",
"variable",
".",
"'='",
... | Build the request url | [
"Build",
"the",
"request",
"url"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L354-L362 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.updateResponseWithResults | private function updateResponseWithResults($json)
{
$response = $this->jsonToArray($json);
if(isset($response['results'][0])) {
$this->response = $response['results'][0];
if(@$response['results'][0]['partial_match'] && $this->excludePartials) {
throw new Exception(trans('location::errors.no_results'));
}
if(! $this->returnLocationData['country']) {
$this->returnLocationData['country'] = $this->findInGoogleSet($response, ['country']);
$this->returnLocationData['iso'] = $this->findInGoogleSet($response, ['country'], 'short_name');
}
if(! $this->returnLocationData['region']) {
$this->returnLocationData['region'] = $this->findInGoogleSet($response, ['administrative_area_level_1']);
}
if(! $this->returnLocationData['city']) {
$this->returnLocationData['city'] = $this->findInGoogleSet($response, ['administrative_area_level_2']);
}
if(! $this->returnLocationData['street']) {
$this->returnLocationData['street'] = $this->findInGoogleSet($response, ['route']);
}
if(! $this->returnLocationData['street_number']) {
$this->returnLocationData['street_number'] = $this->findInGoogleSet($response, ['street_number']);
}
if(! $this->returnLocationData['postal_code']) {
$this->returnLocationData['postal_code'] = $this->findInGoogleSet($response, ['postal_code']);
}
if(! $this->returnLocationData['latitude']) {
$this->returnLocationData['latitude'] = $response['results'][0]['geometry']['location']['lat'];
}
if(! $this->returnLocationData['longitude']) {
$this->returnLocationData['longitude'] = $response['results'][0]['geometry']['location']['lng'];
}
}
elseif(@$response['location']) {
$this->returnLocationData['latitude'] = $response['location']['lat'];
$this->returnLocationData['longitude'] = $response['location']['lng'];
}
else {
throw new Exception(trans('location::errors.no_results'));
}
} | php | private function updateResponseWithResults($json)
{
$response = $this->jsonToArray($json);
if(isset($response['results'][0])) {
$this->response = $response['results'][0];
if(@$response['results'][0]['partial_match'] && $this->excludePartials) {
throw new Exception(trans('location::errors.no_results'));
}
if(! $this->returnLocationData['country']) {
$this->returnLocationData['country'] = $this->findInGoogleSet($response, ['country']);
$this->returnLocationData['iso'] = $this->findInGoogleSet($response, ['country'], 'short_name');
}
if(! $this->returnLocationData['region']) {
$this->returnLocationData['region'] = $this->findInGoogleSet($response, ['administrative_area_level_1']);
}
if(! $this->returnLocationData['city']) {
$this->returnLocationData['city'] = $this->findInGoogleSet($response, ['administrative_area_level_2']);
}
if(! $this->returnLocationData['street']) {
$this->returnLocationData['street'] = $this->findInGoogleSet($response, ['route']);
}
if(! $this->returnLocationData['street_number']) {
$this->returnLocationData['street_number'] = $this->findInGoogleSet($response, ['street_number']);
}
if(! $this->returnLocationData['postal_code']) {
$this->returnLocationData['postal_code'] = $this->findInGoogleSet($response, ['postal_code']);
}
if(! $this->returnLocationData['latitude']) {
$this->returnLocationData['latitude'] = $response['results'][0]['geometry']['location']['lat'];
}
if(! $this->returnLocationData['longitude']) {
$this->returnLocationData['longitude'] = $response['results'][0]['geometry']['location']['lng'];
}
}
elseif(@$response['location']) {
$this->returnLocationData['latitude'] = $response['location']['lat'];
$this->returnLocationData['longitude'] = $response['location']['lng'];
}
else {
throw new Exception(trans('location::errors.no_results'));
}
} | [
"private",
"function",
"updateResponseWithResults",
"(",
"$",
"json",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"jsonToArray",
"(",
"$",
"json",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"response",
"[",
"'results'",
"]",
"[",
"0",
"]",
")",
"... | fill the response with usefull data as far as we can find | [
"fill",
"the",
"response",
"with",
"usefull",
"data",
"as",
"far",
"as",
"we",
"can",
"find"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L389-L440 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.findInGoogleSet | private function findInGoogleSet($response, array $find = [], $type = 'long_name')
{
try {
foreach($response['results'][0]['address_components'] as $data) {
foreach($data['types'] as $key) {
if(in_array($key, $find)) {
return $data[$type];
}
}
}
return '';
}
catch(Exception $e) {
$this->error = $e;
return '';
}
} | php | private function findInGoogleSet($response, array $find = [], $type = 'long_name')
{
try {
foreach($response['results'][0]['address_components'] as $data) {
foreach($data['types'] as $key) {
if(in_array($key, $find)) {
return $data[$type];
}
}
}
return '';
}
catch(Exception $e) {
$this->error = $e;
return '';
}
} | [
"private",
"function",
"findInGoogleSet",
"(",
"$",
"response",
",",
"array",
"$",
"find",
"=",
"[",
"]",
",",
"$",
"type",
"=",
"'long_name'",
")",
"{",
"try",
"{",
"foreach",
"(",
"$",
"response",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'addres... | Find a value in a response from google
@param array (googles response)
@param array (attributes to find)
@return string | [
"Find",
"a",
"value",
"in",
"a",
"response",
"from",
"google"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L449-L466 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.jsonToArray | private function jsonToArray($json)
{
try {
$data = json_decode($json, true);
if(is_array($data)) {
return $data;
}
else {
$this->error = 'The given data string was not json';
return [];
}
}
catch(Exception $e) {
$this->error = $e;
}
} | php | private function jsonToArray($json)
{
try {
$data = json_decode($json, true);
if(is_array($data)) {
return $data;
}
else {
$this->error = 'The given data string was not json';
return [];
}
}
catch(Exception $e) {
$this->error = $e;
}
} | [
"private",
"function",
"jsonToArray",
"(",
"$",
"json",
")",
"{",
"try",
"{",
"$",
"data",
"=",
"json_decode",
"(",
"$",
"json",
",",
"true",
")",
";",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"{",
"return",
"$",
"data",
";",
"}",
"else... | Convert json string to an array if the syntax is right
@param string (json)
@return array|null | [
"Convert",
"json",
"string",
"to",
"an",
"array",
"if",
"the",
"syntax",
"is",
"right"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L475-L490 | train |
Thorazine/location | src/Classes/Facades/Location.php | Location.reset | private function reset()
{
$this->returnLocationData = $this->locationDataTemplate;
$this->locale = (config('location.language')) ? config('location.language') : App::getLocale();
$this->ip = null;
$this->client = null;
} | php | private function reset()
{
$this->returnLocationData = $this->locationDataTemplate;
$this->locale = (config('location.language')) ? config('location.language') : App::getLocale();
$this->ip = null;
$this->client = null;
} | [
"private",
"function",
"reset",
"(",
")",
"{",
"$",
"this",
"->",
"returnLocationData",
"=",
"$",
"this",
"->",
"locationDataTemplate",
";",
"$",
"this",
"->",
"locale",
"=",
"(",
"config",
"(",
"'location.language'",
")",
")",
"?",
"config",
"(",
"'locati... | Reset the class
@return void | [
"Reset",
"the",
"class"
] | cf18c96619af002e3447db1bab14804ba499f2f0 | https://github.com/Thorazine/location/blob/cf18c96619af002e3447db1bab14804ba499f2f0/src/Classes/Facades/Location.php#L507-L513 | train |
yawik/settings | src/Form/Filter/DisableElementsCapableFormSettings.php | DisableElementsCapableFormSettings.convert | protected function convert(array $value)
{
$return = array();
foreach ($value as $name => $elements) {
if (is_array($elements)) {
// We have a checkbox hit for a subform/fieldset,
if (isset($elements['__all__'])) {
if ('0' == $elements['__all__']) {
// The whole subform/fieldset shall be disabled, so add it and continue.
$return[] = $name;
continue;
} else {
// We do not need the toggle all checkbox value anymore.
unset($elements['__all__']);
}
}
// recurse with the subform/fieldset element toggle checkboxes.
$result = $this->convert($elements);
if (count($result)) {
// Some elements on the subform shall be disabled, so add the result array.
$return[$name] = $result;
}
continue;
}
if ('0' == $elements) {
// We have a disabled element, add it to the array.
$return[] = $name;
}
}
return $return;
} | php | protected function convert(array $value)
{
$return = array();
foreach ($value as $name => $elements) {
if (is_array($elements)) {
// We have a checkbox hit for a subform/fieldset,
if (isset($elements['__all__'])) {
if ('0' == $elements['__all__']) {
// The whole subform/fieldset shall be disabled, so add it and continue.
$return[] = $name;
continue;
} else {
// We do not need the toggle all checkbox value anymore.
unset($elements['__all__']);
}
}
// recurse with the subform/fieldset element toggle checkboxes.
$result = $this->convert($elements);
if (count($result)) {
// Some elements on the subform shall be disabled, so add the result array.
$return[$name] = $result;
}
continue;
}
if ('0' == $elements) {
// We have a disabled element, add it to the array.
$return[] = $name;
}
}
return $return;
} | [
"protected",
"function",
"convert",
"(",
"array",
"$",
"value",
")",
"{",
"$",
"return",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"value",
"as",
"$",
"name",
"=>",
"$",
"elements",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"elements",
")"... | Converts an element value array to config array recursively.
@param array $value
@return array | [
"Converts",
"an",
"element",
"value",
"array",
"to",
"config",
"array",
"recursively",
"."
] | fc49d14a5eec21fcc074ce29b1428d91191efecf | https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/Filter/DisableElementsCapableFormSettings.php#L48-L80 | train |
mirko-pagliai/me-cms | src/Model/Table/PostsTable.php | PostsTable.buildRules | public function buildRules(RulesChecker $rules)
{
return $rules->add($rules->existsIn(['category_id'], 'Categories', I18N_SELECT_VALID_OPTION))
->add($rules->existsIn(['user_id'], 'Users', I18N_SELECT_VALID_OPTION))
->add($rules->isUnique(['slug'], I18N_VALUE_ALREADY_USED))
->add($rules->isUnique(['title'], I18N_VALUE_ALREADY_USED));
} | php | public function buildRules(RulesChecker $rules)
{
return $rules->add($rules->existsIn(['category_id'], 'Categories', I18N_SELECT_VALID_OPTION))
->add($rules->existsIn(['user_id'], 'Users', I18N_SELECT_VALID_OPTION))
->add($rules->isUnique(['slug'], I18N_VALUE_ALREADY_USED))
->add($rules->isUnique(['title'], I18N_VALUE_ALREADY_USED));
} | [
"public",
"function",
"buildRules",
"(",
"RulesChecker",
"$",
"rules",
")",
"{",
"return",
"$",
"rules",
"->",
"add",
"(",
"$",
"rules",
"->",
"existsIn",
"(",
"[",
"'category_id'",
"]",
",",
"'Categories'",
",",
"I18N_SELECT_VALID_OPTION",
")",
")",
"->",
... | Returns a rules checker object that will be used for validating
application integrity
@param \Cake\ORM\RulesChecker $rules The rules object to be modified
@return \Cake\ORM\RulesChecker | [
"Returns",
"a",
"rules",
"checker",
"object",
"that",
"will",
"be",
"used",
"for",
"validating",
"application",
"integrity"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/PostsTable.php#L89-L95 | train |
mirko-pagliai/me-cms | src/Model/Table/PostsTable.php | PostsTable.getRelated | public function getRelated(Post $post, $limit = 5, $images = true)
{
key_exists_or_fail(['id', 'tags'], $post->toArray(), __d('me_cms', 'ID or tags of the post are missing'));
$cache = sprintf('related_%s_posts_for_%s', $limit, $post->id);
if ($images) {
$cache .= '_with_images';
}
return Cache::remember($cache, function () use ($images, $limit, $post) {
$related = [];
if ($post->has('tags')) {
//Sorts and takes tags by `post_count` field
$tags = collection($post->tags)->sortBy('post_count')->take($limit)->toList();
//This array will be contain the ID to be excluded
$exclude[] = $post->id;
//For each tag, gets a related post.
//It reverses the tags order, because the tags less popular have
// less chance to find a related post
foreach (array_reverse($tags) as $tag) {
$post = $this->queryForRelated($tag->id, $images)
->where([sprintf('%s.id NOT IN', $this->getAlias()) => $exclude])
->first();
//Adds the current post to the related posts and its ID to the
// IDs to be excluded for the next query
if ($post) {
$related[] = $post;
$exclude[] = $post->id;
}
}
}
return $related;
}, $this->getCacheName());
} | php | public function getRelated(Post $post, $limit = 5, $images = true)
{
key_exists_or_fail(['id', 'tags'], $post->toArray(), __d('me_cms', 'ID or tags of the post are missing'));
$cache = sprintf('related_%s_posts_for_%s', $limit, $post->id);
if ($images) {
$cache .= '_with_images';
}
return Cache::remember($cache, function () use ($images, $limit, $post) {
$related = [];
if ($post->has('tags')) {
//Sorts and takes tags by `post_count` field
$tags = collection($post->tags)->sortBy('post_count')->take($limit)->toList();
//This array will be contain the ID to be excluded
$exclude[] = $post->id;
//For each tag, gets a related post.
//It reverses the tags order, because the tags less popular have
// less chance to find a related post
foreach (array_reverse($tags) as $tag) {
$post = $this->queryForRelated($tag->id, $images)
->where([sprintf('%s.id NOT IN', $this->getAlias()) => $exclude])
->first();
//Adds the current post to the related posts and its ID to the
// IDs to be excluded for the next query
if ($post) {
$related[] = $post;
$exclude[] = $post->id;
}
}
}
return $related;
}, $this->getCacheName());
} | [
"public",
"function",
"getRelated",
"(",
"Post",
"$",
"post",
",",
"$",
"limit",
"=",
"5",
",",
"$",
"images",
"=",
"true",
")",
"{",
"key_exists_or_fail",
"(",
"[",
"'id'",
",",
"'tags'",
"]",
",",
"$",
"post",
"->",
"toArray",
"(",
")",
",",
"__d... | Gets the related posts for a post
@param \MeCms\Model\Entity\Post $post Post entity. It must contain `id` and `Tags`
@param int $limit Limit of related posts
@param bool $images If `true`, gets only posts with images
@return array Array of entities
@uses queryForRelated()
@uses $cache | [
"Gets",
"the",
"related",
"posts",
"for",
"a",
"post"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/PostsTable.php#L126-L164 | train |
mirko-pagliai/me-cms | src/Model/Table/PostsTable.php | PostsTable.queryForRelated | public function queryForRelated($tagId, $images = true)
{
$query = $this->find('active')
->select(['id', 'title', 'preview', 'slug', 'text'])
->matching('Tags', function (Query $q) use ($tagId) {
return $q->where([sprintf('%s.id', $this->Tags->getAlias()) => $tagId]);
});
if ($images) {
$query->where([sprintf('%s.preview NOT IN', $this->getAlias()) => [null, []]]);
}
return $query;
} | php | public function queryForRelated($tagId, $images = true)
{
$query = $this->find('active')
->select(['id', 'title', 'preview', 'slug', 'text'])
->matching('Tags', function (Query $q) use ($tagId) {
return $q->where([sprintf('%s.id', $this->Tags->getAlias()) => $tagId]);
});
if ($images) {
$query->where([sprintf('%s.preview NOT IN', $this->getAlias()) => [null, []]]);
}
return $query;
} | [
"public",
"function",
"queryForRelated",
"(",
"$",
"tagId",
",",
"$",
"images",
"=",
"true",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"find",
"(",
"'active'",
")",
"->",
"select",
"(",
"[",
"'id'",
",",
"'title'",
",",
"'preview'",
",",
"'slug... | Gets the query for related posts from a tag ID
@param int $tagId Tag ID
@param bool $images If `true`, gets only posts with images
@return Cake\ORM\Query The query builder
@since 2.23.0 | [
"Gets",
"the",
"query",
"for",
"related",
"posts",
"from",
"a",
"tag",
"ID"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Model/Table/PostsTable.php#L210-L223 | train |
ommu/mod-core | models/OmmuSystemPhrase.php | OmmuSystemPhrase.getPublicPhrase | public static function getPublicPhrase($select=null)
{
$criteria=new CDbCriteria;
$criteria->condition = 'phrase_id > :first AND phrase_id < :last';
$criteria->params = array(
':first'=>1000,
':last'=>1500,
);
if($select != null)
$criteria->select = $select;
$model = self::model()->findAll($criteria);
return $model;
} | php | public static function getPublicPhrase($select=null)
{
$criteria=new CDbCriteria;
$criteria->condition = 'phrase_id > :first AND phrase_id < :last';
$criteria->params = array(
':first'=>1000,
':last'=>1500,
);
if($select != null)
$criteria->select = $select;
$model = self::model()->findAll($criteria);
return $model;
} | [
"public",
"static",
"function",
"getPublicPhrase",
"(",
"$",
"select",
"=",
"null",
")",
"{",
"$",
"criteria",
"=",
"new",
"CDbCriteria",
";",
"$",
"criteria",
"->",
"condition",
"=",
"'phrase_id > :first AND phrase_id < :last'",
";",
"$",
"criteria",
"->",
"par... | get public phrase | [
"get",
"public",
"phrase"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/models/OmmuSystemPhrase.php#L257-L270 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Script/CleanupScript.php | CleanupScript.pruneRelationships | protected function pruneRelationships()
{
$cli = $this->climate();
$ask = $this->interactive();
$dry = $this->dryRun();
$verb = $this->verbose();
$mucho = ($dry || $verb);
$attach = $this->modelFactory()->get(Attachment::class);
$pivot = $this->modelFactory()->get(Join::class);
$source = $attach->source();
$db = $source->db();
$defaultBinds = [
'%pivotTable' => $pivot->source()->table(),
'%sourceType' => 'object_type',
'%sourceId' => 'object_id',
];
$sql = 'SELECT DISTINCT `%sourceType` FROM `%pivotTable`;';
$rows = $db->query(strtr($sql, $binds), PDO::FETCH_ASSOC);
if ($rows->rowCount()) {
error_log(get_called_class().'::'.__FUNCTION__);
/** @todo Confirm each distinct source type */
foreach ($rows as $row) {
try {
$model = $this->modelFactory()->get($row['object_type']);
} catch (Exception $e) {
unset($e);
$model = $row['object_type'];
}
if ($model instanceof ModelInterface) {
$sql = 'SELECT p.* FROM `%pivotTable` AS p
WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN (
SELECT o.`%objectKey` FROM `%objectTable` AS o
);';
$binds = array_merge($defaultBinds, [
'%objectTable' => $model->source()->table(),
'%objectKey' => $model->key(),
]);
$rows = $source->dbQuery(
strtr($sql, $binds),
[ 'objType' => $row['object_type'] ]
);
/** @todo Show found rows, confirm deletion of dead relationships */
/*
$sql = 'DELETE FROM `%pivotTable` AS p
WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN (
SELECT o.`%objectKey` FROM `%objectTable` AS o
);';
error_log('-- Delete Dead Objects: '.var_export($sql, true));
$source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
*/
} elseif (is_string($model)) {
$sql = 'SELECT p.* FROM `%pivotTable` AS p WHERE p.`%sourceType` = :objType;';
$rows = $source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
/** @todo Explain missing model, confirm deletion of dead relationships */
/*
$sql = 'DELETE FROM `%pivotTable` WHERE `%sourceType` = :objType;';
error_log('-- Delete Dead Model: '.var_export($sql, true));
$source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
*/
}
}
/*
if (!$this->describeCount(
$this->total,
'%d dead objects were found.',
'%d dead object was found.',
'All objects are associated!'
)) {
return $this;
}
*/
$this->conclude();
}
return $this;
} | php | protected function pruneRelationships()
{
$cli = $this->climate();
$ask = $this->interactive();
$dry = $this->dryRun();
$verb = $this->verbose();
$mucho = ($dry || $verb);
$attach = $this->modelFactory()->get(Attachment::class);
$pivot = $this->modelFactory()->get(Join::class);
$source = $attach->source();
$db = $source->db();
$defaultBinds = [
'%pivotTable' => $pivot->source()->table(),
'%sourceType' => 'object_type',
'%sourceId' => 'object_id',
];
$sql = 'SELECT DISTINCT `%sourceType` FROM `%pivotTable`;';
$rows = $db->query(strtr($sql, $binds), PDO::FETCH_ASSOC);
if ($rows->rowCount()) {
error_log(get_called_class().'::'.__FUNCTION__);
/** @todo Confirm each distinct source type */
foreach ($rows as $row) {
try {
$model = $this->modelFactory()->get($row['object_type']);
} catch (Exception $e) {
unset($e);
$model = $row['object_type'];
}
if ($model instanceof ModelInterface) {
$sql = 'SELECT p.* FROM `%pivotTable` AS p
WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN (
SELECT o.`%objectKey` FROM `%objectTable` AS o
);';
$binds = array_merge($defaultBinds, [
'%objectTable' => $model->source()->table(),
'%objectKey' => $model->key(),
]);
$rows = $source->dbQuery(
strtr($sql, $binds),
[ 'objType' => $row['object_type'] ]
);
/** @todo Show found rows, confirm deletion of dead relationships */
/*
$sql = 'DELETE FROM `%pivotTable` AS p
WHERE p.`%sourceType` = :objType AND p.`%sourceId` NOT IN (
SELECT o.`%objectKey` FROM `%objectTable` AS o
);';
error_log('-- Delete Dead Objects: '.var_export($sql, true));
$source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
*/
} elseif (is_string($model)) {
$sql = 'SELECT p.* FROM `%pivotTable` AS p WHERE p.`%sourceType` = :objType;';
$rows = $source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
/** @todo Explain missing model, confirm deletion of dead relationships */
/*
$sql = 'DELETE FROM `%pivotTable` WHERE `%sourceType` = :objType;';
error_log('-- Delete Dead Model: '.var_export($sql, true));
$source->dbQuery(
strtr($sql, $defaultBinds),
[ 'objType' => $model ]
);
*/
}
}
/*
if (!$this->describeCount(
$this->total,
'%d dead objects were found.',
'%d dead object was found.',
'All objects are associated!'
)) {
return $this;
}
*/
$this->conclude();
}
return $this;
} | [
"protected",
"function",
"pruneRelationships",
"(",
")",
"{",
"$",
"cli",
"=",
"$",
"this",
"->",
"climate",
"(",
")",
";",
"$",
"ask",
"=",
"$",
"this",
"->",
"interactive",
"(",
")",
";",
"$",
"dry",
"=",
"$",
"this",
"->",
"dryRun",
"(",
")",
... | Prune relationships of dead objects.
@return self | [
"Prune",
"relationships",
"of",
"dead",
"objects",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Script/CleanupScript.php#L214-L310 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Script/CleanupScript.php | CleanupScript.conclude | protected function conclude()
{
$cli = $this->climate();
if (count($this->messages)) {
$cli->out(implode(' ', $this->messages));
$this->messages = [];
} else {
$cli->info('Done!');
}
return $this;
} | php | protected function conclude()
{
$cli = $this->climate();
if (count($this->messages)) {
$cli->out(implode(' ', $this->messages));
$this->messages = [];
} else {
$cli->info('Done!');
}
return $this;
} | [
"protected",
"function",
"conclude",
"(",
")",
"{",
"$",
"cli",
"=",
"$",
"this",
"->",
"climate",
"(",
")",
";",
"if",
"(",
"count",
"(",
"$",
"this",
"->",
"messages",
")",
")",
"{",
"$",
"cli",
"->",
"out",
"(",
"implode",
"(",
"' '",
",",
"... | Display stored messages or a generic conclusion.
@return self | [
"Display",
"stored",
"messages",
"or",
"a",
"generic",
"conclusion",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Script/CleanupScript.php#L516-L528 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Script/CleanupScript.php | CleanupScript.describeCount | protected function describeCount($count, $plural, $singular, $zero)
{
if (!is_int($count)) {
throw new InvalidArgumentException(
sprintf(
'Must be an integer',
is_object($count) ? get_class($count) : gettype($count)
)
);
}
$cli = $this->climate();
if ($count === 0) {
$cli->info(
sprintf($zero, $count)
);
return false;
} elseif ($count === 1) {
$cli->comment(
sprintf($singular, $count)
);
} else {
$cli->comment(
sprintf($plural, $count)
);
}
$cli->br();
return true;
} | php | protected function describeCount($count, $plural, $singular, $zero)
{
if (!is_int($count)) {
throw new InvalidArgumentException(
sprintf(
'Must be an integer',
is_object($count) ? get_class($count) : gettype($count)
)
);
}
$cli = $this->climate();
if ($count === 0) {
$cli->info(
sprintf($zero, $count)
);
return false;
} elseif ($count === 1) {
$cli->comment(
sprintf($singular, $count)
);
} else {
$cli->comment(
sprintf($plural, $count)
);
}
$cli->br();
return true;
} | [
"protected",
"function",
"describeCount",
"(",
"$",
"count",
",",
"$",
"plural",
",",
"$",
"singular",
",",
"$",
"zero",
")",
"{",
"if",
"(",
"!",
"is_int",
"(",
"$",
"count",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"... | Describe the given object count.
@param integer $count The object count.
@param string $plural The message when the count is more than 1.
@param string $singular The message when the count is 1.
@param string $zero The message when the count is zero.
@throws InvalidArgumentException If the given argument is not an integer.
@return boolean | [
"Describe",
"the",
"given",
"object",
"count",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Script/CleanupScript.php#L540-L571 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Object/Gallery.php | Gallery.attachmentsAsRows | public function attachmentsAsRows()
{
$rows = [];
if ($this->hasAttachments()) {
$rows = array_chunk($this->attachments()->values(), $this->numColumns);
/** Map row content with useful front-end properties. */
array_walk($rows, function(&$value, $key) {
$value = [
'columns' => $value,
'isFirst' => $key === 0
];
});
}
return $rows;
} | php | public function attachmentsAsRows()
{
$rows = [];
if ($this->hasAttachments()) {
$rows = array_chunk($this->attachments()->values(), $this->numColumns);
/** Map row content with useful front-end properties. */
array_walk($rows, function(&$value, $key) {
$value = [
'columns' => $value,
'isFirst' => $key === 0
];
});
}
return $rows;
} | [
"public",
"function",
"attachmentsAsRows",
"(",
")",
"{",
"$",
"rows",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"this",
"->",
"hasAttachments",
"(",
")",
")",
"{",
"$",
"rows",
"=",
"array_chunk",
"(",
"$",
"this",
"->",
"attachments",
"(",
")",
"->",
"... | Retrieve the container's attachments as rows containing columns.
@return array | [
"Retrieve",
"the",
"container",
"s",
"attachments",
"as",
"rows",
"containing",
"columns",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Object/Gallery.php#L27-L44 | train |
mirko-pagliai/me-cms | src/Utility/StaticPage.php | StaticPage.getAllPaths | protected static function getAllPaths()
{
$paths = Cache::read('paths', 'static_pages');
if (empty($paths)) {
//Adds all plugins to paths
$paths = collection(Plugin::all())
->map(function ($plugin) {
return self::getPluginPath($plugin);
})
->filter(function ($path) {
return file_exists($path);
})
->toList();
//Adds APP to paths
array_unshift($paths, self::getAppPath());
Cache::write('paths', $paths, 'static_pages');
}
return $paths;
} | php | protected static function getAllPaths()
{
$paths = Cache::read('paths', 'static_pages');
if (empty($paths)) {
//Adds all plugins to paths
$paths = collection(Plugin::all())
->map(function ($plugin) {
return self::getPluginPath($plugin);
})
->filter(function ($path) {
return file_exists($path);
})
->toList();
//Adds APP to paths
array_unshift($paths, self::getAppPath());
Cache::write('paths', $paths, 'static_pages');
}
return $paths;
} | [
"protected",
"static",
"function",
"getAllPaths",
"(",
")",
"{",
"$",
"paths",
"=",
"Cache",
"::",
"read",
"(",
"'paths'",
",",
"'static_pages'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"paths",
")",
")",
"{",
"//Adds all plugins to paths",
"$",
"paths",
... | Internal method to get all paths for static pages
@return array
@uses MeCms\Core\Plugin::all()
@uses getAppPath()
@uses getPluginPath() | [
"Internal",
"method",
"to",
"get",
"all",
"paths",
"for",
"static",
"pages"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/StaticPage.php#L36-L58 | train |
mirko-pagliai/me-cms | src/Utility/StaticPage.php | StaticPage.getSlug | protected static function getSlug($path, $relativePath)
{
if (string_starts_with($path, $relativePath)) {
$path = substr($path, strlen(Folder::slashTerm($relativePath)));
}
$path = preg_replace(sprintf('/\.[^\.]+$/'), null, $path);
return DS == '/' ? $path : str_replace(DS, '/', $path);
} | php | protected static function getSlug($path, $relativePath)
{
if (string_starts_with($path, $relativePath)) {
$path = substr($path, strlen(Folder::slashTerm($relativePath)));
}
$path = preg_replace(sprintf('/\.[^\.]+$/'), null, $path);
return DS == '/' ? $path : str_replace(DS, '/', $path);
} | [
"protected",
"static",
"function",
"getSlug",
"(",
"$",
"path",
",",
"$",
"relativePath",
")",
"{",
"if",
"(",
"string_starts_with",
"(",
"$",
"path",
",",
"$",
"relativePath",
")",
")",
"{",
"$",
"path",
"=",
"substr",
"(",
"$",
"path",
",",
"strlen",... | Internal method to get the slug.
It takes the full path and removes the relative path and the extension.
@param string $path Path
@param string $relativePath Relative path
@return string | [
"Internal",
"method",
"to",
"get",
"the",
"slug",
"."
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/StaticPage.php#L89-L97 | train |
mirko-pagliai/me-cms | src/Utility/StaticPage.php | StaticPage.all | public static function all()
{
foreach (self::getAllPaths() as $path) {
//Gets all files for each path
$files = (new Folder($path))->findRecursive('^.+\.ctp$', true);
foreach ($files as $file) {
$pages[] = new Entity([
'filename' => pathinfo($file, PATHINFO_FILENAME),
'path' => rtr($file),
'slug' => self::getSlug($file, $path),
'title' => self::title(pathinfo($file, PATHINFO_FILENAME)),
'modified' => new FrozenTime(filemtime($file)),
]);
}
}
return $pages;
} | php | public static function all()
{
foreach (self::getAllPaths() as $path) {
//Gets all files for each path
$files = (new Folder($path))->findRecursive('^.+\.ctp$', true);
foreach ($files as $file) {
$pages[] = new Entity([
'filename' => pathinfo($file, PATHINFO_FILENAME),
'path' => rtr($file),
'slug' => self::getSlug($file, $path),
'title' => self::title(pathinfo($file, PATHINFO_FILENAME)),
'modified' => new FrozenTime(filemtime($file)),
]);
}
}
return $pages;
} | [
"public",
"static",
"function",
"all",
"(",
")",
"{",
"foreach",
"(",
"self",
"::",
"getAllPaths",
"(",
")",
"as",
"$",
"path",
")",
"{",
"//Gets all files for each path",
"$",
"files",
"=",
"(",
"new",
"Folder",
"(",
"$",
"path",
")",
")",
"->",
"find... | Gets all static pages
@return array Static pages
@uses getAllPaths()
@uses getSlug()
@uses title() | [
"Gets",
"all",
"static",
"pages"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/StaticPage.php#L106-L124 | train |
mirko-pagliai/me-cms | src/Utility/StaticPage.php | StaticPage.get | public static function get($slug)
{
$locale = I18n::getLocale();
$slug = array_filter(explode('/', $slug));
$cache = sprintf('page_%s_locale_%s', md5(serialize($slug)), $locale);
$page = Cache::read($cache, 'static_pages');
if (empty($page)) {
//Sets the (partial) filename
$filename = implode(DS, $slug);
//Sets the filename patterns
$patterns = [$filename . '-' . $locale];
if (preg_match('/^(\w+)_\w+$/', $locale, $matches)) {
$patterns[] = $filename . '-' . $matches[1];
}
$patterns[] = $filename;
//Checks if the page exists in APP
foreach ($patterns as $pattern) {
$filename = self::getAppPath() . $pattern . '.ctp';
if (is_readable($filename)) {
$page = DS . 'StaticPages' . DS . $pattern;
break;
}
}
//Checks if the page exists in each plugin
foreach (Plugin::all() as $plugin) {
foreach ($patterns as $pattern) {
$filename = self::getPluginPath($plugin) . $pattern . '.ctp';
if (is_readable($filename)) {
$page = $plugin . '.' . DS . 'StaticPages' . DS . $pattern;
break;
}
}
}
Cache::write($cache, $page, 'static_pages');
}
return $page;
} | php | public static function get($slug)
{
$locale = I18n::getLocale();
$slug = array_filter(explode('/', $slug));
$cache = sprintf('page_%s_locale_%s', md5(serialize($slug)), $locale);
$page = Cache::read($cache, 'static_pages');
if (empty($page)) {
//Sets the (partial) filename
$filename = implode(DS, $slug);
//Sets the filename patterns
$patterns = [$filename . '-' . $locale];
if (preg_match('/^(\w+)_\w+$/', $locale, $matches)) {
$patterns[] = $filename . '-' . $matches[1];
}
$patterns[] = $filename;
//Checks if the page exists in APP
foreach ($patterns as $pattern) {
$filename = self::getAppPath() . $pattern . '.ctp';
if (is_readable($filename)) {
$page = DS . 'StaticPages' . DS . $pattern;
break;
}
}
//Checks if the page exists in each plugin
foreach (Plugin::all() as $plugin) {
foreach ($patterns as $pattern) {
$filename = self::getPluginPath($plugin) . $pattern . '.ctp';
if (is_readable($filename)) {
$page = $plugin . '.' . DS . 'StaticPages' . DS . $pattern;
break;
}
}
}
Cache::write($cache, $page, 'static_pages');
}
return $page;
} | [
"public",
"static",
"function",
"get",
"(",
"$",
"slug",
")",
"{",
"$",
"locale",
"=",
"I18n",
"::",
"getLocale",
"(",
")",
";",
"$",
"slug",
"=",
"array_filter",
"(",
"explode",
"(",
"'/'",
",",
"$",
"slug",
")",
")",
";",
"$",
"cache",
"=",
"sp... | Gets a static page
@param string $slug Slug
@return string|bool Static page or `false`
@uses MeCms\Core\Plugin::all()
@uses getAppPath()
@uses getPluginPath() | [
"Gets",
"a",
"static",
"page"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/StaticPage.php#L134-L180 | train |
mirko-pagliai/me-cms | src/Utility/StaticPage.php | StaticPage.title | public static function title($slugOrPath)
{
//Gets only the filename (without extension)
$slugOrPath = pathinfo($slugOrPath, PATHINFO_FILENAME);
//Turns dashes into underscores (because `Inflector::humanize` will
// remove only underscores)
$slugOrPath = str_replace('-', '_', $slugOrPath);
return Inflector::humanize($slugOrPath);
} | php | public static function title($slugOrPath)
{
//Gets only the filename (without extension)
$slugOrPath = pathinfo($slugOrPath, PATHINFO_FILENAME);
//Turns dashes into underscores (because `Inflector::humanize` will
// remove only underscores)
$slugOrPath = str_replace('-', '_', $slugOrPath);
return Inflector::humanize($slugOrPath);
} | [
"public",
"static",
"function",
"title",
"(",
"$",
"slugOrPath",
")",
"{",
"//Gets only the filename (without extension)",
"$",
"slugOrPath",
"=",
"pathinfo",
"(",
"$",
"slugOrPath",
",",
"PATHINFO_FILENAME",
")",
";",
"//Turns dashes into underscores (because `Inflector::h... | Gets the title for a static page from its slug or path
@param string $slugOrPath Slug or path
@return string | [
"Gets",
"the",
"title",
"for",
"a",
"static",
"page",
"from",
"its",
"slug",
"or",
"path"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/StaticPage.php#L187-L197 | train |
ommu/mod-core | components/system/Utility.php | Utility.applyCurrentTheme | public static function applyCurrentTheme($module = null)
{
$theme = Yii::app()->theme->name;
Yii::app()->theme = $theme;
if($module !== null) {
$themePath = Yii::getPathOfAlias('webroot.themes.'.$theme.'.views.layouts');
$module->setLayoutPath($themePath);
}
} | php | public static function applyCurrentTheme($module = null)
{
$theme = Yii::app()->theme->name;
Yii::app()->theme = $theme;
if($module !== null) {
$themePath = Yii::getPathOfAlias('webroot.themes.'.$theme.'.views.layouts');
$module->setLayoutPath($themePath);
}
} | [
"public",
"static",
"function",
"applyCurrentTheme",
"(",
"$",
"module",
"=",
"null",
")",
"{",
"$",
"theme",
"=",
"Yii",
"::",
"app",
"(",
")",
"->",
"theme",
"->",
"name",
";",
"Yii",
"::",
"app",
"(",
")",
"->",
"theme",
"=",
"$",
"theme",
";",
... | Refer layout path to current applied theme.
@param object $module that currently active [optional]
@return void | [
"Refer",
"layout",
"path",
"to",
"current",
"applied",
"theme",
"."
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L76-L85 | train |
ommu/mod-core | components/system/Utility.php | Utility.getActiveDefaultColumns | public static function getActiveDefaultColumns($columns)
{
$column = array();
foreach($columns as $val) {
$keyIndex = self::getKeyIndex($val);
if($keyIndex)
$column[] = $keyIndex;
}
return $column;
} | php | public static function getActiveDefaultColumns($columns)
{
$column = array();
foreach($columns as $val) {
$keyIndex = self::getKeyIndex($val);
if($keyIndex)
$column[] = $keyIndex;
}
return $column;
} | [
"public",
"static",
"function",
"getActiveDefaultColumns",
"(",
"$",
"columns",
")",
"{",
"$",
"column",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"columns",
"as",
"$",
"val",
")",
"{",
"$",
"keyIndex",
"=",
"self",
"::",
"getKeyIndex",
"(",
"$... | Generates key index defaultColumns in models
@return array | [
"Generates",
"key",
"index",
"defaultColumns",
"in",
"models"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L145-L156 | train |
ommu/mod-core | components/system/Utility.php | Utility.getUrlTitle | public static function getUrlTitle($str, $separator = '-', $lowercase = true) {
if($separator === 'dash') {
$separator = '-';
}
elseif($separator === 'underscore') {
$separator = '_';
}
$qSeparator = preg_quote($separator, '#');
$trans = array(
'&.+?:;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'('.$qSeparator.')+' => $separator
);
$str = strip_tags($str);
foreach ($trans as $key => $val) {
$str = preg_replace('#'.$key.'#i', $val, $str);
}
if ($lowercase === true) {
$str = strtolower($str);
}
return trim(trim($str, $separator));
} | php | public static function getUrlTitle($str, $separator = '-', $lowercase = true) {
if($separator === 'dash') {
$separator = '-';
}
elseif($separator === 'underscore') {
$separator = '_';
}
$qSeparator = preg_quote($separator, '#');
$trans = array(
'&.+?:;' => '',
'[^a-z0-9 _-]' => '',
'\s+' => $separator,
'('.$qSeparator.')+' => $separator
);
$str = strip_tags($str);
foreach ($trans as $key => $val) {
$str = preg_replace('#'.$key.'#i', $val, $str);
}
if ($lowercase === true) {
$str = strtolower($str);
}
return trim(trim($str, $separator));
} | [
"public",
"static",
"function",
"getUrlTitle",
"(",
"$",
"str",
",",
"$",
"separator",
"=",
"'-'",
",",
"$",
"lowercase",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"separator",
"===",
"'dash'",
")",
"{",
"$",
"separator",
"=",
"'-'",
";",
"}",
"elseif",... | Create URL Title
Takes a "title" string as input and creates a
human-friendly URL string with a "separator" string
as the word separator.
@todo Remove old 'dash' and 'underscore' usage in 3.1+.
@param string $str Input string
@param string $separator Word separator
(usually '-' or '_')
@param bool $lowercase Wether to transform the output string to lowercase
@return string | [
"Create",
"URL",
"Title"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L172-L198 | train |
ommu/mod-core | components/system/Utility.php | Utility.deleteFolder | public static function deleteFolder($path)
{
if(file_exists($path)) {
$fh = dir($path);
//print_r($fh);
while (false !== ($files = $fh->read())) {
/*
echo $fh->path.'/'.$files."\n";
chmod($fh->path.'/'.$files, 0755);
if(@unlink($fh->path.'/'.$files))
echo '1'."\n";
else
echo '0'."\n";
*/
@unlink($fh->path.'/'.$files);
}
$fh->close();
@rmdir($path);
return true;
} else
return false;
} | php | public static function deleteFolder($path)
{
if(file_exists($path)) {
$fh = dir($path);
//print_r($fh);
while (false !== ($files = $fh->read())) {
/*
echo $fh->path.'/'.$files."\n";
chmod($fh->path.'/'.$files, 0755);
if(@unlink($fh->path.'/'.$files))
echo '1'."\n";
else
echo '0'."\n";
*/
@unlink($fh->path.'/'.$files);
}
$fh->close();
@rmdir($path);
return true;
} else
return false;
} | [
"public",
"static",
"function",
"deleteFolder",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"fh",
"=",
"dir",
"(",
"$",
"path",
")",
";",
"//print_r($fh);\r",
"while",
"(",
"false",
"!==",
"(",
"$",
"... | remove folder and file | [
"remove",
"folder",
"and",
"file"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L203-L226 | train |
ommu/mod-core | components/system/Utility.php | Utility.recursiveDelete | public static function recursiveDelete($path) {
if(is_file($path)) {
@unlink($path);
} else {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
}elseif ($file->isDir()) {
rmdir($file->getPathname());
}elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
return false;
} | php | public static function recursiveDelete($path) {
if(is_file($path)) {
@unlink($path);
} else {
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
}elseif ($file->isDir()) {
rmdir($file->getPathname());
}elseif ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
}
}
rmdir($path);
}
return false;
} | [
"public",
"static",
"function",
"recursiveDelete",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"is_file",
"(",
"$",
"path",
")",
")",
"{",
"@",
"unlink",
"(",
"$",
"path",
")",
";",
"}",
"else",
"{",
"$",
"it",
"=",
"new",
"RecursiveIteratorIterator",
"("... | Delete files and folder recursively
@param string $path path of file/folder | [
"Delete",
"files",
"and",
"folder",
"recursively"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L428-L451 | train |
ommu/mod-core | components/system/Utility.php | Utility.getConnected | public static function getConnected($serverOptions) {
if(Yii::app()->params['server_options']['default'] == true)
$connectedUrl = Yii::app()->params['server_options']['default_host'];
else {
$connectedUrl = 'neither-connected';
foreach($serverOptions as $val) {
if(self::isServerAvailible($val)) {
$connectedUrl = $val;
break;
}
}
file_put_contents('assets/utility_server_actived.txt', $connectedUrl);
}
return $connectedUrl;
} | php | public static function getConnected($serverOptions) {
if(Yii::app()->params['server_options']['default'] == true)
$connectedUrl = Yii::app()->params['server_options']['default_host'];
else {
$connectedUrl = 'neither-connected';
foreach($serverOptions as $val) {
if(self::isServerAvailible($val)) {
$connectedUrl = $val;
break;
}
}
file_put_contents('assets/utility_server_actived.txt', $connectedUrl);
}
return $connectedUrl;
} | [
"public",
"static",
"function",
"getConnected",
"(",
"$",
"serverOptions",
")",
"{",
"if",
"(",
"Yii",
"::",
"app",
"(",
")",
"->",
"params",
"[",
"'server_options'",
"]",
"[",
"'default'",
"]",
"==",
"true",
")",
"$",
"connectedUrl",
"=",
"Yii",
"::",
... | get alternatif connected domain for inlis sso server
@param type $operator not yet using
@return type | [
"get",
"alternatif",
"connected",
"domain",
"for",
"inlis",
"sso",
"server"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L589-L606 | train |
ommu/mod-core | components/system/Utility.php | Utility.isServerAvailible | public static function isServerAvailible($domain)
{
if(Yii::app()->params['server_options']['status'] == true) {
//check, if a valid url is provided
if (!filter_var($domain, FILTER_VALIDATE_URL))
return false;
//initialize curl
$curlInit = curl_init($domain);
curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlInit,CURLOPT_HEADER,true);
curl_setopt($curlInit,CURLOPT_NOBODY,true);
curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
//get answer
$response = curl_exec($curlInit);
curl_close($curlInit);
if($response)
return true;
return false;
} else
return false;
} | php | public static function isServerAvailible($domain)
{
if(Yii::app()->params['server_options']['status'] == true) {
//check, if a valid url is provided
if (!filter_var($domain, FILTER_VALIDATE_URL))
return false;
//initialize curl
$curlInit = curl_init($domain);
curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlInit,CURLOPT_HEADER,true);
curl_setopt($curlInit,CURLOPT_NOBODY,true);
curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);
//get answer
$response = curl_exec($curlInit);
curl_close($curlInit);
if($response)
return true;
return false;
} else
return false;
} | [
"public",
"static",
"function",
"isServerAvailible",
"(",
"$",
"domain",
")",
"{",
"if",
"(",
"Yii",
"::",
"app",
"(",
")",
"->",
"params",
"[",
"'server_options'",
"]",
"[",
"'status'",
"]",
"==",
"true",
")",
"{",
"//check, if a valid url is provided\r",
"... | returns true, if domain is availible, false if not | [
"returns",
"true",
"if",
"domain",
"is",
"availible",
"false",
"if",
"not"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L609-L633 | train |
ommu/mod-core | components/system/Utility.php | Utility.getLocalDayName | public static function getLocalDayName($date, $short=true) {
$dayName = date('N', strtotime($date));
switch($dayName) {
case 0:
return ($short ? 'Min' : 'Minggu');
break;
case 1:
return ($short ? 'Sen' : 'Senin');
break;
case 2:
return ($short ? 'Sel' : 'Selasa');
break;
case 3:
return ($short ? 'Rab' : 'Rabu');
break;
case 4:
return ($short ? 'Kam' : 'Kamis');
break;
case 5:
return ($short ? 'Jum' : 'Jumat');
break;
case 6:
return ($short ? 'Sab' : 'Sabtu');
break;
}
} | php | public static function getLocalDayName($date, $short=true) {
$dayName = date('N', strtotime($date));
switch($dayName) {
case 0:
return ($short ? 'Min' : 'Minggu');
break;
case 1:
return ($short ? 'Sen' : 'Senin');
break;
case 2:
return ($short ? 'Sel' : 'Selasa');
break;
case 3:
return ($short ? 'Rab' : 'Rabu');
break;
case 4:
return ($short ? 'Kam' : 'Kamis');
break;
case 5:
return ($short ? 'Jum' : 'Jumat');
break;
case 6:
return ($short ? 'Sab' : 'Sabtu');
break;
}
} | [
"public",
"static",
"function",
"getLocalDayName",
"(",
"$",
"date",
",",
"$",
"short",
"=",
"true",
")",
"{",
"$",
"dayName",
"=",
"date",
"(",
"'N'",
",",
"strtotime",
"(",
"$",
"date",
")",
")",
";",
"switch",
"(",
"$",
"dayName",
")",
"{",
"cas... | Mengembalikan nama hari dalam bahasa indonesia.
@params short=true, tampilkan dalam 3 huruf, JUM, SAB | [
"Mengembalikan",
"nama",
"hari",
"dalam",
"bahasa",
"indonesia",
"."
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L681-L712 | train |
ommu/mod-core | components/system/Utility.php | Utility.hardDecode | public static function hardDecode($string) {
$data = htmlspecialchars_decode($string);
$data = html_entity_decode($data);
$data = strip_tags($data);
$data = chop(Utility::convert_smart_quotes($data));
$data = str_replace(array("\r", "\n", " "), "", $data);
return ($data);
} | php | public static function hardDecode($string) {
$data = htmlspecialchars_decode($string);
$data = html_entity_decode($data);
$data = strip_tags($data);
$data = chop(Utility::convert_smart_quotes($data));
$data = str_replace(array("\r", "\n", " "), "", $data);
return ($data);
} | [
"public",
"static",
"function",
"hardDecode",
"(",
"$",
"string",
")",
"{",
"$",
"data",
"=",
"htmlspecialchars_decode",
"(",
"$",
"string",
")",
";",
"$",
"data",
"=",
"html_entity_decode",
"(",
"$",
"data",
")",
";",
"$",
"data",
"=",
"strip_tags",
"("... | Super Cleaning for decode and strip all html tag | [
"Super",
"Cleaning",
"for",
"decode",
"and",
"strip",
"all",
"html",
"tag"
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L814-L822 | train |
ommu/mod-core | components/system/Utility.php | Utility.cleanImageContent | public static function cleanImageContent($content) {
$posImg = strpos($content, '<img');
$result = $content;
if($posImg !== false) {
$posClosedImg = strpos($content, '/>', $posImg) + 2;
$img = substr($content, $posImg, ($posClosedImg-$posImg));
$result = str_replace($img, '', $content);
}
return $result;
} | php | public static function cleanImageContent($content) {
$posImg = strpos($content, '<img');
$result = $content;
if($posImg !== false) {
$posClosedImg = strpos($content, '/>', $posImg) + 2;
$img = substr($content, $posImg, ($posClosedImg-$posImg));
$result = str_replace($img, '', $content);
}
return $result;
} | [
"public",
"static",
"function",
"cleanImageContent",
"(",
"$",
"content",
")",
"{",
"$",
"posImg",
"=",
"strpos",
"(",
"$",
"content",
",",
"'<img'",
")",
";",
"$",
"result",
"=",
"$",
"content",
";",
"if",
"(",
"$",
"posImg",
"!==",
"false",
")",
"{... | Ambil isi berita dan buang image darinya. | [
"Ambil",
"isi",
"berita",
"dan",
"buang",
"image",
"darinya",
"."
] | 68c90e76440e74ee93bcf82905a54d86c941b771 | https://github.com/ommu/mod-core/blob/68c90e76440e74ee93bcf82905a54d86c941b771/components/system/Utility.php#L834-L845 | train |
bright-components/services | src/Traits/CachedService.php | CachedService.resolveBaseService | private static function resolveBaseService()
{
$cachedServices = Config::get('service-classes.cached_services.classes', null);
$baseService = $cachedServices[static::class] ?? static::translateBaseService();
return resolve($baseService);
} | php | private static function resolveBaseService()
{
$cachedServices = Config::get('service-classes.cached_services.classes', null);
$baseService = $cachedServices[static::class] ?? static::translateBaseService();
return resolve($baseService);
} | [
"private",
"static",
"function",
"resolveBaseService",
"(",
")",
"{",
"$",
"cachedServices",
"=",
"Config",
"::",
"get",
"(",
"'service-classes.cached_services.classes'",
",",
"null",
")",
";",
"$",
"baseService",
"=",
"$",
"cachedServices",
"[",
"static",
"::",
... | Resolve the base service for the cached service.
@return string | [
"Resolve",
"the",
"base",
"service",
"for",
"the",
"cached",
"service",
"."
] | c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc | https://github.com/bright-components/services/blob/c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc/src/Traits/CachedService.php#L28-L35 | train |
bright-components/services | src/Traits/CachedService.php | CachedService.translateBaseService | private static function translateBaseService()
{
$cachedServicePrefix = Config::get('service-classes.cached_services.prefix');
$cachedServiceNamespace = '\\'.Config::get('service-classes.cached_services.namespace');
return str_replace([$cachedServicePrefix, $cachedServiceNamespace], ['', ''], static::class);
} | php | private static function translateBaseService()
{
$cachedServicePrefix = Config::get('service-classes.cached_services.prefix');
$cachedServiceNamespace = '\\'.Config::get('service-classes.cached_services.namespace');
return str_replace([$cachedServicePrefix, $cachedServiceNamespace], ['', ''], static::class);
} | [
"private",
"static",
"function",
"translateBaseService",
"(",
")",
"{",
"$",
"cachedServicePrefix",
"=",
"Config",
"::",
"get",
"(",
"'service-classes.cached_services.prefix'",
")",
";",
"$",
"cachedServiceNamespace",
"=",
"'\\\\'",
".",
"Config",
"::",
"get",
"(",
... | Translate the cached service name to the base service name.
@return string | [
"Translate",
"the",
"cached",
"service",
"name",
"to",
"the",
"base",
"service",
"name",
"."
] | c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc | https://github.com/bright-components/services/blob/c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc/src/Traits/CachedService.php#L42-L48 | train |
k3ssen/GeneratorBundle | MetaData/MetaEntity.php | MetaEntity.getBundleName | public function getBundleName(): ?string
{
if ($this->getBundleNamespace() === static::NO_BUNDLE_NAMESPACE) {
return null;
}
if (strpos('\\', $this->getBundleNamespace()) !== false) {
$parts = explode('\\', $this->getBundleNamespace());
return array_pop($parts);
}
return $this->getBundleNamespace();
} | php | public function getBundleName(): ?string
{
if ($this->getBundleNamespace() === static::NO_BUNDLE_NAMESPACE) {
return null;
}
if (strpos('\\', $this->getBundleNamespace()) !== false) {
$parts = explode('\\', $this->getBundleNamespace());
return array_pop($parts);
}
return $this->getBundleNamespace();
} | [
"public",
"function",
"getBundleName",
"(",
")",
":",
"?",
"string",
"{",
"if",
"(",
"$",
"this",
"->",
"getBundleNamespace",
"(",
")",
"===",
"static",
"::",
"NO_BUNDLE_NAMESPACE",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"strpos",
"(",
"'\\\\'"... | Gets bundle name by retrieving the last part of the bundleNamespace
@return string | [
"Gets",
"bundle",
"name",
"by",
"retrieving",
"the",
"last",
"part",
"of",
"the",
"bundleNamespace"
] | 2229b54d69ab7782eb722ee483607886f94849c8 | https://github.com/k3ssen/GeneratorBundle/blob/2229b54d69ab7782eb722ee483607886f94849c8/MetaData/MetaEntity.php#L77-L87 | train |
excelwebzone/Omlex | lib/Omlex/Provider.php | Provider.match | public function match($url)
{
if (!$this->schemes) {
return true;
}
foreach ($this->schemes as $scheme) {
if ($scheme->match($url)) {
return true;
}
}
return false;
} | php | public function match($url)
{
if (!$this->schemes) {
return true;
}
foreach ($this->schemes as $scheme) {
if ($scheme->match($url)) {
return true;
}
}
return false;
} | [
"public",
"function",
"match",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"schemes",
")",
"{",
"return",
"true",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"schemes",
"as",
"$",
"scheme",
")",
"{",
"if",
"(",
"$",
"scheme",
... | Check whether the given URL match one of the provider's schemes
@param string $url The URL to check against
@return Boolean True if match, false if not | [
"Check",
"whether",
"the",
"given",
"URL",
"match",
"one",
"of",
"the",
"provider",
"s",
"schemes"
] | 88fa11bf02d1ab364fbc1cba208e82156d5ef784 | https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/Provider.php#L82-L95 | train |
excelwebzone/Omlex | lib/Omlex/Object.php | Object.factory | static public function factory($object)
{
if (!isset($object->type)) {
throw new ObjectException('The object has no type.');
}
$type = (string)$object->type;
if (!isset(self::$types[$type])) {
throw new NoSupportException(sprintf('The object type "%s" is unknown or invalid.', $type));
}
$class = '\\Omlex\\Object\\'.self::$types[$type];
if (!class_exists($class)) {
throw new ObjectException(sprintf('The object class "%s" is invalid or not found.', $class));
}
$instance = new $class($object);
return $instance;
} | php | static public function factory($object)
{
if (!isset($object->type)) {
throw new ObjectException('The object has no type.');
}
$type = (string)$object->type;
if (!isset(self::$types[$type])) {
throw new NoSupportException(sprintf('The object type "%s" is unknown or invalid.', $type));
}
$class = '\\Omlex\\Object\\'.self::$types[$type];
if (!class_exists($class)) {
throw new ObjectException(sprintf('The object class "%s" is invalid or not found.', $class));
}
$instance = new $class($object);
return $instance;
} | [
"static",
"public",
"function",
"factory",
"(",
"$",
"object",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"object",
"->",
"type",
")",
")",
"{",
"throw",
"new",
"ObjectException",
"(",
"'The object has no type.'",
")",
";",
"}",
"$",
"type",
"=",
"("... | Create an Omlex object from result
@param object $object Raw object returned from API
@return object Instance of object driver
@throws ObjectException On object errors
@throws NoSupportException When object type is not supported or unknown | [
"Create",
"an",
"Omlex",
"object",
"from",
"result"
] | 88fa11bf02d1ab364fbc1cba208e82156d5ef784 | https://github.com/excelwebzone/Omlex/blob/88fa11bf02d1ab364fbc1cba208e82156d5ef784/lib/Omlex/Object.php#L46-L64 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php | ConfigurableAttachmentsTrait.setConfig | public function setConfig($config)
{
if (is_array($config)) {
$this->config = $this->createConfig($config);
} elseif ($config instanceof ConfigInterface) {
$this->config = $config;
} else {
throw new InvalidArgumentException(
'Configuration must be an array or a ConfigInterface object.'
);
}
return $this;
} | php | public function setConfig($config)
{
if (is_array($config)) {
$this->config = $this->createConfig($config);
} elseif ($config instanceof ConfigInterface) {
$this->config = $config;
} else {
throw new InvalidArgumentException(
'Configuration must be an array or a ConfigInterface object.'
);
}
return $this;
} | [
"public",
"function",
"setConfig",
"(",
"$",
"config",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"config",
")",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"this",
"->",
"createConfig",
"(",
"$",
"config",
")",
";",
"}",
"elseif",
"(",
"$",
... | Set the object's configuration container.
@param ConfigInterface|array $config The datas to set.
@throws InvalidArgumentException If the parameter is invalid.
@return ConfigurableInterface Chainable | [
"Set",
"the",
"object",
"s",
"configuration",
"container",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php#L40-L52 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php | ConfigurableAttachmentsTrait.config | public function config($key = null)
{
if ($this->config === null) {
$this->config = $this->createConfig();
}
if ($key !== null) {
return $this->config->get($key);
} else {
return $this->config;
}
} | php | public function config($key = null)
{
if ($this->config === null) {
$this->config = $this->createConfig();
}
if ($key !== null) {
return $this->config->get($key);
} else {
return $this->config;
}
} | [
"public",
"function",
"config",
"(",
"$",
"key",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"config",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"config",
"=",
"$",
"this",
"->",
"createConfig",
"(",
")",
";",
"}",
"if",
"(",
"$",
"k... | Retrieve the object's configuration container, or one of its entry.
If the object has no existing config, create one.
If a key is provided, return the configuration key value instead of the full object.
@param string $key Optional. If provided, the config key value will be returned, instead of the full object.
@return ConfigInterface | [
"Retrieve",
"the",
"object",
"s",
"configuration",
"container",
"or",
"one",
"of",
"its",
"entry",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php#L64-L75 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php | ConfigurableAttachmentsTrait.mergePresets | protected function mergePresets(array $data)
{
if (isset($data['attachable_objects'])) {
$data['attachable_objects'] = $this->mergePresetAttachableObjects($data['attachable_objects']);
}
if (isset($data['default_attachable_objects'])) {
$data['attachable_objects'] = $this->mergePresetAttachableObjects($data['default_attachable_objects']);
}
if (isset($data['preset'])) {
$data = $this->mergePresetWidget($data);
}
return $data;
} | php | protected function mergePresets(array $data)
{
if (isset($data['attachable_objects'])) {
$data['attachable_objects'] = $this->mergePresetAttachableObjects($data['attachable_objects']);
}
if (isset($data['default_attachable_objects'])) {
$data['attachable_objects'] = $this->mergePresetAttachableObjects($data['default_attachable_objects']);
}
if (isset($data['preset'])) {
$data = $this->mergePresetWidget($data);
}
return $data;
} | [
"protected",
"function",
"mergePresets",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'attachable_objects'",
"]",
")",
")",
"{",
"$",
"data",
"[",
"'attachable_objects'",
"]",
"=",
"$",
"this",
"->",
"mergePresetAttachab... | Parse the given data and recursively merge presets from attachments config.
@param array $data The widget data.
@return array Returns the merged widget data. | [
"Parse",
"the",
"given",
"data",
"and",
"recursively",
"merge",
"presets",
"from",
"attachments",
"config",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php#L94-L109 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php | ConfigurableAttachmentsTrait.mergePresetWidget | private function mergePresetWidget(array $data)
{
if (!isset($data['preset']) || !is_string($data['preset'])) {
return $data;
}
$widgetIdent = $data['preset'];
if ($this instanceof ObjectContainerInterface) {
if ($this->hasObj()) {
$widgetIdent = $this->obj()->render($widgetIdent);
}
} elseif ($this instanceof ModelInterface) {
$widgetIdent = $this->render($widgetIdent);
}
$presetWidgets = $this->config('widgets');
if (!isset($presetWidgets[$widgetIdent])) {
return $data;
}
$widgetData = $presetWidgets[$widgetIdent];
if (isset($widgetData['attachable_objects'])) {
$widgetData['attachable_objects'] = $this->mergePresetAttachableObjects(
$widgetData['attachable_objects']
);
}
if (isset($widgetData['default_attachable_objects'])) {
$widgetData['attachable_objects'] = $this->mergePresetAttachableObjects(
$widgetData['default_attachable_objects']
);
}
return array_replace_recursive($widgetData, $data);
} | php | private function mergePresetWidget(array $data)
{
if (!isset($data['preset']) || !is_string($data['preset'])) {
return $data;
}
$widgetIdent = $data['preset'];
if ($this instanceof ObjectContainerInterface) {
if ($this->hasObj()) {
$widgetIdent = $this->obj()->render($widgetIdent);
}
} elseif ($this instanceof ModelInterface) {
$widgetIdent = $this->render($widgetIdent);
}
$presetWidgets = $this->config('widgets');
if (!isset($presetWidgets[$widgetIdent])) {
return $data;
}
$widgetData = $presetWidgets[$widgetIdent];
if (isset($widgetData['attachable_objects'])) {
$widgetData['attachable_objects'] = $this->mergePresetAttachableObjects(
$widgetData['attachable_objects']
);
}
if (isset($widgetData['default_attachable_objects'])) {
$widgetData['attachable_objects'] = $this->mergePresetAttachableObjects(
$widgetData['default_attachable_objects']
);
}
return array_replace_recursive($widgetData, $data);
} | [
"private",
"function",
"mergePresetWidget",
"(",
"array",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"data",
"[",
"'preset'",
"]",
")",
"||",
"!",
"is_string",
"(",
"$",
"data",
"[",
"'preset'",
"]",
")",
")",
"{",
"return",
"$",
"da... | Parse the given data and merge the widget preset.
@param array $data The widget data.
@return array Returns the merged widget data. | [
"Parse",
"the",
"given",
"data",
"and",
"merge",
"the",
"widget",
"preset",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php#L117-L152 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php | ConfigurableAttachmentsTrait.mergePresetAttachableObjects | private function mergePresetAttachableObjects($data)
{
if (is_string($data)) {
$groupIdent = $data;
if ($this instanceof ObjectContainerInterface) {
if ($this->hasObj()) {
$groupIdent = $this->obj()->render($groupIdent);
}
} elseif ($this instanceof ModelInterface) {
$groupIdent = $this->render($groupIdent);
}
$presetGroups = $this->config('groups');
if (isset($presetGroups[$groupIdent])) {
$data = $presetGroups[$groupIdent];
}
}
if (is_array($data)) {
$presetTypes = $this->config('attachables');
$attachables = [];
foreach ($data as $attType => $attStruct) {
if (is_string($attStruct)) {
$attType = $attStruct;
$attStruct = [];
}
if (!is_string($attType)) {
throw new InvalidArgumentException(
'The attachment type must be a string'
);
}
if (!is_array($attStruct)) {
throw new InvalidArgumentException(sprintf(
'The attachment structure for "%s" must be an array',
$attType
));
}
if (isset($presetTypes[$attType])) {
$attStruct = array_replace_recursive(
$presetTypes[$attType],
$attStruct
);
}
$attachables[$attType] = $attStruct;
}
$data = $attachables;
}
return $data;
} | php | private function mergePresetAttachableObjects($data)
{
if (is_string($data)) {
$groupIdent = $data;
if ($this instanceof ObjectContainerInterface) {
if ($this->hasObj()) {
$groupIdent = $this->obj()->render($groupIdent);
}
} elseif ($this instanceof ModelInterface) {
$groupIdent = $this->render($groupIdent);
}
$presetGroups = $this->config('groups');
if (isset($presetGroups[$groupIdent])) {
$data = $presetGroups[$groupIdent];
}
}
if (is_array($data)) {
$presetTypes = $this->config('attachables');
$attachables = [];
foreach ($data as $attType => $attStruct) {
if (is_string($attStruct)) {
$attType = $attStruct;
$attStruct = [];
}
if (!is_string($attType)) {
throw new InvalidArgumentException(
'The attachment type must be a string'
);
}
if (!is_array($attStruct)) {
throw new InvalidArgumentException(sprintf(
'The attachment structure for "%s" must be an array',
$attType
));
}
if (isset($presetTypes[$attType])) {
$attStruct = array_replace_recursive(
$presetTypes[$attType],
$attStruct
);
}
$attachables[$attType] = $attStruct;
}
$data = $attachables;
}
return $data;
} | [
"private",
"function",
"mergePresetAttachableObjects",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"data",
")",
")",
"{",
"$",
"groupIdent",
"=",
"$",
"data",
";",
"if",
"(",
"$",
"this",
"instanceof",
"ObjectContainerInterface",
")",
"{"... | Parse the given data and merge the preset attachment types.
@param string|array $data The attachable objects data.
@throws InvalidArgumentException If the attachment type or structure is invalid.
@return array Returns the merged attachable objects data. | [
"Parse",
"the",
"given",
"data",
"and",
"merge",
"the",
"preset",
"attachment",
"types",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/ConfigurableAttachmentsTrait.php#L161-L215 | train |
TuumPHP/Respond | src/Responder/View.php | View.call | public function call($presenter, array $data = [])
{
if ($presenter instanceof PresenterInterface) {
return $this->callPresenter([$presenter, '__invoke'], $data);
}
if (is_callable($presenter)) {
return $this->callPresenter($presenter, $data);
}
if ($resolver = $this->builder->getContainer()) {
return $this->callPresenter($resolver->get($presenter), $data);
}
throw new \BadMethodCallException('cannot resolve a presenter.');
} | php | public function call($presenter, array $data = [])
{
if ($presenter instanceof PresenterInterface) {
return $this->callPresenter([$presenter, '__invoke'], $data);
}
if (is_callable($presenter)) {
return $this->callPresenter($presenter, $data);
}
if ($resolver = $this->builder->getContainer()) {
return $this->callPresenter($resolver->get($presenter), $data);
}
throw new \BadMethodCallException('cannot resolve a presenter.');
} | [
"public",
"function",
"call",
"(",
"$",
"presenter",
",",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"presenter",
"instanceof",
"PresenterInterface",
")",
"{",
"return",
"$",
"this",
"->",
"callPresenter",
"(",
"[",
"$",
"presenter",
... | calls the presenter to create a view to respond.
@param callable|PresenterInterface|string $presenter
@param array $data
@return ResponseInterface | [
"calls",
"the",
"presenter",
"to",
"create",
"a",
"view",
"to",
"respond",
"."
] | 5861ec0bffc97c500d88bf307a53277f1c2fe12f | https://github.com/TuumPHP/Respond/blob/5861ec0bffc97c500d88bf307a53277f1c2fe12f/src/Responder/View.php#L214-L226 | train |
froq/froq-http | src/request/Method.php | Method.isAjax | public function isAjax(): bool
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
return (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
if (isset($_SERVER['HTTP_X_AJAX'])) {
return (strtolower($_SERVER['HTTP_X_AJAX']) == 'true' || $_SERVER['HTTP_X_AJAX'] == '1');
}
return false;
} | php | public function isAjax(): bool
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
return (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
if (isset($_SERVER['HTTP_X_AJAX'])) {
return (strtolower($_SERVER['HTTP_X_AJAX']) == 'true' || $_SERVER['HTTP_X_AJAX'] == '1');
}
return false;
} | [
"public",
"function",
"isAjax",
"(",
")",
":",
"bool",
"{",
"if",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_REQUESTED_WITH'",
"]",
")",
")",
"{",
"return",
"(",
"strtolower",
"(",
"$",
"_SERVER",
"[",
"'HTTP_X_REQUESTED_WITH'",
"]",
")",
"==",
"'x... | Is ajax.
@return bool | [
"Is",
"ajax",
"."
] | 067207669b5054b867b7df2b5557acf1d43f572a | https://github.com/froq/froq-http/blob/067207669b5054b867b7df2b5557acf1d43f572a/src/request/Method.php#L186-L197 | train |
mirko-pagliai/me-cms | src/Controller/Admin/PhotosController.php | PhotosController.index | public function index()
{
//The "render" type can set by query or by cookies
$render = $this->request->getQuery('render', $this->request->getCookie('render-photos'));
$query = $this->Photos->find()->contain(['Albums' => ['fields' => ['id', 'slug', 'title']]]);
$this->paginate['order'] = ['Photos.created' => 'DESC'];
//Sets the paginate limit and the maximum paginate limit
//See http://book.cakephp.org/3.0/en/controllers/components/pagination.html#limit-the-maximum-number-of-rows-that-can-be-fetched
if ($render === 'grid') {
$this->paginate['limit'] = $this->paginate['maxLimit'] = getConfigOrFail('admin.photos');
$this->viewBuilder()->setTemplate('index_as_grid');
}
$this->set('photos', $this->paginate($this->Photos->queryFromFilter($query, $this->request->getQueryParams())));
if ($render) {
$this->response = $this->response->withCookie((new Cookie('render-photos', $render))->withNeverExpire());
}
} | php | public function index()
{
//The "render" type can set by query or by cookies
$render = $this->request->getQuery('render', $this->request->getCookie('render-photos'));
$query = $this->Photos->find()->contain(['Albums' => ['fields' => ['id', 'slug', 'title']]]);
$this->paginate['order'] = ['Photos.created' => 'DESC'];
//Sets the paginate limit and the maximum paginate limit
//See http://book.cakephp.org/3.0/en/controllers/components/pagination.html#limit-the-maximum-number-of-rows-that-can-be-fetched
if ($render === 'grid') {
$this->paginate['limit'] = $this->paginate['maxLimit'] = getConfigOrFail('admin.photos');
$this->viewBuilder()->setTemplate('index_as_grid');
}
$this->set('photos', $this->paginate($this->Photos->queryFromFilter($query, $this->request->getQueryParams())));
if ($render) {
$this->response = $this->response->withCookie((new Cookie('render-photos', $render))->withNeverExpire());
}
} | [
"public",
"function",
"index",
"(",
")",
"{",
"//The \"render\" type can set by query or by cookies",
"$",
"render",
"=",
"$",
"this",
"->",
"request",
"->",
"getQuery",
"(",
"'render'",
",",
"$",
"this",
"->",
"request",
"->",
"getCookie",
"(",
"'render-photos'",... | Lists photos.
This action can use the `index_as_grid` template.
@return \Cake\Network\Response|null|void
@uses MeCms\Model\Table\PhotosTable::queryFromFilter() | [
"Lists",
"photos",
"."
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Controller/Admin/PhotosController.php#L71-L92 | train |
PitonCMS/Engine | app/Controllers/AdminMediaController.php | AdminMediaController.showMedia | public function showMedia()
{
$mediaMapper = ($this->container->dataMapper)('MediaMapper');
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$data['media'] = $mediaMapper->find();
$data['categories'] = $mediaCategoryMapper->findCategories();
$cats = $mediaCategoryMapper->findAllMediaCategoryAssignments();
// Assign any category ID's to each medium
foreach ($data['media'] as $key => &$medium) {
$medium->category = [];
foreach ($cats as $cat) {
if ($medium->id === $cat->media_id) {
$medium->category[$cat->category_id] = 'on';
}
}
}
return $this->render('media/media.html', $data);
} | php | public function showMedia()
{
$mediaMapper = ($this->container->dataMapper)('MediaMapper');
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$data['media'] = $mediaMapper->find();
$data['categories'] = $mediaCategoryMapper->findCategories();
$cats = $mediaCategoryMapper->findAllMediaCategoryAssignments();
// Assign any category ID's to each medium
foreach ($data['media'] as $key => &$medium) {
$medium->category = [];
foreach ($cats as $cat) {
if ($medium->id === $cat->media_id) {
$medium->category[$cat->category_id] = 'on';
}
}
}
return $this->render('media/media.html', $data);
} | [
"public",
"function",
"showMedia",
"(",
")",
"{",
"$",
"mediaMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'MediaMapper'",
")",
";",
"$",
"mediaCategoryMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper... | Show All Media | [
"Show",
"All",
"Media"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminMediaController.php#L34-L54 | train |
PitonCMS/Engine | app/Controllers/AdminMediaController.php | AdminMediaController.getMedia | public function getMedia()
{
$mediaMapper = ($this->container->dataMapper)('MediaMapper');
$data = $mediaMapper->find();
$template = <<<HTML
{% import "@admin/media/_mediaCardMacro.html" as file %}
<div class="card-wrapper">
{% for media in page.media %}
{{ file.mediaCard(media) }}
{% endfor %}
</div>
HTML;
$mediaHtml = $this->container->view->fetchFromString($template, ['page' => ['media' => $data]]);
$response = $this->response->withHeader('Content-Type', 'application/json');
return $response->write(json_encode(["html" => $mediaHtml]));
} | php | public function getMedia()
{
$mediaMapper = ($this->container->dataMapper)('MediaMapper');
$data = $mediaMapper->find();
$template = <<<HTML
{% import "@admin/media/_mediaCardMacro.html" as file %}
<div class="card-wrapper">
{% for media in page.media %}
{{ file.mediaCard(media) }}
{% endfor %}
</div>
HTML;
$mediaHtml = $this->container->view->fetchFromString($template, ['page' => ['media' => $data]]);
$response = $this->response->withHeader('Content-Type', 'application/json');
return $response->write(json_encode(["html" => $mediaHtml]));
} | [
"public",
"function",
"getMedia",
"(",
")",
"{",
"$",
"mediaMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'MediaMapper'",
")",
";",
"$",
"data",
"=",
"$",
"mediaMapper",
"->",
"find",
"(",
")",
";",
"$",
"template",
... | Get All Media
Gets all media asynchronously with HTML | [
"Get",
"All",
"Media"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminMediaController.php#L120-L140 | train |
PitonCMS/Engine | app/Controllers/AdminMediaController.php | AdminMediaController.editMediaCategories | public function editMediaCategories()
{
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$data = $mediaCategoryMapper->find();
return $this->render('media/mediaCategories.html', ['categories' => $data]);
} | php | public function editMediaCategories()
{
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$data = $mediaCategoryMapper->find();
return $this->render('media/mediaCategories.html', ['categories' => $data]);
} | [
"public",
"function",
"editMediaCategories",
"(",
")",
"{",
"$",
"mediaCategoryMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'MediaCategoryMapper'",
")",
";",
"$",
"data",
"=",
"$",
"mediaCategoryMapper",
"->",
"find",
"(",
... | Edit Media Categories | [
"Edit",
"Media",
"Categories"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminMediaController.php#L166-L173 | train |
PitonCMS/Engine | app/Controllers/AdminMediaController.php | AdminMediaController.saveMediaCategories | public function saveMediaCategories()
{
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$categoriesPost = $this->request->getParsedBody();
foreach ($categoriesPost['category'] as $key => $cat) {
// Skip if category name is empty
if (empty($cat)) {
continue;
}
// Make category object
$category = $mediaCategoryMapper->make();
$category->id = $categoriesPost['id'][$key];
// Check if we need to delete a category, but only if this has been previously saved with an ID
if (isset($categoriesPost['delete'][$key]) && !empty($categoriesPost['id'][$key])) {
$mediaCategoryMapper->delete($category);
}
// Save
$category->category = $cat;
$mediaCategoryMapper->save($category);
}
// Return to showing categories
return $this->redirect('adminEditMediaCategories');
} | php | public function saveMediaCategories()
{
$mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');
$categoriesPost = $this->request->getParsedBody();
foreach ($categoriesPost['category'] as $key => $cat) {
// Skip if category name is empty
if (empty($cat)) {
continue;
}
// Make category object
$category = $mediaCategoryMapper->make();
$category->id = $categoriesPost['id'][$key];
// Check if we need to delete a category, but only if this has been previously saved with an ID
if (isset($categoriesPost['delete'][$key]) && !empty($categoriesPost['id'][$key])) {
$mediaCategoryMapper->delete($category);
}
// Save
$category->category = $cat;
$mediaCategoryMapper->save($category);
}
// Return to showing categories
return $this->redirect('adminEditMediaCategories');
} | [
"public",
"function",
"saveMediaCategories",
"(",
")",
"{",
"$",
"mediaCategoryMapper",
"=",
"(",
"$",
"this",
"->",
"container",
"->",
"dataMapper",
")",
"(",
"'MediaCategoryMapper'",
")",
";",
"$",
"categoriesPost",
"=",
"$",
"this",
"->",
"request",
"->",
... | Save Media Categories | [
"Save",
"Media",
"Categories"
] | 51622658cbd21946757abc27f6928cb482384659 | https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminMediaController.php#L178-L206 | train |
mirko-pagliai/me-cms | src/View/View.php | View.getTitleForLayout | protected function getTitleForLayout()
{
if (!empty($this->titleForLayout)) {
return $this->titleForLayout;
}
//Gets the main title setted by the configuration
$title = getConfigOrFail('main.title');
//For homepage, it returns only the main title
if ($this->request->isUrl(['_name' => 'homepage'])) {
return $title;
}
//If exists, it adds the title setted by the controller, as if it has
// been set via `$this->View->set()`
if ($this->get('title')) {
$title = sprintf('%s - %s', $this->get('title'), $title);
//Else, if exists, it adds the title setted by the current view, as if
// it has been set via `$this->View->Blocks->set()`
} elseif ($this->fetch('title')) {
$title = sprintf('%s - %s', $this->fetch('title'), $title);
}
return $this->titleForLayout = $title;
} | php | protected function getTitleForLayout()
{
if (!empty($this->titleForLayout)) {
return $this->titleForLayout;
}
//Gets the main title setted by the configuration
$title = getConfigOrFail('main.title');
//For homepage, it returns only the main title
if ($this->request->isUrl(['_name' => 'homepage'])) {
return $title;
}
//If exists, it adds the title setted by the controller, as if it has
// been set via `$this->View->set()`
if ($this->get('title')) {
$title = sprintf('%s - %s', $this->get('title'), $title);
//Else, if exists, it adds the title setted by the current view, as if
// it has been set via `$this->View->Blocks->set()`
} elseif ($this->fetch('title')) {
$title = sprintf('%s - %s', $this->fetch('title'), $title);
}
return $this->titleForLayout = $title;
} | [
"protected",
"function",
"getTitleForLayout",
"(",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"titleForLayout",
")",
")",
"{",
"return",
"$",
"this",
"->",
"titleForLayout",
";",
"}",
"//Gets the main title setted by the configuration",
"$",
"tit... | Gets the title for layout
@return string Title
@uses $titleForLayout | [
"Gets",
"the",
"title",
"for",
"layout"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/View.php#L40-L65 | train |
miBadger/miBadger.ActiveRecord | src/AbstractActiveRecord.php | AbstractActiveRecord.getSearchQueryResult | private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
{
$query = (new Query($this->getPdo(), $this->getActiveRecordTable()))
->select();
$this->getSearchQueryWhere($query, $where);
$this->getSearchQueryOrderBy($query, $orderBy);
$this->getSearchQueryLimit($query, $limit, $offset);
return $query->execute();
} | php | private function getSearchQueryResult(array $where = [], array $orderBy = [], $limit = -1, $offset = 0)
{
$query = (new Query($this->getPdo(), $this->getActiveRecordTable()))
->select();
$this->getSearchQueryWhere($query, $where);
$this->getSearchQueryOrderBy($query, $orderBy);
$this->getSearchQueryLimit($query, $limit, $offset);
return $query->execute();
} | [
"private",
"function",
"getSearchQueryResult",
"(",
"array",
"$",
"where",
"=",
"[",
"]",
",",
"array",
"$",
"orderBy",
"=",
"[",
"]",
",",
"$",
"limit",
"=",
"-",
"1",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"$",
"query",
"=",
"(",
"new",
"Query... | Returns the search query result with the given where, order by, limit and offset clauses.
@param array $where = []
@param array $orderBy = []
@param int $limit = -1
@param int $offset = 0
@return \miBadger\Query\QueryResult the search query result with the given where, order by, limit and offset clauses. | [
"Returns",
"the",
"search",
"query",
"result",
"with",
"the",
"given",
"where",
"order",
"by",
"limit",
"and",
"offset",
"clauses",
"."
] | b78f9dcf96ea5433ef8239bc02bad5f02960fe5f | https://github.com/miBadger/miBadger.ActiveRecord/blob/b78f9dcf96ea5433ef8239bc02bad5f02960fe5f/src/AbstractActiveRecord.php#L203-L213 | train |
miBadger/miBadger.ActiveRecord | src/AbstractActiveRecord.php | AbstractActiveRecord.getSearchQueryWhere | private function getSearchQueryWhere($query, $where)
{
foreach ($where as $key => $value) {
$query->where($value[0], $value[1], $value[2]);
}
return $query;
} | php | private function getSearchQueryWhere($query, $where)
{
foreach ($where as $key => $value) {
$query->where($value[0], $value[1], $value[2]);
}
return $query;
} | [
"private",
"function",
"getSearchQueryWhere",
"(",
"$",
"query",
",",
"$",
"where",
")",
"{",
"foreach",
"(",
"$",
"where",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"query",
"->",
"where",
"(",
"$",
"value",
"[",
"0",
"]",
",",
"$",
"... | Returns the given query after adding the given where conditions.
@param \miBadger\Query\Query $query
@param array $where
@return \miBadger\Query\Query the given query after adding the given where conditions. | [
"Returns",
"the",
"given",
"query",
"after",
"adding",
"the",
"given",
"where",
"conditions",
"."
] | b78f9dcf96ea5433ef8239bc02bad5f02960fe5f | https://github.com/miBadger/miBadger.ActiveRecord/blob/b78f9dcf96ea5433ef8239bc02bad5f02960fe5f/src/AbstractActiveRecord.php#L222-L229 | train |
miBadger/miBadger.ActiveRecord | src/AbstractActiveRecord.php | AbstractActiveRecord.getSearchQueryOrderBy | private function getSearchQueryOrderBy($query, $orderBy)
{
foreach ($orderBy as $key => $value) {
$query->orderBy($key, $value);
}
return $query;
} | php | private function getSearchQueryOrderBy($query, $orderBy)
{
foreach ($orderBy as $key => $value) {
$query->orderBy($key, $value);
}
return $query;
} | [
"private",
"function",
"getSearchQueryOrderBy",
"(",
"$",
"query",
",",
"$",
"orderBy",
")",
"{",
"foreach",
"(",
"$",
"orderBy",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"query",
"->",
"orderBy",
"(",
"$",
"key",
",",
"$",
"value",
")",
... | Returns the given query after adding the given order by conditions.
@param \miBadger\Query\Query $query
@param array $orderBy
@return \miBadger\Query\Query the given query after adding the given order by conditions. | [
"Returns",
"the",
"given",
"query",
"after",
"adding",
"the",
"given",
"order",
"by",
"conditions",
"."
] | b78f9dcf96ea5433ef8239bc02bad5f02960fe5f | https://github.com/miBadger/miBadger.ActiveRecord/blob/b78f9dcf96ea5433ef8239bc02bad5f02960fe5f/src/AbstractActiveRecord.php#L238-L245 | train |
miBadger/miBadger.ActiveRecord | src/AbstractActiveRecord.php | AbstractActiveRecord.getSearchQueryLimit | private function getSearchQueryLimit($query, $limit, $offset)
{
if ($limit > -1) {
$query->limit($limit);
$query->offset($offset);
}
return $query;
} | php | private function getSearchQueryLimit($query, $limit, $offset)
{
if ($limit > -1) {
$query->limit($limit);
$query->offset($offset);
}
return $query;
} | [
"private",
"function",
"getSearchQueryLimit",
"(",
"$",
"query",
",",
"$",
"limit",
",",
"$",
"offset",
")",
"{",
"if",
"(",
"$",
"limit",
">",
"-",
"1",
")",
"{",
"$",
"query",
"->",
"limit",
"(",
"$",
"limit",
")",
";",
"$",
"query",
"->",
"off... | Returns the given query after adding the given limit and offset conditions.
@param \miBadger\Query\Query $query
@param int $limit
@param int $offset
@return \miBadger\Query\Query the given query after adding the given limit and offset conditions. | [
"Returns",
"the",
"given",
"query",
"after",
"adding",
"the",
"given",
"limit",
"and",
"offset",
"conditions",
"."
] | b78f9dcf96ea5433ef8239bc02bad5f02960fe5f | https://github.com/miBadger/miBadger.ActiveRecord/blob/b78f9dcf96ea5433ef8239bc02bad5f02960fe5f/src/AbstractActiveRecord.php#L255-L263 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php | AttachmentContainerTrait.attachmentsMetadata | public function attachmentsMetadata()
{
if ($this->attachmentsMetadata === null) {
$this->attachmentsMetadata = [];
$metadata = $this->metadata();
if (isset($metadata['attachments'])) {
$this->attachmentsMetadata = $this->mergePresets($metadata['attachments']);
}
}
return $this->attachmentsMetadata;
} | php | public function attachmentsMetadata()
{
if ($this->attachmentsMetadata === null) {
$this->attachmentsMetadata = [];
$metadata = $this->metadata();
if (isset($metadata['attachments'])) {
$this->attachmentsMetadata = $this->mergePresets($metadata['attachments']);
}
}
return $this->attachmentsMetadata;
} | [
"public",
"function",
"attachmentsMetadata",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"attachmentsMetadata",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"attachmentsMetadata",
"=",
"[",
"]",
";",
"$",
"metadata",
"=",
"$",
"this",
"->",
"metadata",
"... | Retrieve the attachments configuration from this object's metadata.
@return array | [
"Retrieve",
"the",
"attachments",
"configuration",
"from",
"this",
"object",
"s",
"metadata",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php#L56-L68 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php | AttachmentContainerTrait.attachmentGroup | public function attachmentGroup()
{
if ($this->group === null) {
$config = $this->attachmentsMetadata();
$group = AttachmentContainerInterface::DEFAULT_GROUPING;
if (isset($config['group'])) {
$group = $config['group'];
// If the 'default_group' is not set, search for it.
} elseif (isset($config['default_group'])) {
$group = $config['default_group'];
// If the 'default_group' is not set, search for it.
} elseif (isset($config['default_widget'])) {
$widget = $config['default_widget'];
$metadata = $this->metadata();
$found = false;
if (isset($metadata['admin']['form_groups'][$widget]['group'])) {
$group = $metadata['admin']['form_groups'][$widget]['group'];
$found = true;
}
if (!$found && isset($metadata['admin']['forms'])) {
foreach ($metadata['admin']['forms'] as $form) {
if (isset($form['groups'][$widget]['group'])) {
$group = $form['groups'][$widget]['group'];
$found = true;
break;
}
}
}
if (!$found && isset($metadata['admin']['dashboards'])) {
foreach ($metadata['admin']['dashboards'] as $dashboard) {
if (isset($dashboard['widgets'][$widget]['group'])) {
$group = $dashboard['widgets'][$widget]['group'];
$found = true;
break;
}
}
}
}
if (!is_string($group)) {
throw new UnexpectedValueException('The attachment grouping must be a string.');
}
$this->group = $group;
}
return $this->group;
} | php | public function attachmentGroup()
{
if ($this->group === null) {
$config = $this->attachmentsMetadata();
$group = AttachmentContainerInterface::DEFAULT_GROUPING;
if (isset($config['group'])) {
$group = $config['group'];
// If the 'default_group' is not set, search for it.
} elseif (isset($config['default_group'])) {
$group = $config['default_group'];
// If the 'default_group' is not set, search for it.
} elseif (isset($config['default_widget'])) {
$widget = $config['default_widget'];
$metadata = $this->metadata();
$found = false;
if (isset($metadata['admin']['form_groups'][$widget]['group'])) {
$group = $metadata['admin']['form_groups'][$widget]['group'];
$found = true;
}
if (!$found && isset($metadata['admin']['forms'])) {
foreach ($metadata['admin']['forms'] as $form) {
if (isset($form['groups'][$widget]['group'])) {
$group = $form['groups'][$widget]['group'];
$found = true;
break;
}
}
}
if (!$found && isset($metadata['admin']['dashboards'])) {
foreach ($metadata['admin']['dashboards'] as $dashboard) {
if (isset($dashboard['widgets'][$widget]['group'])) {
$group = $dashboard['widgets'][$widget]['group'];
$found = true;
break;
}
}
}
}
if (!is_string($group)) {
throw new UnexpectedValueException('The attachment grouping must be a string.');
}
$this->group = $group;
}
return $this->group;
} | [
"public",
"function",
"attachmentGroup",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"group",
"===",
"null",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"attachmentsMetadata",
"(",
")",
";",
"$",
"group",
"=",
"AttachmentContainerInterface",
"::",
... | Retrieve the widget's attachment grouping.
@throws UnexpectedValueException If the grouping is invalid.
@return string | [
"Retrieve",
"the",
"widget",
"s",
"attachment",
"grouping",
"."
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php#L76-L126 | train |
locomotivemtl/charcoal-attachment | src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php | AttachmentContainerTrait.attachableObjects | public function attachableObjects()
{
if ($this->attachableObjects === null) {
$this->attachableObjects = [];
$config = $this->attachmentsMetadata();
if (isset($config['attachable_objects'])) {
foreach ($config['attachable_objects'] as $attType => $attMeta) {
// Disable an attachable model
if (isset($attMeta['active']) && !$attMeta['active']) {
continue;
}
// Useful for replacing a pre-defined attachment type
if (isset($attMeta['attachment_type'])) {
$attType = $attMeta['attachment_type'];
} else {
$attMeta['attachment_type'] = $attType;
}
// Alias
$attMeta['attachmentType'] = $attMeta['attachment_type'];
if (isset($attMeta['label'])) {
$attMeta['label'] = $this->translator()->translation($attMeta['label']);
} else {
$attMeta['label'] = ucfirst(basename($attType));
}
$faIcon = '';
if (isset($attMeta['fa_icon']) && !empty($attMeta['fa_icon'])) {
$faIcon = 'fa fa-'.$attMeta['fa_icon'];
} elseif ($this->attachmentWidget()) {
$attParts = explode('/', $attType);
$defaultIcons = $this->attachmentWidget()->defaultIcons();
if (isset($defaultIcons[end($attParts)])) {
$faIcon = 'fa fa-'.$defaultIcons[end($attParts)];
}
}
$attMeta['faIcon'] = $faIcon;
$attMeta['hasFaIcon'] = !!$faIcon;
// Custom forms
if (isset($attMeta['form_ident'])) {
$attMeta['formIdent'] = $attMeta['form_ident'];
} else {
$attMeta['formIdent'] = null;
}
if (isset($attMeta['quick_form_ident'])) {
$attMeta['quickFormIdent'] = $attMeta['quick_form_ident'];
} else {
$attMeta['quickFormIdent'] = null;
}
$this->attachableObjects[$attType] = $attMeta;
}
}
}
return $this->attachableObjects;
} | php | public function attachableObjects()
{
if ($this->attachableObjects === null) {
$this->attachableObjects = [];
$config = $this->attachmentsMetadata();
if (isset($config['attachable_objects'])) {
foreach ($config['attachable_objects'] as $attType => $attMeta) {
// Disable an attachable model
if (isset($attMeta['active']) && !$attMeta['active']) {
continue;
}
// Useful for replacing a pre-defined attachment type
if (isset($attMeta['attachment_type'])) {
$attType = $attMeta['attachment_type'];
} else {
$attMeta['attachment_type'] = $attType;
}
// Alias
$attMeta['attachmentType'] = $attMeta['attachment_type'];
if (isset($attMeta['label'])) {
$attMeta['label'] = $this->translator()->translation($attMeta['label']);
} else {
$attMeta['label'] = ucfirst(basename($attType));
}
$faIcon = '';
if (isset($attMeta['fa_icon']) && !empty($attMeta['fa_icon'])) {
$faIcon = 'fa fa-'.$attMeta['fa_icon'];
} elseif ($this->attachmentWidget()) {
$attParts = explode('/', $attType);
$defaultIcons = $this->attachmentWidget()->defaultIcons();
if (isset($defaultIcons[end($attParts)])) {
$faIcon = 'fa fa-'.$defaultIcons[end($attParts)];
}
}
$attMeta['faIcon'] = $faIcon;
$attMeta['hasFaIcon'] = !!$faIcon;
// Custom forms
if (isset($attMeta['form_ident'])) {
$attMeta['formIdent'] = $attMeta['form_ident'];
} else {
$attMeta['formIdent'] = null;
}
if (isset($attMeta['quick_form_ident'])) {
$attMeta['quickFormIdent'] = $attMeta['quick_form_ident'];
} else {
$attMeta['quickFormIdent'] = null;
}
$this->attachableObjects[$attType] = $attMeta;
}
}
}
return $this->attachableObjects;
} | [
"public",
"function",
"attachableObjects",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"attachableObjects",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"attachableObjects",
"=",
"[",
"]",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"attachmentsMetadata",
... | Returns attachable objects
@return array Attachable Objects | [
"Returns",
"attachable",
"objects"
] | 82963e414483e7a0fc75e30894db0bba376dbd2d | https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Attachment/Traits/AttachmentContainerTrait.php#L143-L205 | train |
mirko-pagliai/me-cms | src/Utility/Sitemap.php | Sitemap.pages | public static function pages()
{
if (!getConfig('sitemap.pages')) {
return [];
}
$table = TableRegistry::get('MeCms.PagesCategories');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Pages->getAlias();
$categories = $table->find('active')
->select(['id', 'lft', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['category_id', 'slug', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
})
->order(['lft' => 'ASC']);
if ($categories->isEmpty()) {
return [];
}
//Adds categories index
$url[] = self::parse(['_name' => 'pagesCategories']);
foreach ($categories as $category) {
//Adds the category
$url[] = self::parse(
['_name' => 'pagesCategory', $category->slug],
['lastmod' => array_value_first($category->pages)->modified]
);
//Adds each page
foreach ($category->pages as $page) {
$url[] = self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | php | public static function pages()
{
if (!getConfig('sitemap.pages')) {
return [];
}
$table = TableRegistry::get('MeCms.PagesCategories');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Pages->getAlias();
$categories = $table->find('active')
->select(['id', 'lft', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['category_id', 'slug', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
})
->order(['lft' => 'ASC']);
if ($categories->isEmpty()) {
return [];
}
//Adds categories index
$url[] = self::parse(['_name' => 'pagesCategories']);
foreach ($categories as $category) {
//Adds the category
$url[] = self::parse(
['_name' => 'pagesCategory', $category->slug],
['lastmod' => array_value_first($category->pages)->modified]
);
//Adds each page
foreach ($category->pages as $page) {
$url[] = self::parse(['_name' => 'page', $page->slug], ['lastmod' => $page->modified]);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | [
"public",
"static",
"function",
"pages",
"(",
")",
"{",
"if",
"(",
"!",
"getConfig",
"(",
"'sitemap.pages'",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"table",
"=",
"TableRegistry",
"::",
"get",
"(",
"'MeCms.PagesCategories'",
")",
";",
"$",
"u... | Returns pages urls
@return array
@uses MeCms\Utility\SitemapBuilder::parse() | [
"Returns",
"pages",
"urls"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Sitemap.php#L37-L82 | train |
mirko-pagliai/me-cms | src/Utility/Sitemap.php | Sitemap.photos | public static function photos()
{
if (!getConfig('sitemap.photos')) {
return [];
}
$table = TableRegistry::get('MeCms.PhotosAlbums');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Photos->getAlias();
$albums = $table->find('active')
->select(['id', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['id', 'album_id', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
});
if ($albums->isEmpty()) {
return [];
}
$latest = $table->Photos->find('active')
->select(['modified'])
->order([sprintf('%s.modified', $alias) => 'DESC'])
->firstOrFail();
//Adds albums index
$url[] = self::parse(['_name' => 'albums'], ['lastmod' => $latest->modified]);
foreach ($albums as $album) {
//Adds the album
$url[] = self::parse(['_name' => 'album', $album->slug], ['lastmod' => array_value_first($album->photos)->modified]);
//Adds each photo
foreach ($album->photos as $photo) {
$url[] = self::parse(
['_name' => 'photo', 'slug' => $album->slug, 'id' => $photo->id],
['lastmod' => $photo->modified]
);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | php | public static function photos()
{
if (!getConfig('sitemap.photos')) {
return [];
}
$table = TableRegistry::get('MeCms.PhotosAlbums');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Photos->getAlias();
$albums = $table->find('active')
->select(['id', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['id', 'album_id', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
});
if ($albums->isEmpty()) {
return [];
}
$latest = $table->Photos->find('active')
->select(['modified'])
->order([sprintf('%s.modified', $alias) => 'DESC'])
->firstOrFail();
//Adds albums index
$url[] = self::parse(['_name' => 'albums'], ['lastmod' => $latest->modified]);
foreach ($albums as $album) {
//Adds the album
$url[] = self::parse(['_name' => 'album', $album->slug], ['lastmod' => array_value_first($album->photos)->modified]);
//Adds each photo
foreach ($album->photos as $photo) {
$url[] = self::parse(
['_name' => 'photo', 'slug' => $album->slug, 'id' => $photo->id],
['lastmod' => $photo->modified]
);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | [
"public",
"static",
"function",
"photos",
"(",
")",
"{",
"if",
"(",
"!",
"getConfig",
"(",
"'sitemap.photos'",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"table",
"=",
"TableRegistry",
"::",
"get",
"(",
"'MeCms.PhotosAlbums'",
")",
";",
"$",
"ur... | Returns photos urls
@return array
@uses MeCms\Utility\SitemapBuilder::parse() | [
"Returns",
"photos",
"urls"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Sitemap.php#L89-L138 | train |
mirko-pagliai/me-cms | src/Utility/Sitemap.php | Sitemap.posts | public static function posts()
{
if (!getConfig('sitemap.posts')) {
return [];
}
$table = TableRegistry::get('MeCms.PostsCategories');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Posts->getAlias();
$categories = $table->find('active')
->select(['id', 'lft', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['category_id', 'slug', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
})
->order(['lft' => 'ASC']);
if ($categories->isEmpty()) {
return [];
}
$latest = $table->Posts->find('active')
->select(['modified'])
->order([sprintf('%s.modified', $alias) => 'DESC'])
->firstOrFail();
//Adds posts index, categories index and posts search
$url[] = self::parse(['_name' => 'posts'], ['lastmod' => $latest->modified]);
$url[] = self::parse(['_name' => 'postsCategories']);
$url[] = self::parse(['_name' => 'postsSearch'], ['priority' => '0.2']);
foreach ($categories as $category) {
//Adds the category
$url[] = self::parse(
['_name' => 'postsCategory', $category->slug],
['lastmod' => array_value_first($category->posts)->modified]
);
//Adds each post
foreach ($category->posts as $post) {
$url[] = self::parse(['_name' => 'post', $post->slug], ['lastmod' => $post->modified]);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | php | public static function posts()
{
if (!getConfig('sitemap.posts')) {
return [];
}
$table = TableRegistry::get('MeCms.PostsCategories');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$alias = $table->Posts->getAlias();
$categories = $table->find('active')
->select(['id', 'lft', 'slug'])
->contain($alias, function (Query $q) use ($alias) {
return $q->find('active')
->select(['category_id', 'slug', 'modified'])
->order([sprintf('%s.modified', $alias) => 'DESC']);
})
->order(['lft' => 'ASC']);
if ($categories->isEmpty()) {
return [];
}
$latest = $table->Posts->find('active')
->select(['modified'])
->order([sprintf('%s.modified', $alias) => 'DESC'])
->firstOrFail();
//Adds posts index, categories index and posts search
$url[] = self::parse(['_name' => 'posts'], ['lastmod' => $latest->modified]);
$url[] = self::parse(['_name' => 'postsCategories']);
$url[] = self::parse(['_name' => 'postsSearch'], ['priority' => '0.2']);
foreach ($categories as $category) {
//Adds the category
$url[] = self::parse(
['_name' => 'postsCategory', $category->slug],
['lastmod' => array_value_first($category->posts)->modified]
);
//Adds each post
foreach ($category->posts as $post) {
$url[] = self::parse(['_name' => 'post', $post->slug], ['lastmod' => $post->modified]);
}
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | [
"public",
"static",
"function",
"posts",
"(",
")",
"{",
"if",
"(",
"!",
"getConfig",
"(",
"'sitemap.posts'",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"table",
"=",
"TableRegistry",
"::",
"get",
"(",
"'MeCms.PostsCategories'",
")",
";",
"$",
"u... | Returns posts urls
@return array
@uses MeCms\Utility\SitemapBuilder::parse() | [
"Returns",
"posts",
"urls"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Sitemap.php#L145-L196 | train |
mirko-pagliai/me-cms | src/Utility/Sitemap.php | Sitemap.postsTags | public static function postsTags()
{
if (!getConfig('sitemap.posts_tags')) {
return [];
}
$table = TableRegistry::get('MeCms.Tags');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$tags = $table->find('active')
->select(['tag', 'modified'])
->order(['tag' => 'ASC']);
if ($tags->isEmpty()) {
return [];
}
$latest = $table->find()
->select(['modified'])
->order(['modified' => 'DESC'])
->firstOrFail();
//Adds the tags index
$url[] = self::parse(['_name' => 'postsTags'], ['lastmod' => $latest->modified]);
//Adds each tag
foreach ($tags as $tag) {
$url[] = self::parse(['_name' => 'postsTag', $tag->slug], ['lastmod' => $tag->modified]);
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | php | public static function postsTags()
{
if (!getConfig('sitemap.posts_tags')) {
return [];
}
$table = TableRegistry::get('MeCms.Tags');
$url = Cache::read('sitemap', $table->getCacheName());
if (!$url) {
$tags = $table->find('active')
->select(['tag', 'modified'])
->order(['tag' => 'ASC']);
if ($tags->isEmpty()) {
return [];
}
$latest = $table->find()
->select(['modified'])
->order(['modified' => 'DESC'])
->firstOrFail();
//Adds the tags index
$url[] = self::parse(['_name' => 'postsTags'], ['lastmod' => $latest->modified]);
//Adds each tag
foreach ($tags as $tag) {
$url[] = self::parse(['_name' => 'postsTag', $tag->slug], ['lastmod' => $tag->modified]);
}
Cache::write('sitemap', $url, $table->getCacheName());
}
return $url;
} | [
"public",
"static",
"function",
"postsTags",
"(",
")",
"{",
"if",
"(",
"!",
"getConfig",
"(",
"'sitemap.posts_tags'",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"table",
"=",
"TableRegistry",
"::",
"get",
"(",
"'MeCms.Tags'",
")",
";",
"$",
"url... | Returns posts tags urls
@return array
@uses MeCms\Utility\SitemapBuilder::parse() | [
"Returns",
"posts",
"tags",
"urls"
] | df668ad8e3ee221497c47578d474e487f24ce92a | https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Sitemap.php#L203-L238 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.