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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
thelia/core | lib/Thelia/Controller/Admin/SessionController.php | SessionController.applyUserLocale | protected function applyUserLocale(UserInterface $user)
{
// Set the current language according to locale preference
$locale = $user->getLocale();
if (null === $lang = LangQuery::create()->findOneByLocale($locale)) {
$lang = Lang::getDefaultLanguage();
}
$this->getSession()->setLang($lang);
} | php | protected function applyUserLocale(UserInterface $user)
{
// Set the current language according to locale preference
$locale = $user->getLocale();
if (null === $lang = LangQuery::create()->findOneByLocale($locale)) {
$lang = Lang::getDefaultLanguage();
}
$this->getSession()->setLang($lang);
} | [
"protected",
"function",
"applyUserLocale",
"(",
"UserInterface",
"$",
"user",
")",
"{",
"// Set the current language according to locale preference",
"$",
"locale",
"=",
"$",
"user",
"->",
"getLocale",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"lang",
"=",
... | Save user locale preference in session.
@param UserInterface $user | [
"Save",
"user",
"locale",
"preference",
"in",
"session",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Controller/Admin/SessionController.php#L296-L306 | train |
thelia/core | lib/Thelia/Config/DatabaseConfigurationSource.php | DatabaseConfigurationSource.addConnection | protected function addConnection($name, array $parameters = [], array $envParameters = [])
{
$connectionParameterBag = new ParameterBag($envParameters);
$connectionParameterBag->add($parameters);
$connectionParameterBag->resolve();
$this->connections[$name] = $connectionParameterBag;
} | php | protected function addConnection($name, array $parameters = [], array $envParameters = [])
{
$connectionParameterBag = new ParameterBag($envParameters);
$connectionParameterBag->add($parameters);
$connectionParameterBag->resolve();
$this->connections[$name] = $connectionParameterBag;
} | [
"protected",
"function",
"addConnection",
"(",
"$",
"name",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
",",
"array",
"$",
"envParameters",
"=",
"[",
"]",
")",
"{",
"$",
"connectionParameterBag",
"=",
"new",
"ParameterBag",
"(",
"$",
"envParameters",
"... | Create and resolve a ParameterBag for a connection.
Add the bag to the connections map.
@param string $name Connection name.
@param array $parameters Connection parameters.
@param array $envParameters Environment parameters. | [
"Create",
"and",
"resolve",
"a",
"ParameterBag",
"for",
"a",
"connection",
".",
"Add",
"the",
"bag",
"to",
"the",
"connections",
"map",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Config/DatabaseConfigurationSource.php#L82-L88 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior.setupFieldAssociations | public function setupFieldAssociations($fields, $table, $fieldConditions, $strategy)
{
$config = $this->getConfig();
$this->_table->hasMany($config['translationTable'], [
'className' => $config['translationTable'],
'foreignKey' => 'id',
'strategy' => $strategy,
'propertyName' => '_i18n',
'dependent' => true,
]);
} | php | public function setupFieldAssociations($fields, $table, $fieldConditions, $strategy)
{
$config = $this->getConfig();
$this->_table->hasMany($config['translationTable'], [
'className' => $config['translationTable'],
'foreignKey' => 'id',
'strategy' => $strategy,
'propertyName' => '_i18n',
'dependent' => true,
]);
} | [
"public",
"function",
"setupFieldAssociations",
"(",
"$",
"fields",
",",
"$",
"table",
",",
"$",
"fieldConditions",
",",
"$",
"strategy",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"$",
"this",
"->",
"_table",
"->",
"h... | Create a hasMany association for all records
Don't create a hasOne association here as the join conditions are modified
in before find - so create/modify it there
@param array $fields - ignored
@param string $table - ignored
@param string $fieldConditions - ignored
@param string $strategy the strategy used in the _i18n association
@return void | [
"Create",
"a",
"hasMany",
"association",
"for",
"all",
"records"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L103-L114 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior._addFieldsToQuery | protected function _addFieldsToQuery(Query $query, array $config)
{
if ($query->isAutoFieldsEnabled()) {
return true;
}
$select = array_filter($query->clause('select'), function ($field) {
return is_string($field);
});
if (!$select) {
return true;
}
$alias = $config['mainTableAlias'];
$joinRequired = false;
foreach ($this->_translationFields() as $field) {
if (array_intersect($select, [$field, "$alias.$field"])) {
$joinRequired = true;
$query->select($query->aliasField($field, $config['hasOneAlias']));
}
}
if ($joinRequired) {
$query->select($query->aliasField('locale', $config['hasOneAlias']));
}
return $joinRequired;
} | php | protected function _addFieldsToQuery(Query $query, array $config)
{
if ($query->isAutoFieldsEnabled()) {
return true;
}
$select = array_filter($query->clause('select'), function ($field) {
return is_string($field);
});
if (!$select) {
return true;
}
$alias = $config['mainTableAlias'];
$joinRequired = false;
foreach ($this->_translationFields() as $field) {
if (array_intersect($select, [$field, "$alias.$field"])) {
$joinRequired = true;
$query->select($query->aliasField($field, $config['hasOneAlias']));
}
}
if ($joinRequired) {
$query->select($query->aliasField('locale', $config['hasOneAlias']));
}
return $joinRequired;
} | [
"protected",
"function",
"_addFieldsToQuery",
"(",
"Query",
"$",
"query",
",",
"array",
"$",
"config",
")",
"{",
"if",
"(",
"$",
"query",
"->",
"isAutoFieldsEnabled",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"select",
"=",
"array_filter",
"("... | Add translation fields to query
If the query is using autofields (directly or implicitly) add the
main table's fields to the query first.
Only add translations for fields that are in the main table, always
add the locale field though.
@param \Cake\ORM\Query $query the query to check
@param array $config the config to use for adding fields
@return bool Whether a join to the translation table is required | [
"Add",
"translation",
"fields",
"to",
"query"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L180-L208 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior._iterateClause | protected function _iterateClause(Query $query, $name = '', $config = [])
{
$clause = $query->clause($name);
if (!$clause || !$clause->count()) {
return false;
}
$alias = $config['hasOneAlias'];
$fields = $this->_translationFields();
$mainTableAlias = $config['mainTableAlias'];
$mainTableFields = $this->_mainFields();
$joinRequired = false;
$clause->iterateParts(function ($c, &$field) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) {
if (!is_string($field) || strpos($field, '.')) {
return $c;
}
if (in_array($field, $fields)) {
$joinRequired = true;
$field = "$alias.$field";
} elseif (in_array($field, $mainTableFields)) {
$field = "$mainTableAlias.$field";
}
return $c;
});
return $joinRequired;
} | php | protected function _iterateClause(Query $query, $name = '', $config = [])
{
$clause = $query->clause($name);
if (!$clause || !$clause->count()) {
return false;
}
$alias = $config['hasOneAlias'];
$fields = $this->_translationFields();
$mainTableAlias = $config['mainTableAlias'];
$mainTableFields = $this->_mainFields();
$joinRequired = false;
$clause->iterateParts(function ($c, &$field) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) {
if (!is_string($field) || strpos($field, '.')) {
return $c;
}
if (in_array($field, $fields)) {
$joinRequired = true;
$field = "$alias.$field";
} elseif (in_array($field, $mainTableFields)) {
$field = "$mainTableAlias.$field";
}
return $c;
});
return $joinRequired;
} | [
"protected",
"function",
"_iterateClause",
"(",
"Query",
"$",
"query",
",",
"$",
"name",
"=",
"''",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"clause",
"=",
"$",
"query",
"->",
"clause",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
... | Iterate over a clause to alias fields
The objective here is to transparently prevent ambiguous field errors by
prefixing fields with the appropriate table alias. This method currently
expects to receive an order clause only.
@param \Cake\ORM\Query $query the query to check
@param string $name The clause name
@param array $config the config to use for adding fields
@return bool Whether a join to the translation table is required | [
"Iterate",
"over",
"a",
"clause",
"to",
"alias",
"fields"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L222-L251 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior._traverseClause | protected function _traverseClause(Query $query, $name = '', $config = [])
{
$clause = $query->clause($name);
if (!$clause || !$clause->count()) {
return false;
}
$alias = $config['hasOneAlias'];
$fields = $this->_translationFields();
$mainTableAlias = $config['mainTableAlias'];
$mainTableFields = $this->_mainFields();
$joinRequired = false;
$clause->traverse(function ($expression) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) {
if (!($expression instanceof FieldInterface)) {
return;
}
$field = $expression->getField();
if (!is_string($field) || strpos($field, '.')) {
return;
}
if (in_array($field, $fields)) {
$joinRequired = true;
$expression->setField("$alias.$field");
return;
}
if (in_array($field, $mainTableFields)) {
$expression->setField("$mainTableAlias.$field");
}
});
return $joinRequired;
} | php | protected function _traverseClause(Query $query, $name = '', $config = [])
{
$clause = $query->clause($name);
if (!$clause || !$clause->count()) {
return false;
}
$alias = $config['hasOneAlias'];
$fields = $this->_translationFields();
$mainTableAlias = $config['mainTableAlias'];
$mainTableFields = $this->_mainFields();
$joinRequired = false;
$clause->traverse(function ($expression) use ($fields, $alias, $mainTableAlias, $mainTableFields, &$joinRequired) {
if (!($expression instanceof FieldInterface)) {
return;
}
$field = $expression->getField();
if (!is_string($field) || strpos($field, '.')) {
return;
}
if (in_array($field, $fields)) {
$joinRequired = true;
$expression->setField("$alias.$field");
return;
}
if (in_array($field, $mainTableFields)) {
$expression->setField("$mainTableAlias.$field");
}
});
return $joinRequired;
} | [
"protected",
"function",
"_traverseClause",
"(",
"Query",
"$",
"query",
",",
"$",
"name",
"=",
"''",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"clause",
"=",
"$",
"query",
"->",
"clause",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
... | Traverse over a clause to alias fields
The objective here is to transparently prevent ambiguous field errors by
prefixing fields with the appropriate table alias. This method currently
expects to receive a where clause only.
@param \Cake\ORM\Query $query the query to check
@param string $name The clause name
@param array $config the config to use for adding fields
@return bool Whether a join to the translation table is required | [
"Traverse",
"over",
"a",
"clause",
"to",
"alias",
"fields"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L265-L300 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior._mainFields | protected function _mainFields()
{
$fields = $this->getConfig('mainTableFields');
if ($fields) {
return $fields;
}
$table = $this->_table;
$fields = $table->getSchema()->columns();
$this->setConfig('mainTableFields', $fields);
return $fields;
} | php | protected function _mainFields()
{
$fields = $this->getConfig('mainTableFields');
if ($fields) {
return $fields;
}
$table = $this->_table;
$fields = $table->getSchema()->columns();
$this->setConfig('mainTableFields', $fields);
return $fields;
} | [
"protected",
"function",
"_mainFields",
"(",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'mainTableFields'",
")",
";",
"if",
"(",
"$",
"fields",
")",
"{",
"return",
"$",
"fields",
";",
"}",
"$",
"table",
"=",
"$",
"this",
"->"... | Lazy define and return the main table fields
@return array | [
"Lazy",
"define",
"and",
"return",
"the",
"main",
"table",
"fields"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L572-L586 | train |
AD7six/cakephp-shadow-translate | src/Model/Behavior/ShadowTranslateBehavior.php | ShadowTranslateBehavior._translationFields | protected function _translationFields()
{
$fields = $this->getConfig('fields');
if ($fields) {
return $fields;
}
$table = $this->_translationTable();
$fields = $table->getSchema()->columns();
$fields = array_values(array_diff($fields, ['id', 'locale']));
$this->setConfig('fields', $fields);
return $fields;
} | php | protected function _translationFields()
{
$fields = $this->getConfig('fields');
if ($fields) {
return $fields;
}
$table = $this->_translationTable();
$fields = $table->getSchema()->columns();
$fields = array_values(array_diff($fields, ['id', 'locale']));
$this->setConfig('fields', $fields);
return $fields;
} | [
"protected",
"function",
"_translationFields",
"(",
")",
"{",
"$",
"fields",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'fields'",
")",
";",
"if",
"(",
"$",
"fields",
")",
"{",
"return",
"$",
"fields",
";",
"}",
"$",
"table",
"=",
"$",
"this",
"->",
... | Lazy define and return the translation table fields
@return array | [
"Lazy",
"define",
"and",
"return",
"the",
"translation",
"table",
"fields"
] | 3e20e232911d0eddfe4adb47ddd24c6bf7b3f879 | https://github.com/AD7six/cakephp-shadow-translate/blob/3e20e232911d0eddfe4adb47ddd24c6bf7b3f879/src/Model/Behavior/ShadowTranslateBehavior.php#L593-L608 | train |
thelia/core | lib/Thelia/Model/Tools/ModelCriteriaTools.php | ModelCriteriaTools.getI18n | public static function getI18n(
$backendContext,
$requestedLangId,
ModelCriteria &$search,
$currentLocale,
$columns,
$foreignTable,
$foreignKey,
$forceReturn = false,
$localeAlias = null
) {
// If a lang has been requested, find the related Lang object, and get the locale
if ($requestedLangId !== null) {
$localeSearch = LangQuery::create()->findByIdOrLocale($requestedLangId);
if ($localeSearch === null) {
throw new \InvalidArgumentException(
sprintf(
'Incorrect lang argument given : lang %s not found',
$requestedLangId
)
);
}
$locale = $localeSearch->getLocale();
} else {
// Use the currently defined locale
$locale = $currentLocale;
}
// Call the proper method depending on the context: front or back
if ($backendContext) {
self::getBackEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $localeAlias);
} else {
self::getFrontEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $forceReturn, $localeAlias);
}
return $locale;
} | php | public static function getI18n(
$backendContext,
$requestedLangId,
ModelCriteria &$search,
$currentLocale,
$columns,
$foreignTable,
$foreignKey,
$forceReturn = false,
$localeAlias = null
) {
// If a lang has been requested, find the related Lang object, and get the locale
if ($requestedLangId !== null) {
$localeSearch = LangQuery::create()->findByIdOrLocale($requestedLangId);
if ($localeSearch === null) {
throw new \InvalidArgumentException(
sprintf(
'Incorrect lang argument given : lang %s not found',
$requestedLangId
)
);
}
$locale = $localeSearch->getLocale();
} else {
// Use the currently defined locale
$locale = $currentLocale;
}
// Call the proper method depending on the context: front or back
if ($backendContext) {
self::getBackEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $localeAlias);
} else {
self::getFrontEndI18n($search, $locale, $columns, $foreignTable, $foreignKey, $forceReturn, $localeAlias);
}
return $locale;
} | [
"public",
"static",
"function",
"getI18n",
"(",
"$",
"backendContext",
",",
"$",
"requestedLangId",
",",
"ModelCriteria",
"&",
"$",
"search",
",",
"$",
"currentLocale",
",",
"$",
"columns",
",",
"$",
"foreignTable",
",",
"$",
"foreignKey",
",",
"$",
"forceRe... | Bild query to retrieve I18n
@param bool $backendContext
@param int $requestedLangId
@param ModelCriteria $search
@param string $currentLocale
@param array $columns
@param string $foreignTable
@param string $foreignKey
@param bool $forceReturn
@param string|null $localeAlias le local table if different of the main query table
@return string | [
"Bild",
"query",
"to",
"retrieve",
"I18n"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Tools/ModelCriteriaTools.php#L254-L292 | train |
GrahamCampbell/Analyzer | src/AnalysisTrait.php | AnalysisTrait.provideFilesToCheck | public function provideFilesToCheck()
{
$iterator = new AppendIterator();
foreach ($this->getPaths() as $path) {
$iterator->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}
$files = new CallbackFilterIterator($iterator, function ($file) {
return $file->getFilename()[0] !== '.' && !$file->isDir();
});
return array_map(function ($file) {
return [(string) $file];
}, iterator_to_array($files));
} | php | public function provideFilesToCheck()
{
$iterator = new AppendIterator();
foreach ($this->getPaths() as $path) {
$iterator->append(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}
$files = new CallbackFilterIterator($iterator, function ($file) {
return $file->getFilename()[0] !== '.' && !$file->isDir();
});
return array_map(function ($file) {
return [(string) $file];
}, iterator_to_array($files));
} | [
"public",
"function",
"provideFilesToCheck",
"(",
")",
"{",
"$",
"iterator",
"=",
"new",
"AppendIterator",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getPaths",
"(",
")",
"as",
"$",
"path",
")",
"{",
"$",
"iterator",
"->",
"append",
"(",
"new",... | Get the files to check.
@return string[][] | [
"Get",
"the",
"files",
"to",
"check",
"."
] | e918797f052c001362bda65e7364026910608bef | https://github.com/GrahamCampbell/Analyzer/blob/e918797f052c001362bda65e7364026910608bef/src/AnalysisTrait.php#L60-L75 | train |
BoldGrid/library | src/Library/Page/Connect.php | Connect.isConnectScreen | public function isConnectScreen( $screen ) {
$base = ! empty( $screen->base ) ? $screen->base : null;
return 'settings_page_boldgrid-connect' === $base;
} | php | public function isConnectScreen( $screen ) {
$base = ! empty( $screen->base ) ? $screen->base : null;
return 'settings_page_boldgrid-connect' === $base;
} | [
"public",
"function",
"isConnectScreen",
"(",
"$",
"screen",
")",
"{",
"$",
"base",
"=",
"!",
"empty",
"(",
"$",
"screen",
"->",
"base",
")",
"?",
"$",
"screen",
"->",
"base",
":",
"null",
";",
"return",
"'settings_page_boldgrid-connect'",
"===",
"$",
"b... | Check if the current screen is the connect screen.
@since 2.4.0
@param object $screen Current Screen.
@return boolean Is the screen the connect screen? | [
"Check",
"if",
"the",
"current",
"screen",
"is",
"the",
"connect",
"screen",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Page/Connect.php#L84-L87 | train |
BoldGrid/library | src/Library/Page/Connect.php | Connect.addScripts | public function addScripts() {
if ( $this->isConnectScreen( get_current_screen() ) ) {
// Enqueue bglib-connect js.
$handle = 'bglib-connect';
wp_register_script(
$handle,
Configs::get( 'libraryUrl' ) . 'src/assets/js/connect.js' ,
array( 'jquery' ),
date( 'Ymd' ),
false
);
$translation = array(
'settingsSaved' => __( 'Settings saved.', 'boldgrid-library' ),
'unknownError' => __( 'Unknown error.', 'boldgrid-library' ),
'ajaxError' => __( 'Could not reach the AJAX URL address. HTTP error: ', 'boldgrid-library' ),
);
wp_localize_script( $handle, 'BoldGridLibraryConnect', $translation );
wp_enqueue_script( $handle );
// Enqueue jquery-toggles js.
wp_enqueue_script(
'jquery-toggles',
Configs::get( 'libraryUrl' ) . 'build/toggles.min.js',
array( 'jquery' ),
date( 'Ymd' ),
true
);
// Enqueue jquery-toggles css.
wp_enqueue_style( 'jquery-toggles-full',
Configs::get( 'libraryUrl' ) . 'build/toggles-full.css', array(), date( 'Ymd' ) );
/**
* Add additional scripts to Connect page.
*
* @since 2.4.0
*/
do_action( 'Boldgrid\Library\Library\Page\Connect\addScripts' );
}
} | php | public function addScripts() {
if ( $this->isConnectScreen( get_current_screen() ) ) {
// Enqueue bglib-connect js.
$handle = 'bglib-connect';
wp_register_script(
$handle,
Configs::get( 'libraryUrl' ) . 'src/assets/js/connect.js' ,
array( 'jquery' ),
date( 'Ymd' ),
false
);
$translation = array(
'settingsSaved' => __( 'Settings saved.', 'boldgrid-library' ),
'unknownError' => __( 'Unknown error.', 'boldgrid-library' ),
'ajaxError' => __( 'Could not reach the AJAX URL address. HTTP error: ', 'boldgrid-library' ),
);
wp_localize_script( $handle, 'BoldGridLibraryConnect', $translation );
wp_enqueue_script( $handle );
// Enqueue jquery-toggles js.
wp_enqueue_script(
'jquery-toggles',
Configs::get( 'libraryUrl' ) . 'build/toggles.min.js',
array( 'jquery' ),
date( 'Ymd' ),
true
);
// Enqueue jquery-toggles css.
wp_enqueue_style( 'jquery-toggles-full',
Configs::get( 'libraryUrl' ) . 'build/toggles-full.css', array(), date( 'Ymd' ) );
/**
* Add additional scripts to Connect page.
*
* @since 2.4.0
*/
do_action( 'Boldgrid\Library\Library\Page\Connect\addScripts' );
}
} | [
"public",
"function",
"addScripts",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isConnectScreen",
"(",
"get_current_screen",
"(",
")",
")",
")",
"{",
"// Enqueue bglib-connect js.",
"$",
"handle",
"=",
"'bglib-connect'",
";",
"wp_register_script",
"(",
"$",
... | Enqueue scripts needed for this page.
@since 2.4.0
@hook admin_enqueue_scripts | [
"Enqueue",
"scripts",
"needed",
"for",
"this",
"page",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Page/Connect.php#L107-L150 | train |
BoldGrid/library | src/Library/Page/Connect.php | Connect.saveSettings | public function saveSettings() {
// Check user permissions.
if ( ! current_user_can( 'update_plugins' ) ) {
wp_send_json_error( array(
'error' => __( 'User access violation!', 'boldgrid-library' ),
) );
}
// Check security nonce and referer.
if ( ! check_admin_referer( 'boldgrid_library_connect_settings_save' ) ) {
wp_send_json_error( array(
'error' => __( 'Security violation! Please try again.', 'boldgrid-library' ),
) );
}
// Read settings form POST request, sanitize, and merge settings with saved.
$boldgridSettings = array_merge(
get_option( 'boldgrid_settings' ),
self::sanitizeSettings(
array(
'autoupdate' => ! empty( $_POST['autoupdate'] ) ?
(array) $_POST['autoupdate'] : array(),
'release_channel' => ! empty( $_POST['plugin_release_channel'] ) ?
sanitize_key( $_POST['plugin_release_channel'] ) : 'stable',
'theme_release_channel' => ! empty( $_POST['theme_release_channel'] ) ?
sanitize_key( $_POST['theme_release_channel'] ) : 'stable',
)
)
);
// If new auto-update settings were passed, then remove deprecated settings.
if ( ! empty( $_POST['autoupdate'] ) ) {
unset( $boldgridSettings['plugin_autoupdate'], $boldgridSettings['theme_autoupdate'] );
}
update_option( 'boldgrid_settings', $boldgridSettings );
wp_send_json_success();
} | php | public function saveSettings() {
// Check user permissions.
if ( ! current_user_can( 'update_plugins' ) ) {
wp_send_json_error( array(
'error' => __( 'User access violation!', 'boldgrid-library' ),
) );
}
// Check security nonce and referer.
if ( ! check_admin_referer( 'boldgrid_library_connect_settings_save' ) ) {
wp_send_json_error( array(
'error' => __( 'Security violation! Please try again.', 'boldgrid-library' ),
) );
}
// Read settings form POST request, sanitize, and merge settings with saved.
$boldgridSettings = array_merge(
get_option( 'boldgrid_settings' ),
self::sanitizeSettings(
array(
'autoupdate' => ! empty( $_POST['autoupdate'] ) ?
(array) $_POST['autoupdate'] : array(),
'release_channel' => ! empty( $_POST['plugin_release_channel'] ) ?
sanitize_key( $_POST['plugin_release_channel'] ) : 'stable',
'theme_release_channel' => ! empty( $_POST['theme_release_channel'] ) ?
sanitize_key( $_POST['theme_release_channel'] ) : 'stable',
)
)
);
// If new auto-update settings were passed, then remove deprecated settings.
if ( ! empty( $_POST['autoupdate'] ) ) {
unset( $boldgridSettings['plugin_autoupdate'], $boldgridSettings['theme_autoupdate'] );
}
update_option( 'boldgrid_settings', $boldgridSettings );
wp_send_json_success();
} | [
"public",
"function",
"saveSettings",
"(",
")",
"{",
"// Check user permissions.",
"if",
"(",
"!",
"current_user_can",
"(",
"'update_plugins'",
")",
")",
"{",
"wp_send_json_error",
"(",
"array",
"(",
"'error'",
"=>",
"__",
"(",
"'User access violation!'",
",",
"'b... | AJAX callback for the Connect Settings page.
@since 2.7.0
@uses $_POST['autoupdate'] Optional auto-update settings for plugins and themes.
@uses $_POST['plugin_release_channel'] Plugin release channel.
@uses $_POST['theme_release_channel'] Theme release channel.
@see self::sanitizeSettings()
@hook wp_ajax_boldgrid_library_connect_settings_save | [
"AJAX",
"callback",
"for",
"the",
"Connect",
"Settings",
"page",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Page/Connect.php#L185-L223 | train |
BoldGrid/library | src/Library/Page/Connect.php | Connect.sanitizeSettings | public static function sanitizeSettings( array $settings ) {
$result = array();
if ( ! empty( $settings['autoupdate'] ) && is_array( $settings['autoupdate'] ) ) {
foreach ( $settings['autoupdate'] as $category => $itemSetting ) {
$category = sanitize_key( $category );
foreach ( $itemSetting as $id => $val ) {
$id = sanitize_text_field( $id );
$result['autoupdate'][ $category ][ $id ] = (bool) $val;
}
}
}
// Validate release channel settings.
$channels = array(
'stable',
'edge',
'candidate',
);
if ( empty( $settings['release_channel'] ) ||
! in_array( $settings['release_channel'], $channels, true ) ) {
$result['release_channel'] = 'stable';
} else {
$result['release_channel'] = $settings['release_channel'];
}
if ( empty( $settings['theme_release_channel'] ) ||
! in_array( $settings['theme_release_channel'], $channels, true ) ) {
$result['theme_release_channel'] = 'stable';
} else {
$result['theme_release_channel'] = $settings['theme_release_channel'];
}
return $result;
} | php | public static function sanitizeSettings( array $settings ) {
$result = array();
if ( ! empty( $settings['autoupdate'] ) && is_array( $settings['autoupdate'] ) ) {
foreach ( $settings['autoupdate'] as $category => $itemSetting ) {
$category = sanitize_key( $category );
foreach ( $itemSetting as $id => $val ) {
$id = sanitize_text_field( $id );
$result['autoupdate'][ $category ][ $id ] = (bool) $val;
}
}
}
// Validate release channel settings.
$channels = array(
'stable',
'edge',
'candidate',
);
if ( empty( $settings['release_channel'] ) ||
! in_array( $settings['release_channel'], $channels, true ) ) {
$result['release_channel'] = 'stable';
} else {
$result['release_channel'] = $settings['release_channel'];
}
if ( empty( $settings['theme_release_channel'] ) ||
! in_array( $settings['theme_release_channel'], $channels, true ) ) {
$result['theme_release_channel'] = 'stable';
} else {
$result['theme_release_channel'] = $settings['theme_release_channel'];
}
return $result;
} | [
"public",
"static",
"function",
"sanitizeSettings",
"(",
"array",
"$",
"settings",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"settings",
"[",
"'autoupdate'",
"]",
")",
"&&",
"is_array",
"(",
"$",
"settings... | Sanitize settings.
@since 2.7.0
@static
@param array $settings {
Settings.
@type array $autoupdate {
Optional auto-update settings. This array does not always get included.
@type array $plugins {
Plugin auto-update settings.
@type string $slug Plugin auto-update setting (1=Enabled, 0=Disabled).
}
@type array $themes {
Theme auto-update settings.
@type string $stylesheet Theme auto-update setting (1=Enabled, 0=Disabled).
}
}
@type string $release_channel Plugin release channel.
@type string $theme_release_channel Theme release channel.
}
@return array | [
"Sanitize",
"settings",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Page/Connect.php#L254-L291 | train |
thelia/core | lib/Thelia/Core/Hook/HookHelper.php | HookHelper.trans | protected function trans($context, $key)
{
$message = "";
if (array_key_exists($context, $this->messages)) {
if (array_key_exists($key, $this->messages[$context])) {
$message = $this->messages[$context][$key];
}
}
return $message;
} | php | protected function trans($context, $key)
{
$message = "";
if (array_key_exists($context, $this->messages)) {
if (array_key_exists($key, $this->messages[$context])) {
$message = $this->messages[$context][$key];
}
}
return $message;
} | [
"protected",
"function",
"trans",
"(",
"$",
"context",
",",
"$",
"key",
")",
"{",
"$",
"message",
"=",
"\"\"",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"context",
",",
"$",
"this",
"->",
"messages",
")",
")",
"{",
"if",
"(",
"array_key_exists",
... | Translate Hook labels
@param $context
@param $key
@return string | [
"Translate",
"Hook",
"labels"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Hook/HookHelper.php#L228-L239 | train |
thelia/core | lib/Thelia/Model/CategoryQuery.php | CategoryQuery.getPathToCategory | public static function getPathToCategory($categoryId)
{
$path = [];
$category = (new CategoryQuery)->findPk($categoryId);
if ($category !== null) {
$path[] = $category;
if ($category->getParent() !== 0) {
$path = array_merge(self::getPathToCategory($category->getParent()), $path);
}
}
return $path;
} | php | public static function getPathToCategory($categoryId)
{
$path = [];
$category = (new CategoryQuery)->findPk($categoryId);
if ($category !== null) {
$path[] = $category;
if ($category->getParent() !== 0) {
$path = array_merge(self::getPathToCategory($category->getParent()), $path);
}
}
return $path;
} | [
"public",
"static",
"function",
"getPathToCategory",
"(",
"$",
"categoryId",
")",
"{",
"$",
"path",
"=",
"[",
"]",
";",
"$",
"category",
"=",
"(",
"new",
"CategoryQuery",
")",
"->",
"findPk",
"(",
"$",
"categoryId",
")",
";",
"if",
"(",
"$",
"category"... | Get categories from root to child
@param integer $categoryId Category ID
@since 2.3.0
@return array An array of \Thelia\Model\Category from root to wanted category
or an empty array if Category ID doesn't exists | [
"Get",
"categories",
"from",
"root",
"to",
"child"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/CategoryQuery.php#L108-L122 | train |
thelia/core | lib/Thelia/Core/HttpFoundation/Request.php | Request.getPathInfo | public function getPathInfo()
{
$pathInfo = parent::getPathInfo();
$pathLength = \strlen($pathInfo);
if ($pathInfo !== '/' && $pathInfo[$pathLength - 1] === '/'
&& (bool) ConfigQuery::read('allow_slash_ended_uri', false)
) {
if (null === $this->resolvedPathInfo) {
$this->resolvedPathInfo = substr($pathInfo, 0, $pathLength - 1); // Remove the slash
}
$pathInfo = $this->resolvedPathInfo;
}
return $pathInfo;
} | php | public function getPathInfo()
{
$pathInfo = parent::getPathInfo();
$pathLength = \strlen($pathInfo);
if ($pathInfo !== '/' && $pathInfo[$pathLength - 1] === '/'
&& (bool) ConfigQuery::read('allow_slash_ended_uri', false)
) {
if (null === $this->resolvedPathInfo) {
$this->resolvedPathInfo = substr($pathInfo, 0, $pathLength - 1); // Remove the slash
}
$pathInfo = $this->resolvedPathInfo;
}
return $pathInfo;
} | [
"public",
"function",
"getPathInfo",
"(",
")",
"{",
"$",
"pathInfo",
"=",
"parent",
"::",
"getPathInfo",
"(",
")",
";",
"$",
"pathLength",
"=",
"\\",
"strlen",
"(",
"$",
"pathInfo",
")",
";",
"if",
"(",
"$",
"pathInfo",
"!==",
"'/'",
"&&",
"$",
"path... | Filter PathInfo to allow slash ending uri
example:
/admin will be the same as /admin/ | [
"Filter",
"PathInfo",
"to",
"allow",
"slash",
"ending",
"uri"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/HttpFoundation/Request.php#L60-L76 | train |
BoldGrid/library | src/Library/Registration.php | Registration.preUpgradePlugin | public function preUpgradePlugin( $options ) {
$plugin = ! empty( $options['hook_extra']['plugin'] ) ? $options['hook_extra']['plugin'] : null;
$isBoldgridPlugin = \Boldgrid\Library\Library\Util\Plugin::isBoldgridPlugin( $plugin );
if( $isBoldgridPlugin ) {
/*
* Before this plugin is upgraded, remove it from the list of
* registered libraries.
*
* We need to remove it because this plugin may be upgraded
* (or downgraded) to a version of the plugin where it does not
* contain the library.
*
* Reregistration of this plugin will take place in the constructor
* the next time this class is instantiated.
*/
$utilPlugin = new \Boldgrid\Library\Util\Registration\Plugin( $plugin );
$utilPlugin->deregister();
}
return $options;
} | php | public function preUpgradePlugin( $options ) {
$plugin = ! empty( $options['hook_extra']['plugin'] ) ? $options['hook_extra']['plugin'] : null;
$isBoldgridPlugin = \Boldgrid\Library\Library\Util\Plugin::isBoldgridPlugin( $plugin );
if( $isBoldgridPlugin ) {
/*
* Before this plugin is upgraded, remove it from the list of
* registered libraries.
*
* We need to remove it because this plugin may be upgraded
* (or downgraded) to a version of the plugin where it does not
* contain the library.
*
* Reregistration of this plugin will take place in the constructor
* the next time this class is instantiated.
*/
$utilPlugin = new \Boldgrid\Library\Util\Registration\Plugin( $plugin );
$utilPlugin->deregister();
}
return $options;
} | [
"public",
"function",
"preUpgradePlugin",
"(",
"$",
"options",
")",
"{",
"$",
"plugin",
"=",
"!",
"empty",
"(",
"$",
"options",
"[",
"'hook_extra'",
"]",
"[",
"'plugin'",
"]",
")",
"?",
"$",
"options",
"[",
"'hook_extra'",
"]",
"[",
"'plugin'",
"]",
":... | Take action before a plugin is upgraded.
It's nice that WordPress has an "upgrader_process_complete" action you
can hook into to take action after a plugin is upgraded. However, what
about an action BEFORE the upgrade? Such an action does not exist.
What does exist is the ability to filter our $upgrader options before the
upgrade takes place. So, in order to do an action before the upgrade
runs, we'll hook into the upgrader_package_options filter.
@since 2.2.1
@hook: upgrader_package_options
@param array $options See filter declaration in
wp-admin/includes/class-wp-upgrader.php
@return array | [
"Take",
"action",
"before",
"a",
"plugin",
"is",
"upgraded",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Library/Registration.php#L50-L73 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getDomains | public function getDomains() {
$domains = array();
$checks = $this->getChecks();
foreach ($checks as $check) {
$domains[$check->id] = $check->hostname;
}
return $domains;
} | php | public function getDomains() {
$domains = array();
$checks = $this->getChecks();
foreach ($checks as $check) {
$domains[$check->id] = $check->hostname;
}
return $domains;
} | [
"public",
"function",
"getDomains",
"(",
")",
"{",
"$",
"domains",
"=",
"array",
"(",
")",
";",
"$",
"checks",
"=",
"$",
"this",
"->",
"getChecks",
"(",
")",
";",
"foreach",
"(",
"$",
"checks",
"as",
"$",
"check",
")",
"{",
"$",
"domains",
"[",
"... | Fetches the list of domains being monitored in Pingdom.
@return array
An array of domains, indexed by check ID. | [
"Fetches",
"the",
"list",
"of",
"domains",
"being",
"monitored",
"in",
"Pingdom",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L91-L98 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getChecks | public function getChecks($limit = NULL, $offset = NULL) {
$parameters = array();
if (!empty($limit)) {
$parameters['limit'] = $limit;
if (!empty($offset)) {
$parameters['offset'] = $offset;
}
}
$data = $this->request('GET', 'checks', $parameters);
return $data->checks;
} | php | public function getChecks($limit = NULL, $offset = NULL) {
$parameters = array();
if (!empty($limit)) {
$parameters['limit'] = $limit;
if (!empty($offset)) {
$parameters['offset'] = $offset;
}
}
$data = $this->request('GET', 'checks', $parameters);
return $data->checks;
} | [
"public",
"function",
"getChecks",
"(",
"$",
"limit",
"=",
"NULL",
",",
"$",
"offset",
"=",
"NULL",
")",
"{",
"$",
"parameters",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"limit",
")",
")",
"{",
"$",
"parameters",
"[",
"'lim... | Retrieves a list of checks.
@param int $limit
Limits the number of returned checks to the specified quantity (max value
is 25000).
@param int $offset
Offset for listing (requires limit).
@return array
An indexed array of checks. | [
"Retrieves",
"a",
"list",
"of",
"checks",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L112-L122 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getCheck | public function getCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('GET', "checks/${check_id}");
return $data->check;
} | php | public function getCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('GET', "checks/${check_id}");
return $data->check;
} | [
"public",
"function",
"getCheck",
"(",
"$",
"check_id",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
")",
",",
"__METHOD__",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"request",
"(",
"'GE... | Retrieves detailed information about a specified check.
@param int $check_id
The ID of the check to retrieve.
@return array
An array of information about the check. | [
"Retrieves",
"detailed",
"information",
"about",
"a",
"specified",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L133-L137 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.addCheck | public function addCheck($check, $defaults = array()) {
$this->ensureParameters(array(
'name' => $check['name'],
'host' => $check['host'],
'url' => $check['url'],
), __METHOD__);
$check += $defaults;
$data = $this->request('POST', 'checks', $check);
return sprintf('Created check %s for %s at http://%s%s', $data->check->id, $check['name'], $check['host'], $check['url']);
} | php | public function addCheck($check, $defaults = array()) {
$this->ensureParameters(array(
'name' => $check['name'],
'host' => $check['host'],
'url' => $check['url'],
), __METHOD__);
$check += $defaults;
$data = $this->request('POST', 'checks', $check);
return sprintf('Created check %s for %s at http://%s%s', $data->check->id, $check['name'], $check['host'], $check['url']);
} | [
"public",
"function",
"addCheck",
"(",
"$",
"check",
",",
"$",
"defaults",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'name'",
"=>",
"$",
"check",
"[",
"'name'",
"]",
",",
"'host'",
"=>",
"$",
"check"... | Adds a new check.
@param array $check
An array representing the check to create. The only required properties
are "name" and "host", default values for the other properties will be
assumed if not explicitly provided.
@param array $defaults
An array of default settings for the check.
@return string
A success message. | [
"Adds",
"a",
"new",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L152-L161 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.pauseCheck | public function pauseCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$check = array(
'paused' => TRUE,
);
return $this->modifyCheck($check_id, $check);
} | php | public function pauseCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$check = array(
'paused' => TRUE,
);
return $this->modifyCheck($check_id, $check);
} | [
"public",
"function",
"pauseCheck",
"(",
"$",
"check_id",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
")",
",",
"__METHOD__",
")",
";",
"$",
"check",
"=",
"array",
"(",
"'paused'",
"=>",
"TRUE"... | Pauses a check.
@param int $check_id
The ID of the check to pause.
@return string
The returned response message. | [
"Pauses",
"a",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L172-L178 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.unpauseCheck | public function unpauseCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$check = array(
'paused' => FALSE,
);
return $this->modifyCheck($check_id, $check);
} | php | public function unpauseCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$check = array(
'paused' => FALSE,
);
return $this->modifyCheck($check_id, $check);
} | [
"public",
"function",
"unpauseCheck",
"(",
"$",
"check_id",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
")",
",",
"__METHOD__",
")",
";",
"$",
"check",
"=",
"array",
"(",
"'paused'",
"=>",
"FAL... | Unpauses a check.
@param array $check_id
The ID of the check to pause.
@return string
The returned response message. | [
"Unpauses",
"a",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L189-L195 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.pauseChecks | public function pauseChecks($check_ids) {
$this->ensureParameters(array('check_ids' => $check_ids), __METHOD__);
$parameters = array(
'paused' => TRUE,
);
return $this->modifyChecks($check_ids, $parameters);
} | php | public function pauseChecks($check_ids) {
$this->ensureParameters(array('check_ids' => $check_ids), __METHOD__);
$parameters = array(
'paused' => TRUE,
);
return $this->modifyChecks($check_ids, $parameters);
} | [
"public",
"function",
"pauseChecks",
"(",
"$",
"check_ids",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_ids'",
"=>",
"$",
"check_ids",
")",
",",
"__METHOD__",
")",
";",
"$",
"parameters",
"=",
"array",
"(",
"'paused'",
"=>",... | Pauses multiple checks.
@param array $check_ids
An array of check IDs to pause.
@return string
The returned response message. | [
"Pauses",
"multiple",
"checks",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L206-L212 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.unpauseChecks | public function unpauseChecks($check_ids) {
$this->ensureParameters(array('check_ids' => $check_ids), __METHOD__);
$parameters = array(
'paused' => FALSE,
);
return $this->modifyChecks($check_ids, $parameters);
} | php | public function unpauseChecks($check_ids) {
$this->ensureParameters(array('check_ids' => $check_ids), __METHOD__);
$parameters = array(
'paused' => FALSE,
);
return $this->modifyChecks($check_ids, $parameters);
} | [
"public",
"function",
"unpauseChecks",
"(",
"$",
"check_ids",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_ids'",
"=>",
"$",
"check_ids",
")",
",",
"__METHOD__",
")",
";",
"$",
"parameters",
"=",
"array",
"(",
"'paused'",
"=>... | Unpauses multiple checks.
@param array $check_ids
An array of check IDs to unpause.
@return string
The returned response message. | [
"Unpauses",
"multiple",
"checks",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L223-L229 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.modifyCheck | public function modifyCheck($check_id, $parameters) {
$this->ensureParameters(array(
'check_id' => $check_id,
'parameters' => $parameters,
), __METHOD__);
$data = $this->request('PUT', "checks/${check_id}", $parameters);
return $data->message;
} | php | public function modifyCheck($check_id, $parameters) {
$this->ensureParameters(array(
'check_id' => $check_id,
'parameters' => $parameters,
), __METHOD__);
$data = $this->request('PUT', "checks/${check_id}", $parameters);
return $data->message;
} | [
"public",
"function",
"modifyCheck",
"(",
"$",
"check_id",
",",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
",",
"'parameters'",
"=>",
"$",
"parameters",
",",
")",
",",
"__METH... | Modifies a check.
@param int $check_id
The ID of the check to modify.
@param array $parameters
An array of settings by which to modify the check.
@return string
The returned response message. | [
"Modifies",
"a",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L242-L249 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.modifyChecks | public function modifyChecks($check_ids, $parameters) {
$this->ensureParameters(array(
'check_ids' => $check_ids,
'parameters' => $parameters,
), __METHOD__);
$parameters['checkids'] = implode(',', $check_ids);
$data = $this->request('PUT', 'checks', $parameters);
return $data->message;
} | php | public function modifyChecks($check_ids, $parameters) {
$this->ensureParameters(array(
'check_ids' => $check_ids,
'parameters' => $parameters,
), __METHOD__);
$parameters['checkids'] = implode(',', $check_ids);
$data = $this->request('PUT', 'checks', $parameters);
return $data->message;
} | [
"public",
"function",
"modifyChecks",
"(",
"$",
"check_ids",
",",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_ids'",
"=>",
"$",
"check_ids",
",",
"'parameters'",
"=>",
"$",
"parameters",
",",
")",
",",
"__... | Modifies multiple checks.
Pingdom allows all checks to be modified at once when the "checkids"
parameter is not supplied but since that is a very destructive operation we
require the check IDs to be explicitly specified. See modifyAllChecks() if
you need to modify all checks at once.
@param array $check_ids
An array of check IDs to modify.
@param array $parameters
An array of parameters by which to modify the given checks:
- paused: TRUE for paused; FALSE for unpaused.
- resolution: An integer specifying the check frequency.
@return string
The returned response message. | [
"Modifies",
"multiple",
"checks",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L269-L277 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.modifyAllChecks | public function modifyAllChecks($parameters) {
$this->ensureParameters(array('parameters' => $parameters), __METHOD__);
$data = $this->request('PUT', 'checks', $parameters);
return $data->message;
} | php | public function modifyAllChecks($parameters) {
$this->ensureParameters(array('parameters' => $parameters), __METHOD__);
$data = $this->request('PUT', 'checks', $parameters);
return $data->message;
} | [
"public",
"function",
"modifyAllChecks",
"(",
"$",
"parameters",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'parameters'",
"=>",
"$",
"parameters",
")",
",",
"__METHOD__",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"request",
... | Modifies all checks.
This method can be used to modify all checks at once. Check modification by
this method is limited to adjusting the paused status and check frequency.
This is a relatively destructive operation so please be careful that you
intend to modify all checks before calling this method.
@param array $parameters
An array of parameters by which to modify the given checks:
- paused: TRUE for paused; FALSE for unpaused.
- resolution: An integer specifying the check frequency.
@return string
The returned response message. | [
"Modifies",
"all",
"checks",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L295-L299 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.removeCheck | public function removeCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('DELETE', "checks/${check_id}");
return $data->message;
} | php | public function removeCheck($check_id) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('DELETE', "checks/${check_id}");
return $data->message;
} | [
"public",
"function",
"removeCheck",
"(",
"$",
"check_id",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
")",
",",
"__METHOD__",
")",
";",
"$",
"data",
"=",
"$",
"this",
"->",
"request",
"(",
"... | Removes a check.
@param int $check_id
The ID of the check to remove.
@return string
The returned response message. | [
"Removes",
"a",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L310-L314 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getContacts | public function getContacts($limit = NULL, $offset = NULL) {
$parameters = array();
if (!empty($limit)) {
$parameters['limit'] = $limit;
if (!empty($offset)) {
$parameters['offset'] = $offset;
}
}
$data = $this->request('GET', 'contacts', $parameters);
return $data->contacts;
} | php | public function getContacts($limit = NULL, $offset = NULL) {
$parameters = array();
if (!empty($limit)) {
$parameters['limit'] = $limit;
if (!empty($offset)) {
$parameters['offset'] = $offset;
}
}
$data = $this->request('GET', 'contacts', $parameters);
return $data->contacts;
} | [
"public",
"function",
"getContacts",
"(",
"$",
"limit",
"=",
"NULL",
",",
"$",
"offset",
"=",
"NULL",
")",
"{",
"$",
"parameters",
"=",
"array",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"limit",
")",
")",
"{",
"$",
"parameters",
"[",
"'l... | Gets the list of contacts stored in Pingdom.
@param int $limit
Limits the number of returned contacts to the specified quantity.
@param int $offset
The offset for the listing (requires limit).
@return string
The returned response message. | [
"Gets",
"the",
"list",
"of",
"contacts",
"stored",
"in",
"Pingdom",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L346-L356 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getAnalysis | public function getAnalysis($check_id, $parameters = array()) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('GET', "analysis/${check_id}", $parameters);
return $data->analysis;
} | php | public function getAnalysis($check_id, $parameters = array()) {
$this->ensureParameters(array('check_id' => $check_id), __METHOD__);
$data = $this->request('GET', "analysis/${check_id}", $parameters);
return $data->analysis;
} | [
"public",
"function",
"getAnalysis",
"(",
"$",
"check_id",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
")",
",",
"__METHOD__",
")",
";",
"$",
"... | Fetches the latest root cause analysis results for a specified check.
@param int $check_id
The ID of the check.
@param array $parameters
An array of parameters for the request.
@return string
The returned response message. | [
"Fetches",
"the",
"latest",
"root",
"cause",
"analysis",
"results",
"for",
"a",
"specified",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L391-L395 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getRawAnalysis | public function getRawAnalysis($check_id, $analysis_id, $parameters = array()) {
$this->ensureParameters(array(
'check_id' => $check_id,
'analysis_id' => $analysis_id,
), __METHOD__);
$data = $this->request('GET', "analysis/{$check_id}/{$analysis_id}", $parameters);
return $data;
} | php | public function getRawAnalysis($check_id, $analysis_id, $parameters = array()) {
$this->ensureParameters(array(
'check_id' => $check_id,
'analysis_id' => $analysis_id,
), __METHOD__);
$data = $this->request('GET', "analysis/{$check_id}/{$analysis_id}", $parameters);
return $data;
} | [
"public",
"function",
"getRawAnalysis",
"(",
"$",
"check_id",
",",
"$",
"analysis_id",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"ensureParameters",
"(",
"array",
"(",
"'check_id'",
"=>",
"$",
"check_id",
",",
"'analysis_... | Fetches the raw root cause analysis for a specified check.
@param int $check_id
The ID of the check.
@param int $analysis_id
The analysis ID.
@param array $parameters
An array of parameters for the request.
@return string
The returned response message. | [
"Fetches",
"the",
"raw",
"root",
"cause",
"analysis",
"for",
"a",
"specified",
"check",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L410-L417 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.ensureParameters | public function ensureParameters($parameters = array(), $method) {
if (empty($parameters) || empty($method)) {
throw new MissingParameterException(sprintf('%s called without required parameters.', __METHOD__));
}
foreach ($parameters as $parameter => $value) {
if (!isset($value)) {
throw new MissingParameterException(sprintf('Missing required %s parameter in %s', $parameter, $method));
}
}
} | php | public function ensureParameters($parameters = array(), $method) {
if (empty($parameters) || empty($method)) {
throw new MissingParameterException(sprintf('%s called without required parameters.', __METHOD__));
}
foreach ($parameters as $parameter => $value) {
if (!isset($value)) {
throw new MissingParameterException(sprintf('Missing required %s parameter in %s', $parameter, $method));
}
}
} | [
"public",
"function",
"ensureParameters",
"(",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"$",
"method",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"parameters",
")",
"||",
"empty",
"(",
"$",
"method",
")",
")",
"{",
"throw",
"new",
"MissingParameter... | Checks that required parameters were provided.
PHP only triggers a warning for missing parameters and continues with
program execution. To avoid calling the Pingdom API with known malformed
data, we throw an exception if we find that something required is missing.
@param array $parameters
An array of parameters to check, keyed by parameter name with the
parameter itself as the value.
@param string $method
The calling method's name.
@throws MissingParameterException | [
"Checks",
"that",
"required",
"parameters",
"were",
"provided",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L434-L443 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.request | public function request($method, $resource, $parameters = array(), $headers = array(), $body = NULL) {
$handle = curl_init();
$headers[] = 'Content-Type: application/json; charset=utf-8';
$headers[] = 'App-Key: ' . $this->api_key;
if (!empty($this->account_email)) {
$headers[] = 'Account-Email: '.$this->account_email;
}
if (!empty($body)) {
if (!is_string($body)) {
$body = json_encode($body);
}
curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
$headers[] = 'Content-Length: ' . strlen($body);
}
if (!empty($headers)) {
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_URL, $this->buildRequestUrl($resource, $parameters));
curl_setopt($handle, CURLOPT_USERPWD, $this->getAuth());
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_MAXREDIRS, 10);
curl_setopt($handle, CURLOPT_USERAGENT, 'PingdomApi/1.0');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_TIMEOUT, 10);
$gzip = !empty($this->gzip) ? 'gzip' : '';
curl_setopt($handle, CURLOPT_ENCODING, $gzip);
$response = curl_exec($handle);
if (curl_errno($handle) > 0) {
$curl_error = sprintf('Curl error: %s', curl_error($handle));
curl_close($handle);
throw new CurlErrorException($curl_error, $curl_errno);
}
$data = json_decode($response);
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
$status_class = (int) floor($status / 100);
if ($status_class === 4 || $status_class === 5) {
$message = $this->getError($data, $status);
switch ($status_class) {
case 4:
throw new ClientErrorException(sprintf('Client error: %s', $message), $status);
case 5:
throw new ServerErrorException(sprintf('Server error: %s', $message), $status);
}
}
return $data;
} | php | public function request($method, $resource, $parameters = array(), $headers = array(), $body = NULL) {
$handle = curl_init();
$headers[] = 'Content-Type: application/json; charset=utf-8';
$headers[] = 'App-Key: ' . $this->api_key;
if (!empty($this->account_email)) {
$headers[] = 'Account-Email: '.$this->account_email;
}
if (!empty($body)) {
if (!is_string($body)) {
$body = json_encode($body);
}
curl_setopt($handle, CURLOPT_POSTFIELDS, $body);
$headers[] = 'Content-Length: ' . strlen($body);
}
if (!empty($headers)) {
curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_URL, $this->buildRequestUrl($resource, $parameters));
curl_setopt($handle, CURLOPT_USERPWD, $this->getAuth());
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_MAXREDIRS, 10);
curl_setopt($handle, CURLOPT_USERAGENT, 'PingdomApi/1.0');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_TIMEOUT, 10);
$gzip = !empty($this->gzip) ? 'gzip' : '';
curl_setopt($handle, CURLOPT_ENCODING, $gzip);
$response = curl_exec($handle);
if (curl_errno($handle) > 0) {
$curl_error = sprintf('Curl error: %s', curl_error($handle));
curl_close($handle);
throw new CurlErrorException($curl_error, $curl_errno);
}
$data = json_decode($response);
$status = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
$status_class = (int) floor($status / 100);
if ($status_class === 4 || $status_class === 5) {
$message = $this->getError($data, $status);
switch ($status_class) {
case 4:
throw new ClientErrorException(sprintf('Client error: %s', $message), $status);
case 5:
throw new ServerErrorException(sprintf('Server error: %s', $message), $status);
}
}
return $data;
} | [
"public",
"function",
"request",
"(",
"$",
"method",
",",
"$",
"resource",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
",",
"$",
"headers",
"=",
"array",
"(",
")",
",",
"$",
"body",
"=",
"NULL",
")",
"{",
"$",
"handle",
"=",
"curl_init",
"(",
... | Makes a request to the Pingdom REST API.
@param string $method
The HTTP request method e.g. GET, POST, and PUT.
@param string $resource
The resource location e.g. checks/{checkid}.
@param array $parameters
The request parameters, if any are required. This is used to build the
URL query string.
@param array $headers
Additional request headers, if any are required.
@param mixed $body
Data to use for the body of the request when using POST or PUT methods.
This can be a JSON string literal or something that json_encode() accepts.
@return object
An object containing the response data. | [
"Makes",
"a",
"request",
"to",
"the",
"Pingdom",
"REST",
"API",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L464-L516 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.buildRequestUrl | public function buildRequestUrl($resource, $parameters = array()) {
foreach ($parameters as $property => $value) {
if (is_bool($value)) {
$parameters[$property] = $value ? 'true' : 'false';
}
}
$query = empty($parameters) ? '' : '?' . http_build_query($parameters, NULL, '&');
return sprintf('%s/%s%s', self::ENDPOINT, $resource, $query);
} | php | public function buildRequestUrl($resource, $parameters = array()) {
foreach ($parameters as $property => $value) {
if (is_bool($value)) {
$parameters[$property] = $value ? 'true' : 'false';
}
}
$query = empty($parameters) ? '' : '?' . http_build_query($parameters, NULL, '&');
return sprintf('%s/%s%s', self::ENDPOINT, $resource, $query);
} | [
"public",
"function",
"buildRequestUrl",
"(",
"$",
"resource",
",",
"$",
"parameters",
"=",
"array",
"(",
")",
")",
"{",
"foreach",
"(",
"$",
"parameters",
"as",
"$",
"property",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_bool",
"(",
"$",
"value",
... | Builds the request URL.
The Pingdom API requires boolean values to be transmitted as "true" and
"false" string representations. To preserve the convenience of using the
boolean types we will convert them here.
@param string $resource
The resource path part of the URL, without leading or trailing slashes.
@param array $parameters
An array of query string parameters to append to the URL.
@return string
The fully-formed request URI. | [
"Builds",
"the",
"request",
"URL",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L533-L541 | train |
acquia/pingdom-api | src/Acquia/Pingdom/PingdomApi.php | PingdomApi.getError | protected function getError($response_data, $status) {
if (!empty($response_data->error)) {
$error = $response_data->error;
$message = sprintf('%s %s: %s',
$error->statuscode,
$error->statusdesc,
$error->errormessage);
}
else {
$message = sprintf('Error code: %s. No reason was given by Pingdom for the error.', $status);
}
return $message;
} | php | protected function getError($response_data, $status) {
if (!empty($response_data->error)) {
$error = $response_data->error;
$message = sprintf('%s %s: %s',
$error->statuscode,
$error->statusdesc,
$error->errormessage);
}
else {
$message = sprintf('Error code: %s. No reason was given by Pingdom for the error.', $status);
}
return $message;
} | [
"protected",
"function",
"getError",
"(",
"$",
"response_data",
",",
"$",
"status",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"response_data",
"->",
"error",
")",
")",
"{",
"$",
"error",
"=",
"$",
"response_data",
"->",
"error",
";",
"$",
"message",... | Gets the human-readable error message for a failed request.
@param object $response_data
The object containing the response data.
@param int $status
The HTTP status code.
@return string
The error message. | [
"Gets",
"the",
"human",
"-",
"readable",
"error",
"message",
"for",
"a",
"failed",
"request",
"."
] | 62a506f4cd89ed8129873401e2f72ed21e1ccb2a | https://github.com/acquia/pingdom-api/blob/62a506f4cd89ed8129873401e2f72ed21e1ccb2a/src/Acquia/Pingdom/PingdomApi.php#L554-L566 | train |
thelia/core | lib/Thelia/Core/Template/Loop/Coupon.php | Coupon.getArgDefinitions | protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createBooleanOrBothTypeArgument('is_enabled'),
Argument::createBooleanTypeArgument('in_use'),
Argument::createAnyListTypeArgument('code'),
new Argument(
'order',
new TypeCollection(
new EnumListType(
array(
'id', 'id-reverse',
'code', 'code-reverse',
'title', 'title-reverse',
'enabled', 'enabled-reverse',
'start-date', 'start-date-reverse',
'expiration-date', 'expiration-date-reverse',
'days-left', 'days-left-reverse',
'usages-left', 'usages-left-reverse'
)
)
),
'code'
)
);
} | php | protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createBooleanOrBothTypeArgument('is_enabled'),
Argument::createBooleanTypeArgument('in_use'),
Argument::createAnyListTypeArgument('code'),
new Argument(
'order',
new TypeCollection(
new EnumListType(
array(
'id', 'id-reverse',
'code', 'code-reverse',
'title', 'title-reverse',
'enabled', 'enabled-reverse',
'start-date', 'start-date-reverse',
'expiration-date', 'expiration-date-reverse',
'days-left', 'days-left-reverse',
'usages-left', 'usages-left-reverse'
)
)
),
'code'
)
);
} | [
"protected",
"function",
"getArgDefinitions",
"(",
")",
"{",
"return",
"new",
"ArgumentCollection",
"(",
"Argument",
"::",
"createIntListTypeArgument",
"(",
"'id'",
")",
",",
"Argument",
"::",
"createBooleanOrBothTypeArgument",
"(",
"'is_enabled'",
")",
",",
"Argument... | Define all args used in your loop
@return ArgumentCollection | [
"Define",
"all",
"args",
"used",
"in",
"your",
"loop"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Core/Template/Loop/Coupon.php#L53-L79 | train |
thelia/core | lib/Thelia/Install/Database.php | Database.prepareSql | protected function prepareSql($sql)
{
$sql = str_replace(";',", "-CODE-", $sql);
$sql = trim($sql);
preg_match_all('#DELIMITER (.+?)\n(.+?)DELIMITER ;#s', $sql, $m);
foreach ($m[0] as $k => $v) {
if ($m[1][$k] == '|') {
throw new \RuntimeException('You can not use "|" as delimiter: '.$v);
}
$stored = str_replace(';', '|', $m[2][$k]);
$stored = str_replace($m[1][$k], ";\n", $stored);
$sql = str_replace($v, $stored, $sql);
}
$query = array();
$tab = explode(";\n", $sql);
$size = \count($tab);
for ($i = 0; $i < $size; $i++) {
$queryTemp = str_replace("-CODE-", ";',", $tab[$i]);
$queryTemp = str_replace("|", ";", $queryTemp);
$query[] = $queryTemp;
}
return $query;
} | php | protected function prepareSql($sql)
{
$sql = str_replace(";',", "-CODE-", $sql);
$sql = trim($sql);
preg_match_all('#DELIMITER (.+?)\n(.+?)DELIMITER ;#s', $sql, $m);
foreach ($m[0] as $k => $v) {
if ($m[1][$k] == '|') {
throw new \RuntimeException('You can not use "|" as delimiter: '.$v);
}
$stored = str_replace(';', '|', $m[2][$k]);
$stored = str_replace($m[1][$k], ";\n", $stored);
$sql = str_replace($v, $stored, $sql);
}
$query = array();
$tab = explode(";\n", $sql);
$size = \count($tab);
for ($i = 0; $i < $size; $i++) {
$queryTemp = str_replace("-CODE-", ";',", $tab[$i]);
$queryTemp = str_replace("|", ";", $queryTemp);
$query[] = $queryTemp;
}
return $query;
} | [
"protected",
"function",
"prepareSql",
"(",
"$",
"sql",
")",
"{",
"$",
"sql",
"=",
"str_replace",
"(",
"\";',\"",
",",
"\"-CODE-\"",
",",
"$",
"sql",
")",
";",
"$",
"sql",
"=",
"trim",
"(",
"$",
"sql",
")",
";",
"preg_match_all",
"(",
"'#DELIMITER (.+?... | Separate each sql instruction in an array
@param $sql
@return array | [
"Separate",
"each",
"sql",
"instruction",
"in",
"an",
"array"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Database.php#L128-L152 | train |
thelia/core | lib/Thelia/Install/Database.php | Database.backupDb | public function backupDb($filename, $tables = '*')
{
$data = [];
// get all of the tables
if ($tables == '*') {
$tables = array();
$result = $this->connection->prepare('SHOW TABLES');
$result->execute();
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
} else {
$tables = \is_array($tables) ? $tables : explode(',', $tables);
}
$data[] = "\n";
$data[] = 'SET foreign_key_checks=0;';
$data[] = "\n\n";
foreach ($tables as $table) {
if (!preg_match("/^[\w_\-]+$/", $table)) {
Tlog::getInstance()->alert(
sprintf(
"Attempt to backup the db with this invalid table name: '%s'",
$table
)
);
continue;
}
$result = $this->execute('SELECT * FROM `' . $table . '`');
$fieldCount = $result->columnCount();
$data[] = 'DROP TABLE `' . $table . '`;';
$resultStruct = $this->execute('SHOW CREATE TABLE `' . $table . '`');
$rowStruct = $resultStruct->fetch(PDO::FETCH_NUM);
$data[] = "\n\n";
$data[] = $rowStruct[1];
$data[] = ";\n\n";
for ($i = 0; $i < $fieldCount; $i++) {
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$data[] = 'INSERT INTO `' . $table . '` VALUES(';
for ($j = 0; $j < $fieldCount; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$data[] = '"' . $row[$j] . '"';
} else {
$data[] = '""';
}
if ($j < ($fieldCount - 1)) {
$data[] = ',';
}
}
$data[] = ");\n";
}
}
$data[] = "\n\n\n";
}
$data[] = 'SET foreign_key_checks=1;';
//save filename
$this->writeFilename($filename, $data);
} | php | public function backupDb($filename, $tables = '*')
{
$data = [];
// get all of the tables
if ($tables == '*') {
$tables = array();
$result = $this->connection->prepare('SHOW TABLES');
$result->execute();
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$tables[] = $row[0];
}
} else {
$tables = \is_array($tables) ? $tables : explode(',', $tables);
}
$data[] = "\n";
$data[] = 'SET foreign_key_checks=0;';
$data[] = "\n\n";
foreach ($tables as $table) {
if (!preg_match("/^[\w_\-]+$/", $table)) {
Tlog::getInstance()->alert(
sprintf(
"Attempt to backup the db with this invalid table name: '%s'",
$table
)
);
continue;
}
$result = $this->execute('SELECT * FROM `' . $table . '`');
$fieldCount = $result->columnCount();
$data[] = 'DROP TABLE `' . $table . '`;';
$resultStruct = $this->execute('SHOW CREATE TABLE `' . $table . '`');
$rowStruct = $resultStruct->fetch(PDO::FETCH_NUM);
$data[] = "\n\n";
$data[] = $rowStruct[1];
$data[] = ";\n\n";
for ($i = 0; $i < $fieldCount; $i++) {
while ($row = $result->fetch(PDO::FETCH_NUM)) {
$data[] = 'INSERT INTO `' . $table . '` VALUES(';
for ($j = 0; $j < $fieldCount; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$data[] = '"' . $row[$j] . '"';
} else {
$data[] = '""';
}
if ($j < ($fieldCount - 1)) {
$data[] = ',';
}
}
$data[] = ");\n";
}
}
$data[] = "\n\n\n";
}
$data[] = 'SET foreign_key_checks=1;';
//save filename
$this->writeFilename($filename, $data);
} | [
"public",
"function",
"backupDb",
"(",
"$",
"filename",
",",
"$",
"tables",
"=",
"'*'",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"// get all of the tables",
"if",
"(",
"$",
"tables",
"==",
"'*'",
")",
"{",
"$",
"tables",
"=",
"array",
"(",
")",
"... | Backup the db OR just a table
@param string $filename
@param string $tables | [
"Backup",
"the",
"db",
"OR",
"just",
"a",
"table"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Database.php#L160-L231 | train |
thelia/core | lib/Thelia/Install/Database.php | Database.writeFilename | private function writeFilename($filename, $data)
{
$f = fopen($filename, "w+");
fwrite($f, implode('', $data));
fclose($f);
} | php | private function writeFilename($filename, $data)
{
$f = fopen($filename, "w+");
fwrite($f, implode('', $data));
fclose($f);
} | [
"private",
"function",
"writeFilename",
"(",
"$",
"filename",
",",
"$",
"data",
")",
"{",
"$",
"f",
"=",
"fopen",
"(",
"$",
"filename",
",",
"\"w+\"",
")",
";",
"fwrite",
"(",
"$",
"f",
",",
"implode",
"(",
"''",
",",
"$",
"data",
")",
")",
";",
... | Save an array of data to a filename
@param string $filename
@param array $data | [
"Save",
"an",
"array",
"of",
"data",
"to",
"a",
"filename"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Database.php#L250-L256 | train |
thelia/core | lib/Thelia/Action/Country.php | Country.toggleVisibility | public function toggleVisibility(CountryToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$country = $event->getCountry();
$country
->setDispatcher($dispatcher)
->setVisible(!$country->getVisible())
->save();
$event->setCountry($country);
} | php | public function toggleVisibility(CountryToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$country = $event->getCountry();
$country
->setDispatcher($dispatcher)
->setVisible(!$country->getVisible())
->save();
$event->setCountry($country);
} | [
"public",
"function",
"toggleVisibility",
"(",
"CountryToggleVisibilityEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"country",
"=",
"$",
"event",
"->",
"getCountry",
"(",
")",
";",
"$",
"country"... | Toggle Country visibility
@param CountryToggleVisibilityEvent $event
@param $eventName
@param EventDispatcherInterface $dispatcher | [
"Toggle",
"Country",
"visibility"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Country.php#L96-L106 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.addItem | public function addItem(CartEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$cart = $event->getCart();
$newness = $event->getNewness();
$append = $event->getAppend();
$quantity = $event->getQuantity();
$currency = $cart->getCurrency();
$customer = $cart->getCustomer();
$discount = 0;
if ($cart->isNew()) {
$persistEvent = new CartPersistEvent($cart);
$dispatcher->dispatch(TheliaEvents::CART_PERSIST, $persistEvent);
}
if (null !== $customer && $customer->getDiscount() > 0) {
$discount = $customer->getDiscount();
}
$productSaleElementsId = $event->getProductSaleElementsId();
$productId = $event->getProduct();
// Search for an identical item in the cart
$findItemEvent = clone $event;
$dispatcher->dispatch(TheliaEvents::CART_FINDITEM, $findItemEvent);
$cartItem = $findItemEvent->getCartItem();
if ($cartItem === null || $newness) {
$productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId);
if (null !== $productSaleElements) {
$productPrices = $productSaleElements->getPricesByCurrency($currency, $discount);
$cartItem = $this->doAddItem($dispatcher, $cart, $productId, $productSaleElements, $quantity, $productPrices);
}
} elseif ($append && $cartItem !== null) {
$cartItem->addQuantity($quantity)->save();
}
$event->setCartItem($cartItem);
} | php | public function addItem(CartEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$cart = $event->getCart();
$newness = $event->getNewness();
$append = $event->getAppend();
$quantity = $event->getQuantity();
$currency = $cart->getCurrency();
$customer = $cart->getCustomer();
$discount = 0;
if ($cart->isNew()) {
$persistEvent = new CartPersistEvent($cart);
$dispatcher->dispatch(TheliaEvents::CART_PERSIST, $persistEvent);
}
if (null !== $customer && $customer->getDiscount() > 0) {
$discount = $customer->getDiscount();
}
$productSaleElementsId = $event->getProductSaleElementsId();
$productId = $event->getProduct();
// Search for an identical item in the cart
$findItemEvent = clone $event;
$dispatcher->dispatch(TheliaEvents::CART_FINDITEM, $findItemEvent);
$cartItem = $findItemEvent->getCartItem();
if ($cartItem === null || $newness) {
$productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId);
if (null !== $productSaleElements) {
$productPrices = $productSaleElements->getPricesByCurrency($currency, $discount);
$cartItem = $this->doAddItem($dispatcher, $cart, $productId, $productSaleElements, $quantity, $productPrices);
}
} elseif ($append && $cartItem !== null) {
$cartItem->addQuantity($quantity)->save();
}
$event->setCartItem($cartItem);
} | [
"public",
"function",
"addItem",
"(",
"CartEvent",
"$",
"event",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"cart",
"=",
"$",
"event",
"->",
"getCart",
"(",
")",
";",
"$",
"newness",
"=",
"$",
"event",
"->",... | add an article in the current cart
@param \Thelia\Core\Event\Cart\CartEvent $event
@param $eventName
@param EventDispatcherInterface $dispatcher | [
"add",
"an",
"article",
"in",
"the",
"current",
"cart"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L80-L122 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.updateQuantity | protected function updateQuantity(EventDispatcherInterface $dispatcher, CartItem $cartItem, $quantity)
{
$cartItem->setDisptacher($dispatcher);
$cartItem->updateQuantity($quantity)
->save();
return $cartItem;
} | php | protected function updateQuantity(EventDispatcherInterface $dispatcher, CartItem $cartItem, $quantity)
{
$cartItem->setDisptacher($dispatcher);
$cartItem->updateQuantity($quantity)
->save();
return $cartItem;
} | [
"protected",
"function",
"updateQuantity",
"(",
"EventDispatcherInterface",
"$",
"dispatcher",
",",
"CartItem",
"$",
"cartItem",
",",
"$",
"quantity",
")",
"{",
"$",
"cartItem",
"->",
"setDisptacher",
"(",
"$",
"dispatcher",
")",
";",
"$",
"cartItem",
"->",
"u... | increase the quantity for an existing cartItem
@param EventDispatcherInterface $dispatcher
@param CartItem $cartItem
@param float $quantity
@throws \Exception
@throws \Propel\Runtime\Exception\PropelException
@return CartItem | [
"increase",
"the",
"quantity",
"for",
"an",
"existing",
"cartItem"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L238-L245 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.doAddItem | protected function doAddItem(
EventDispatcherInterface $dispatcher,
CartModel $cart,
$productId,
ProductSaleElements $productSaleElements,
$quantity,
ProductPriceTools $productPrices
) {
$cartItem = new CartItem();
$cartItem->setDisptacher($dispatcher);
$cartItem
->setCart($cart)
->setProductId($productId)
->setProductSaleElementsId($productSaleElements->getId())
->setQuantity($quantity)
->setPrice($productPrices->getPrice())
->setPromoPrice($productPrices->getPromoPrice())
->setPromo($productSaleElements->getPromo())
->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30))
->save();
return $cartItem;
} | php | protected function doAddItem(
EventDispatcherInterface $dispatcher,
CartModel $cart,
$productId,
ProductSaleElements $productSaleElements,
$quantity,
ProductPriceTools $productPrices
) {
$cartItem = new CartItem();
$cartItem->setDisptacher($dispatcher);
$cartItem
->setCart($cart)
->setProductId($productId)
->setProductSaleElementsId($productSaleElements->getId())
->setQuantity($quantity)
->setPrice($productPrices->getPrice())
->setPromoPrice($productPrices->getPromoPrice())
->setPromo($productSaleElements->getPromo())
->setPriceEndOfLife(time() + ConfigQuery::read("cart.priceEOF", 60*60*24*30))
->save();
return $cartItem;
} | [
"protected",
"function",
"doAddItem",
"(",
"EventDispatcherInterface",
"$",
"dispatcher",
",",
"CartModel",
"$",
"cart",
",",
"$",
"productId",
",",
"ProductSaleElements",
"$",
"productSaleElements",
",",
"$",
"quantity",
",",
"ProductPriceTools",
"$",
"productPrices"... | try to attach a new item to an existing cart
@param EventDispatcherInterface $dispatcher
@param \Thelia\Model\Cart $cart
@param int $productId
@param ProductSaleElements $productSaleElements
@param float $quantity
@param ProductPriceTools $productPrices
@return CartItem | [
"try",
"to",
"attach",
"a",
"new",
"item",
"to",
"an",
"existing",
"cart"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L259-L281 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.findItem | protected function findItem($cartId, $productId, $productSaleElementsId)
{
return CartItemQuery::create()
->filterByCartId($cartId)
->filterByProductId($productId)
->filterByProductSaleElementsId($productSaleElementsId)
->findOne();
} | php | protected function findItem($cartId, $productId, $productSaleElementsId)
{
return CartItemQuery::create()
->filterByCartId($cartId)
->filterByProductId($productId)
->filterByProductSaleElementsId($productSaleElementsId)
->findOne();
} | [
"protected",
"function",
"findItem",
"(",
"$",
"cartId",
",",
"$",
"productId",
",",
"$",
"productSaleElementsId",
")",
"{",
"return",
"CartItemQuery",
"::",
"create",
"(",
")",
"->",
"filterByCartId",
"(",
"$",
"cartId",
")",
"->",
"filterByProductId",
"(",
... | find a specific record in CartItem table using the Cart id, the product id
and the product_sale_elements id
@param int $cartId
@param int $productId
@param int $productSaleElementsId
@return CartItem
@deprecated this method is deprecated. Dispatch a TheliaEvents::CART_FINDITEM instead | [
"find",
"a",
"specific",
"record",
"in",
"CartItem",
"table",
"using",
"the",
"Cart",
"id",
"the",
"product",
"id",
"and",
"the",
"product_sale_elements",
"id"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L294-L301 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.findCartItem | public function findCartItem(CartEvent $event)
{
// Do not try to find a cartItem if one exists in the event, as previous event handlers
// mays have put it in th event.
if (null === $event->getCartItem() && null !== $foundItem = CartItemQuery::create()
->filterByCartId($event->getCart()->getId())
->filterByProductId($event->getProduct())
->filterByProductSaleElementsId($event->getProductSaleElementsId())
->findOne()) {
$event->setCartItem($foundItem);
}
} | php | public function findCartItem(CartEvent $event)
{
// Do not try to find a cartItem if one exists in the event, as previous event handlers
// mays have put it in th event.
if (null === $event->getCartItem() && null !== $foundItem = CartItemQuery::create()
->filterByCartId($event->getCart()->getId())
->filterByProductId($event->getProduct())
->filterByProductSaleElementsId($event->getProductSaleElementsId())
->findOne()) {
$event->setCartItem($foundItem);
}
} | [
"public",
"function",
"findCartItem",
"(",
"CartEvent",
"$",
"event",
")",
"{",
"// Do not try to find a cartItem if one exists in the event, as previous event handlers",
"// mays have put it in th event.",
"if",
"(",
"null",
"===",
"$",
"event",
"->",
"getCartItem",
"(",
")"... | Find a specific record in CartItem table using the current CartEvent
@param CartEvent $event the cart event | [
"Find",
"a",
"specific",
"record",
"in",
"CartItem",
"table",
"using",
"the",
"current",
"CartEvent"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L308-L319 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.restoreCurrentCart | public function restoreCurrentCart(CartRestoreEvent $cartRestoreEvent, $eventName, EventDispatcherInterface $dispatcher)
{
$cookieName = ConfigQuery::read("cart.cookie_name", 'thelia_cart');
$persistentCookie = ConfigQuery::read("cart.use_persistent_cookie", 1);
$cart = null;
if ($this->requestStack->getCurrentRequest()->cookies->has($cookieName) && $persistentCookie) {
$cart = $this->managePersistentCart($cartRestoreEvent, $cookieName, $dispatcher);
} elseif (!$persistentCookie) {
$cart = $this->manageNonPersistentCookie($cartRestoreEvent, $dispatcher);
}
// Still no cart ? Create a new one.
if (null === $cart) {
$cart = $this->dispatchNewCart($dispatcher);
}
$cartRestoreEvent->setCart($cart);
} | php | public function restoreCurrentCart(CartRestoreEvent $cartRestoreEvent, $eventName, EventDispatcherInterface $dispatcher)
{
$cookieName = ConfigQuery::read("cart.cookie_name", 'thelia_cart');
$persistentCookie = ConfigQuery::read("cart.use_persistent_cookie", 1);
$cart = null;
if ($this->requestStack->getCurrentRequest()->cookies->has($cookieName) && $persistentCookie) {
$cart = $this->managePersistentCart($cartRestoreEvent, $cookieName, $dispatcher);
} elseif (!$persistentCookie) {
$cart = $this->manageNonPersistentCookie($cartRestoreEvent, $dispatcher);
}
// Still no cart ? Create a new one.
if (null === $cart) {
$cart = $this->dispatchNewCart($dispatcher);
}
$cartRestoreEvent->setCart($cart);
} | [
"public",
"function",
"restoreCurrentCart",
"(",
"CartRestoreEvent",
"$",
"cartRestoreEvent",
",",
"$",
"eventName",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"cookieName",
"=",
"ConfigQuery",
"::",
"read",
"(",
"\"cart.cookie_name\"",
",",
... | Search if cart already exists in session. If not try to restore it from the cart cookie,
or duplicate an old one.
@param CartRestoreEvent $cartRestoreEvent
@param $eventName
@param EventDispatcherInterface $dispatcher | [
"Search",
"if",
"cart",
"already",
"exists",
"in",
"session",
".",
"If",
"not",
"try",
"to",
"restore",
"it",
"from",
"the",
"cart",
"cookie",
"or",
"duplicate",
"an",
"old",
"one",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L329-L348 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.manageNonPersistentCookie | protected function manageNonPersistentCookie(CartRestoreEvent $cartRestoreEvent, EventDispatcherInterface $dispatcher)
{
$cart = $cartRestoreEvent->getCart();
if (null === $cart) {
$cart = $this->dispatchNewCart($dispatcher);
} else {
$cart = $this->manageCartDuplicationAtCustomerLogin($cart, $dispatcher);
}
return $cart;
} | php | protected function manageNonPersistentCookie(CartRestoreEvent $cartRestoreEvent, EventDispatcherInterface $dispatcher)
{
$cart = $cartRestoreEvent->getCart();
if (null === $cart) {
$cart = $this->dispatchNewCart($dispatcher);
} else {
$cart = $this->manageCartDuplicationAtCustomerLogin($cart, $dispatcher);
}
return $cart;
} | [
"protected",
"function",
"manageNonPersistentCookie",
"(",
"CartRestoreEvent",
"$",
"cartRestoreEvent",
",",
"EventDispatcherInterface",
"$",
"dispatcher",
")",
"{",
"$",
"cart",
"=",
"$",
"cartRestoreEvent",
"->",
"getCart",
"(",
")",
";",
"if",
"(",
"null",
"===... | The cart token is not saved in a cookie, if the cart is present in session, we just change the customer id
if needed or create duplicate the current cart if the customer is not the same as customer already present in
the cart.
@param CartRestoreEvent $cartRestoreEvent
@param EventDispatcherInterface $dispatcher
@return CartModel
@throws \Exception
@throws \Propel\Runtime\Exception\PropelException | [
"The",
"cart",
"token",
"is",
"not",
"saved",
"in",
"a",
"cookie",
"if",
"the",
"cart",
"is",
"present",
"in",
"session",
"we",
"just",
"change",
"the",
"customer",
"id",
"if",
"needed",
"or",
"create",
"duplicate",
"the",
"current",
"cart",
"if",
"the",... | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L361-L372 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.createEmptyCart | public function createEmptyCart(CartCreateEvent $cartCreateEvent)
{
$cart = new CartModel();
$cart->setCurrency($this->getSession()->getCurrency(true));
/** @var CustomerModel $customer */
if (null !== $customer = $this->getSession()->getCustomerUser()) {
$cart->setCustomer(CustomerQuery::create()->findPk($customer->getId()));
}
$this->getSession()->setSessionCart($cart);
if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) {
// set cart_use_cookie to "" to remove the cart cookie
// see Thelia\Core\EventListener\ResponseListener
$this->getSession()->set("cart_use_cookie", "");
}
$cartCreateEvent->setCart($cart);
} | php | public function createEmptyCart(CartCreateEvent $cartCreateEvent)
{
$cart = new CartModel();
$cart->setCurrency($this->getSession()->getCurrency(true));
/** @var CustomerModel $customer */
if (null !== $customer = $this->getSession()->getCustomerUser()) {
$cart->setCustomer(CustomerQuery::create()->findPk($customer->getId()));
}
$this->getSession()->setSessionCart($cart);
if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) {
// set cart_use_cookie to "" to remove the cart cookie
// see Thelia\Core\EventListener\ResponseListener
$this->getSession()->set("cart_use_cookie", "");
}
$cartCreateEvent->setCart($cart);
} | [
"public",
"function",
"createEmptyCart",
"(",
"CartCreateEvent",
"$",
"cartCreateEvent",
")",
"{",
"$",
"cart",
"=",
"new",
"CartModel",
"(",
")",
";",
"$",
"cart",
"->",
"setCurrency",
"(",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"getCurrency",
"... | Create a new, empty cart object, and assign it to the current customer, if any.
@param CartCreateEvent $cartCreateEvent | [
"Create",
"a",
"new",
"empty",
"cart",
"object",
"and",
"assign",
"it",
"to",
"the",
"current",
"customer",
"if",
"any",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L456-L476 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.duplicateCart | protected function duplicateCart(EventDispatcherInterface $dispatcher, CartModel $cart, CustomerModel $customer = null)
{
$newCart = $cart->duplicate(
$this->generateCartCookieIdentifier(),
$customer,
$this->getSession()->getCurrency(),
$dispatcher
);
$cartEvent = new CartDuplicationEvent($newCart, $cart);
$dispatcher->dispatch(TheliaEvents::CART_DUPLICATE, $cartEvent);
return $cartEvent->getDuplicatedCart();
} | php | protected function duplicateCart(EventDispatcherInterface $dispatcher, CartModel $cart, CustomerModel $customer = null)
{
$newCart = $cart->duplicate(
$this->generateCartCookieIdentifier(),
$customer,
$this->getSession()->getCurrency(),
$dispatcher
);
$cartEvent = new CartDuplicationEvent($newCart, $cart);
$dispatcher->dispatch(TheliaEvents::CART_DUPLICATE, $cartEvent);
return $cartEvent->getDuplicatedCart();
} | [
"protected",
"function",
"duplicateCart",
"(",
"EventDispatcherInterface",
"$",
"dispatcher",
",",
"CartModel",
"$",
"cart",
",",
"CustomerModel",
"$",
"customer",
"=",
"null",
")",
"{",
"$",
"newCart",
"=",
"$",
"cart",
"->",
"duplicate",
"(",
"$",
"this",
... | Duplicate an existing Cart. If a customer ID is provided the created cart will be attached to this customer.
@param EventDispatcherInterface $dispatcher
@param CartModel $cart
@param CustomerModel $customer
@return CartModel | [
"Duplicate",
"an",
"existing",
"Cart",
".",
"If",
"a",
"customer",
"ID",
"is",
"provided",
"the",
"created",
"cart",
"will",
"be",
"attached",
"to",
"this",
"customer",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L486-L499 | train |
thelia/core | lib/Thelia/Action/Cart.php | Cart.generateCartCookieIdentifier | protected function generateCartCookieIdentifier()
{
$id = null;
if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) {
$id = $this->tokenProvider->getToken();
$this->getSession()->set('cart_use_cookie', $id);
}
return $id;
} | php | protected function generateCartCookieIdentifier()
{
$id = null;
if (ConfigQuery::read("cart.use_persistent_cookie", 1) == 1) {
$id = $this->tokenProvider->getToken();
$this->getSession()->set('cart_use_cookie', $id);
}
return $id;
} | [
"protected",
"function",
"generateCartCookieIdentifier",
"(",
")",
"{",
"$",
"id",
"=",
"null",
";",
"if",
"(",
"ConfigQuery",
"::",
"read",
"(",
"\"cart.use_persistent_cookie\"",
",",
"1",
")",
"==",
"1",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"to... | Generate the cart cookie identifier, or return null if the cart is only managed in the session object,
not in a client cookie.
@return string | [
"Generate",
"the",
"cart",
"cookie",
"identifier",
"or",
"return",
"null",
"if",
"the",
"cart",
"is",
"only",
"managed",
"in",
"the",
"session",
"object",
"not",
"in",
"a",
"client",
"cookie",
"."
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Action/Cart.php#L507-L517 | train |
thelia/core | lib/Thelia/Model/Content.php | Content.addCriteriaToPositionQuery | protected function addCriteriaToPositionQuery($query)
{
$contents = ContentFolderQuery::create()
->filterByFolderId($this->getDefaultFolderId())
->filterByDefaultFolder(true)
->select('content_id')
->find();
// Filtrer la requete sur ces produits
if ($contents != null) {
$query->filterById($contents, Criteria::IN);
}
} | php | protected function addCriteriaToPositionQuery($query)
{
$contents = ContentFolderQuery::create()
->filterByFolderId($this->getDefaultFolderId())
->filterByDefaultFolder(true)
->select('content_id')
->find();
// Filtrer la requete sur ces produits
if ($contents != null) {
$query->filterById($contents, Criteria::IN);
}
} | [
"protected",
"function",
"addCriteriaToPositionQuery",
"(",
"$",
"query",
")",
"{",
"$",
"contents",
"=",
"ContentFolderQuery",
"::",
"create",
"(",
")",
"->",
"filterByFolderId",
"(",
"$",
"this",
"->",
"getDefaultFolderId",
"(",
")",
")",
"->",
"filterByDefaul... | Calculate next position relative to our parent
@param ContentQuery $query
@deprecated since 2.3, and will be removed in 2.4 | [
"Calculate",
"next",
"position",
"relative",
"to",
"our",
"parent"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Model/Content.php#L40-L52 | train |
thelia/core | lib/Thelia/Install/Update.php | Update.getDatabasePDO | protected function getDatabasePDO()
{
$configPath = THELIA_CONF_DIR . "database.yml";
if (!file_exists($configPath)) {
throw new UpdateException("Thelia is not installed yet");
}
$definePropel = new DatabaseConfigurationSource(
Yaml::parse(file_get_contents($configPath)),
$this->getEnvParameters()
);
return $definePropel->getTheliaConnectionPDO();
} | php | protected function getDatabasePDO()
{
$configPath = THELIA_CONF_DIR . "database.yml";
if (!file_exists($configPath)) {
throw new UpdateException("Thelia is not installed yet");
}
$definePropel = new DatabaseConfigurationSource(
Yaml::parse(file_get_contents($configPath)),
$this->getEnvParameters()
);
return $definePropel->getTheliaConnectionPDO();
} | [
"protected",
"function",
"getDatabasePDO",
"(",
")",
"{",
"$",
"configPath",
"=",
"THELIA_CONF_DIR",
".",
"\"database.yml\"",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"configPath",
")",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"\"Thelia is not inst... | retrieve the database connection
@return \PDO
@throws ParseException
@throws \PDOException | [
"retrieve",
"the",
"database",
"connection"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Update.php#L105-L119 | train |
thelia/core | lib/Thelia/Install/Update.php | Update.getDataBaseSize | public function getDataBaseSize()
{
$stmt = $this->connection->query(
"SELECT sum(data_length) / 1024 / 1024 'size' FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema"
);
if ($stmt->rowCount()) {
return \floatval($stmt->fetch(PDO::FETCH_OBJ)->size);
}
throw new \Exception('Impossible to calculate the database size');
} | php | public function getDataBaseSize()
{
$stmt = $this->connection->query(
"SELECT sum(data_length) / 1024 / 1024 'size' FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema"
);
if ($stmt->rowCount()) {
return \floatval($stmt->fetch(PDO::FETCH_OBJ)->size);
}
throw new \Exception('Impossible to calculate the database size');
} | [
"public",
"function",
"getDataBaseSize",
"(",
")",
"{",
"$",
"stmt",
"=",
"$",
"this",
"->",
"connection",
"->",
"query",
"(",
"\"SELECT sum(data_length) / 1024 / 1024 'size' FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema\"",
")",
";",
"if"... | Returns the database size in Mo
@return float
@throws \Exception | [
"Returns",
"the",
"database",
"size",
"in",
"Mo"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Update.php#L404-L415 | train |
thelia/core | lib/Thelia/Install/Update.php | Update.checkBackupIsPossible | public function checkBackupIsPossible()
{
$size = 0;
if (preg_match('/^(\d+)(.)$/', ini_get('memory_limit'), $matches)) {
switch (strtolower($matches[2])) {
case 'k':
$size = $matches[1] / 1024;
break;
case 'm':
$size = $matches[1];
break;
case 'g':
$size = $matches[1] * 1024;
break;
}
}
if ($this->getDataBaseSize() > ($size - 64) / 8) {
return false;
}
return true;
} | php | public function checkBackupIsPossible()
{
$size = 0;
if (preg_match('/^(\d+)(.)$/', ini_get('memory_limit'), $matches)) {
switch (strtolower($matches[2])) {
case 'k':
$size = $matches[1] / 1024;
break;
case 'm':
$size = $matches[1];
break;
case 'g':
$size = $matches[1] * 1024;
break;
}
}
if ($this->getDataBaseSize() > ($size - 64) / 8) {
return false;
}
return true;
} | [
"public",
"function",
"checkBackupIsPossible",
"(",
")",
"{",
"$",
"size",
"=",
"0",
";",
"if",
"(",
"preg_match",
"(",
"'/^(\\d+)(.)$/'",
",",
"ini_get",
"(",
"'memory_limit'",
")",
",",
"$",
"matches",
")",
")",
"{",
"switch",
"(",
"strtolower",
"(",
"... | Checks whether it is possible to make a data base backup
@return bool | [
"Checks",
"whether",
"it",
"is",
"possible",
"to",
"make",
"a",
"data",
"base",
"backup"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Update.php#L423-L445 | train |
thelia/core | lib/Thelia/Install/Update.php | Update.addPostInstructions | protected function addPostInstructions($version, $instructions)
{
if (!isset($this->postInstructions[$version])) {
$this->postInstructions[$version] = [];
}
$this->postInstructions[$version][] = $instructions;
} | php | protected function addPostInstructions($version, $instructions)
{
if (!isset($this->postInstructions[$version])) {
$this->postInstructions[$version] = [];
}
$this->postInstructions[$version][] = $instructions;
} | [
"protected",
"function",
"addPostInstructions",
"(",
"$",
"version",
",",
"$",
"instructions",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"postInstructions",
"[",
"$",
"version",
"]",
")",
")",
"{",
"$",
"this",
"->",
"postInstructions",
... | Add a new post update instruction
@param string $instructions content of the instruction un markdown format | [
"Add",
"a",
"new",
"post",
"update",
"instruction"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Update.php#L478-L485 | train |
thelia/core | lib/Thelia/Install/Update.php | Update.getPostInstructions | public function getPostInstructions($format = 'plain')
{
$content = [];
if (\count($this->postInstructions) == 0) {
return null;
}
ksort($this->postInstructions);
foreach ($this->postInstructions as $version => $instructions) {
$content[] = sprintf("## %s", $version);
foreach ($instructions as $instruction) {
$content[] = sprintf("%s", $instruction);
}
}
$content = implode("\n\n", $content);
if ($format === 'html') {
$content = Markdown::defaultTransform($content);
}
return $content;
} | php | public function getPostInstructions($format = 'plain')
{
$content = [];
if (\count($this->postInstructions) == 0) {
return null;
}
ksort($this->postInstructions);
foreach ($this->postInstructions as $version => $instructions) {
$content[] = sprintf("## %s", $version);
foreach ($instructions as $instruction) {
$content[] = sprintf("%s", $instruction);
}
}
$content = implode("\n\n", $content);
if ($format === 'html') {
$content = Markdown::defaultTransform($content);
}
return $content;
} | [
"public",
"function",
"getPostInstructions",
"(",
"$",
"format",
"=",
"'plain'",
")",
"{",
"$",
"content",
"=",
"[",
"]",
";",
"if",
"(",
"\\",
"count",
"(",
"$",
"this",
"->",
"postInstructions",
")",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",... | Return the content of all instructions
@param string $format the format of the export : plain (default) or html
@return string the instructions in plain text or html | [
"Return",
"the",
"content",
"of",
"all",
"instructions"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Install/Update.php#L493-L517 | train |
thelia/core | lib/Thelia/Command/Install.php | Install.checkPermission | protected function checkPermission(OutputInterface $output)
{
$output->writeln(array(
"Checking some permissions"
));
/** @var Translator $translator */
$translator = $this->getContainer()->get('thelia.translator');
$permissions = new CheckPermission(false, $translator);
$isValid = $permissions->exec();
foreach ($permissions->getValidationMessages() as $item => $data) {
if ($data['status']) {
$output->writeln(
array(
sprintf(
"<info>%s ...</info> %s",
$data['text'],
"<info>Ok</info>"
)
)
);
} else {
$output->writeln(array(
sprintf(
"<error>%s </error>%s",
$data['text'],
sprintf("<error>%s</error>", $data["hint"])
)
));
}
}
if (false === $isValid) {
throw new \RuntimeException('Please put correct permissions and reload install process');
}
} | php | protected function checkPermission(OutputInterface $output)
{
$output->writeln(array(
"Checking some permissions"
));
/** @var Translator $translator */
$translator = $this->getContainer()->get('thelia.translator');
$permissions = new CheckPermission(false, $translator);
$isValid = $permissions->exec();
foreach ($permissions->getValidationMessages() as $item => $data) {
if ($data['status']) {
$output->writeln(
array(
sprintf(
"<info>%s ...</info> %s",
$data['text'],
"<info>Ok</info>"
)
)
);
} else {
$output->writeln(array(
sprintf(
"<error>%s </error>%s",
$data['text'],
sprintf("<error>%s</error>", $data["hint"])
)
));
}
}
if (false === $isValid) {
throw new \RuntimeException('Please put correct permissions and reload install process');
}
} | [
"protected",
"function",
"checkPermission",
"(",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"output",
"->",
"writeln",
"(",
"array",
"(",
"\"Checking some permissions\"",
")",
")",
";",
"/** @var Translator $translator */",
"$",
"translator",
"=",
"$",
"this",... | Test if needed directories have write permission
@param \Symfony\Component\Console\Output\OutputInterface $output | [
"Test",
"if",
"needed",
"directories",
"have",
"write",
"permission"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Command/Install.php#L145-L182 | train |
thelia/core | lib/Thelia/Command/Install.php | Install.createConfigFile | protected function createConfigFile($connectionInfo)
{
$fs = new Filesystem();
$sampleConfigFile = THELIA_CONF_DIR . "database.yml.sample";
$configFile = THELIA_CONF_DIR . "database.yml";
$fs->copy($sampleConfigFile, $configFile, true);
$configContent = file_get_contents($configFile);
$configContent = str_replace("%DRIVER%", "mysql", $configContent);
$configContent = str_replace("%USERNAME%", $connectionInfo["username"], $configContent);
$configContent = str_replace("%PASSWORD%", $connectionInfo["password"], $configContent);
$configContent = str_replace(
"%DSN%",
sprintf("mysql:host=%s;dbname=%s;port=%s", $connectionInfo["host"], $connectionInfo["dbName"], $connectionInfo['port']),
$configContent
);
file_put_contents($configFile, $configContent);
$fs->remove($this->getContainer()->getParameter("kernel.cache_dir"));
} | php | protected function createConfigFile($connectionInfo)
{
$fs = new Filesystem();
$sampleConfigFile = THELIA_CONF_DIR . "database.yml.sample";
$configFile = THELIA_CONF_DIR . "database.yml";
$fs->copy($sampleConfigFile, $configFile, true);
$configContent = file_get_contents($configFile);
$configContent = str_replace("%DRIVER%", "mysql", $configContent);
$configContent = str_replace("%USERNAME%", $connectionInfo["username"], $configContent);
$configContent = str_replace("%PASSWORD%", $connectionInfo["password"], $configContent);
$configContent = str_replace(
"%DSN%",
sprintf("mysql:host=%s;dbname=%s;port=%s", $connectionInfo["host"], $connectionInfo["dbName"], $connectionInfo['port']),
$configContent
);
file_put_contents($configFile, $configContent);
$fs->remove($this->getContainer()->getParameter("kernel.cache_dir"));
} | [
"protected",
"function",
"createConfigFile",
"(",
"$",
"connectionInfo",
")",
"{",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"sampleConfigFile",
"=",
"THELIA_CONF_DIR",
".",
"\"database.yml.sample\"",
";",
"$",
"configFile",
"=",
"THELIA_CONF_DIR",
... | rename database config file and complete it
@param array $connectionInfo | [
"rename",
"database",
"config",
"file",
"and",
"complete",
"it"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Command/Install.php#L189-L212 | train |
thelia/core | lib/Thelia/Command/Install.php | Install.tryConnection | protected function tryConnection($connectionInfo, OutputInterface $output)
{
if (\is_null($connectionInfo["dbName"])) {
return false;
}
$dsn = "mysql:host=%s;port=%s";
try {
$connection = new \PDO(
sprintf($dsn, $connectionInfo["host"], $connectionInfo["port"]),
$connectionInfo["username"],
$connectionInfo["password"]
);
$connection->query('SET NAMES \'UTF8\'');
} catch (\PDOException $e) {
$output->writeln(array(
"<error>Wrong connection information</error>"
));
return false;
}
return $connection;
} | php | protected function tryConnection($connectionInfo, OutputInterface $output)
{
if (\is_null($connectionInfo["dbName"])) {
return false;
}
$dsn = "mysql:host=%s;port=%s";
try {
$connection = new \PDO(
sprintf($dsn, $connectionInfo["host"], $connectionInfo["port"]),
$connectionInfo["username"],
$connectionInfo["password"]
);
$connection->query('SET NAMES \'UTF8\'');
} catch (\PDOException $e) {
$output->writeln(array(
"<error>Wrong connection information</error>"
));
return false;
}
return $connection;
} | [
"protected",
"function",
"tryConnection",
"(",
"$",
"connectionInfo",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"if",
"(",
"\\",
"is_null",
"(",
"$",
"connectionInfo",
"[",
"\"dbName\"",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"dsn",
... | test database access
@param $connectionInfo
@param OutputInterface $output
@return bool|\PDO | [
"test",
"database",
"access"
] | 38fbe7d5046bad6c0af9ea7c686b4655e8d84e67 | https://github.com/thelia/core/blob/38fbe7d5046bad6c0af9ea7c686b4655e8d84e67/lib/Thelia/Command/Install.php#L221-L245 | train |
BoldGrid/library | src/Util/Version.php | Version.setVersion | public function setVersion() {
$wp_filesystem = self::getWpFilesystem();
// Get installed composer package data.
$installedFile = wp_normalize_path( realpath( __DIR__ . '/../../../../' ) ) . '/composer/installed.json';
if ( 'direct' === get_filesystem_method() ) {
$file = $wp_filesystem->get_contents( $installedFile );
} else {
$installedUrl = str_replace( ABSPATH, get_site_url() . '/', $installedFile );
$file = wp_remote_retrieve_body( wp_remote_get( $installedUrl ) );
}
$installed = json_decode( $file, true );
// Check for dep's installed version.
$version = null;
if ( $installed ) {
foreach( $installed as $key => $value ) {
if ( $value['name'] === $this->getDependency() ) {
$version = $value['version_normalized'];
break;
}
}
}
return $version;
} | php | public function setVersion() {
$wp_filesystem = self::getWpFilesystem();
// Get installed composer package data.
$installedFile = wp_normalize_path( realpath( __DIR__ . '/../../../../' ) ) . '/composer/installed.json';
if ( 'direct' === get_filesystem_method() ) {
$file = $wp_filesystem->get_contents( $installedFile );
} else {
$installedUrl = str_replace( ABSPATH, get_site_url() . '/', $installedFile );
$file = wp_remote_retrieve_body( wp_remote_get( $installedUrl ) );
}
$installed = json_decode( $file, true );
// Check for dep's installed version.
$version = null;
if ( $installed ) {
foreach( $installed as $key => $value ) {
if ( $value['name'] === $this->getDependency() ) {
$version = $value['version_normalized'];
break;
}
}
}
return $version;
} | [
"public",
"function",
"setVersion",
"(",
")",
"{",
"$",
"wp_filesystem",
"=",
"self",
"::",
"getWpFilesystem",
"(",
")",
";",
"// Get installed composer package data.",
"$",
"installedFile",
"=",
"wp_normalize_path",
"(",
"realpath",
"(",
"__DIR__",
".",
"'/../../..... | Sets the version of dependency.
@since 1.0.0
@return mixed $version Normalized version number if found or null. | [
"Sets",
"the",
"version",
"of",
"dependency",
"."
] | 51afe070e211cff9cf78454ff97912a0d943805c | https://github.com/BoldGrid/library/blob/51afe070e211cff9cf78454ff97912a0d943805c/src/Util/Version.php#L56-L83 | train |
QoboLtd/cakephp-utils | src/ModuleConfig/ClassFactory.php | ClassFactory.create | public static function create(string $configType, ClassType $classType, array $options = [])
{
$classType = (string)$classType;
$classMapVersion = empty($options['classMapVersion']) ? Configure::read('ModuleConfig.classMapVersion') : (string)$options['classMapVersion'];
$classMap = empty($options['classMap'][$classMapVersion]) ? Configure::read('ModuleConfig.classMap.' . $classMapVersion) : (array)$options['classMap'][$classMapVersion];
if (empty($classMap[$configType][$classType])) {
throw new InvalidArgumentException("No [$classType] found for configuration type [$configType] in class map version [$classMapVersion]");
}
$className = $classMap[$configType][$classType];
$params = $options['classArgs'] ?? [];
$result = static::getInstance($className, $params);
return $result;
} | php | public static function create(string $configType, ClassType $classType, array $options = [])
{
$classType = (string)$classType;
$classMapVersion = empty($options['classMapVersion']) ? Configure::read('ModuleConfig.classMapVersion') : (string)$options['classMapVersion'];
$classMap = empty($options['classMap'][$classMapVersion]) ? Configure::read('ModuleConfig.classMap.' . $classMapVersion) : (array)$options['classMap'][$classMapVersion];
if (empty($classMap[$configType][$classType])) {
throw new InvalidArgumentException("No [$classType] found for configuration type [$configType] in class map version [$classMapVersion]");
}
$className = $classMap[$configType][$classType];
$params = $options['classArgs'] ?? [];
$result = static::getInstance($className, $params);
return $result;
} | [
"public",
"static",
"function",
"create",
"(",
"string",
"$",
"configType",
",",
"ClassType",
"$",
"classType",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"classType",
"=",
"(",
"string",
")",
"$",
"classType",
";",
"$",
"classMapVersion... | Create a new instance of a helper class
Options:
- classArgs: array of class arguments which will be passed to the constructor.
@throws \InvalidArgumentException when cannot create instance
@param string $configType Configuration type
@param \Qobo\Utils\ModuleConfig\ClassType $classType Class type
@param mixed[] $options Options
@return object | [
"Create",
"a",
"new",
"instance",
"of",
"a",
"helper",
"class"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/ModuleConfig/ClassFactory.php#L42-L57 | train |
QoboLtd/cakephp-utils | src/ModuleConfig/ClassFactory.php | ClassFactory.getInstance | public static function getInstance(string $class, array $params = [])
{
if (!class_exists($class)) {
throw new InvalidArgumentException("Class [$class] does not exist");
}
if (empty($params)) {
return new $class;
}
$reflection = new ReflectionClass($class);
return $reflection->newInstanceArgs($params);
} | php | public static function getInstance(string $class, array $params = [])
{
if (!class_exists($class)) {
throw new InvalidArgumentException("Class [$class] does not exist");
}
if (empty($params)) {
return new $class;
}
$reflection = new ReflectionClass($class);
return $reflection->newInstanceArgs($params);
} | [
"public",
"static",
"function",
"getInstance",
"(",
"string",
"$",
"class",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Class ... | Get an instance of a given class
This method is public because it is useful in a variety of
situations, not just for the factory via class map.
@throws \InvalidArgumentException when cannot create instance
@param string $class Class name to instantiate
@param mixed[] $params Optional parameters to the class
@return object | [
"Get",
"an",
"instance",
"of",
"a",
"given",
"class"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/ModuleConfig/ClassFactory.php#L106-L119 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.includeLanguageJavaScriptFiles | public function includeLanguageJavaScriptFiles()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath('locale-' . ContextService::get()->getLanguageKey()) . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return $this->getFormzLocalizationJavaScriptAssetHandler()
->injectTranslationsForFormFieldsValidation()
->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | php | public function includeLanguageJavaScriptFiles()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath('locale-' . ContextService::get()->getLanguageKey()) . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return $this->getFormzLocalizationJavaScriptAssetHandler()
->injectTranslationsForFormFieldsValidation()
->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | [
"public",
"function",
"includeLanguageJavaScriptFiles",
"(",
")",
"{",
"$",
"filePath",
"=",
"$",
"this",
"->",
"assetHandlerConnectorManager",
"->",
"getFormzGeneratedFilePath",
"(",
"'locale-'",
".",
"ContextService",
"::",
"get",
"(",
")",
"->",
"getLanguageKey",
... | This function will handle the JavaScript language files.
A file will be created for the current language (there can be as many
files as languages), containing the translations handling for JavaScript.
If the file already exists, it is directly included.
@return $this | [
"This",
"function",
"will",
"handle",
"the",
"JavaScript",
"language",
"files",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L113-L129 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.generateAndIncludeFormzConfigurationJavaScript | public function generateAndIncludeFormzConfigurationJavaScript()
{
$formzConfigurationJavaScriptAssetHandler = $this->getFormzConfigurationJavaScriptAssetHandler();
$fileName = $formzConfigurationJavaScriptAssetHandler->getJavaScriptFileName();
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$fileName,
function () use ($formzConfigurationJavaScriptAssetHandler) {
return $formzConfigurationJavaScriptAssetHandler->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($fileName));
return $this;
} | php | public function generateAndIncludeFormzConfigurationJavaScript()
{
$formzConfigurationJavaScriptAssetHandler = $this->getFormzConfigurationJavaScriptAssetHandler();
$fileName = $formzConfigurationJavaScriptAssetHandler->getJavaScriptFileName();
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$fileName,
function () use ($formzConfigurationJavaScriptAssetHandler) {
return $formzConfigurationJavaScriptAssetHandler->getJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($fileName));
return $this;
} | [
"public",
"function",
"generateAndIncludeFormzConfigurationJavaScript",
"(",
")",
"{",
"$",
"formzConfigurationJavaScriptAssetHandler",
"=",
"$",
"this",
"->",
"getFormzConfigurationJavaScriptAssetHandler",
"(",
")",
";",
"$",
"fileName",
"=",
"$",
"formzConfigurationJavaScri... | Includes FormZ configuration JavaScript declaration. If the file exists,
it is directly included, otherwise the JavaScript code is calculated,
then put in the cache file.
@return $this | [
"Includes",
"FormZ",
"configuration",
"JavaScript",
"declaration",
".",
"If",
"the",
"file",
"exists",
"it",
"is",
"directly",
"included",
"otherwise",
"the",
"JavaScript",
"code",
"is",
"calculated",
"then",
"put",
"in",
"the",
"cache",
"file",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L138-L153 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.generateAndIncludeJavaScript | public function generateAndIncludeJavaScript()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath() . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return
// Form initialization code.
$this->getFormInitializationJavaScriptAssetHandler()
->getFormInitializationJavaScriptCode() .
LF .
// Fields validation code.
$this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptCode() .
LF .
// Fields activation conditions code.
$this->getFieldsActivationJavaScriptAssetHandler()
->getFieldsActivationJavaScriptCode() .
LF .
// Fields validation activation conditions code.
$this->getFieldsValidationActivationJavaScriptAssetHandler()
->getFieldsValidationActivationJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | php | public function generateAndIncludeJavaScript()
{
$filePath = $this->assetHandlerConnectorManager->getFormzGeneratedFilePath() . '.js';
$this->assetHandlerConnectorManager->createFileInTemporaryDirectory(
$filePath,
function () {
return
// Form initialization code.
$this->getFormInitializationJavaScriptAssetHandler()
->getFormInitializationJavaScriptCode() .
LF .
// Fields validation code.
$this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptCode() .
LF .
// Fields activation conditions code.
$this->getFieldsActivationJavaScriptAssetHandler()
->getFieldsActivationJavaScriptCode() .
LF .
// Fields validation activation conditions code.
$this->getFieldsValidationActivationJavaScriptAssetHandler()
->getFieldsValidationActivationJavaScriptCode();
}
);
$this->includeJsFile(StringService::get()->getResourceRelativePath($filePath));
return $this;
} | [
"public",
"function",
"generateAndIncludeJavaScript",
"(",
")",
"{",
"$",
"filePath",
"=",
"$",
"this",
"->",
"assetHandlerConnectorManager",
"->",
"getFormzGeneratedFilePath",
"(",
")",
".",
"'.js'",
";",
"$",
"this",
"->",
"assetHandlerConnectorManager",
"->",
"cr... | Will include the generated JavaScript, from multiple asset handlers
sources.
@return $this | [
"Will",
"include",
"the",
"generated",
"JavaScript",
"from",
"multiple",
"asset",
"handlers",
"sources",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L161-L190 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.generateAndIncludeInlineJavaScript | public function generateAndIncludeInlineJavaScript()
{
$formName = $this->assetHandlerFactory->getFormObject()->getName();
$javaScriptCode = $this->getFormRequestDataJavaScriptAssetHandler()
->getFormRequestDataJavaScriptCode();
if (ExtensionService::get()->isInDebugMode()) {
$javaScriptCode .= LF . $this->getDebugActivationCode();
}
$uri = $this->getAjaxUrl();
$javaScriptCode .= LF;
$javaScriptCode .= <<<JS
Fz.setAjaxUrl('$uri');
JS;
$this->addInlineJs('FormZ - Initialization ' . $formName, $javaScriptCode);
return $this;
} | php | public function generateAndIncludeInlineJavaScript()
{
$formName = $this->assetHandlerFactory->getFormObject()->getName();
$javaScriptCode = $this->getFormRequestDataJavaScriptAssetHandler()
->getFormRequestDataJavaScriptCode();
if (ExtensionService::get()->isInDebugMode()) {
$javaScriptCode .= LF . $this->getDebugActivationCode();
}
$uri = $this->getAjaxUrl();
$javaScriptCode .= LF;
$javaScriptCode .= <<<JS
Fz.setAjaxUrl('$uri');
JS;
$this->addInlineJs('FormZ - Initialization ' . $formName, $javaScriptCode);
return $this;
} | [
"public",
"function",
"generateAndIncludeInlineJavaScript",
"(",
")",
"{",
"$",
"formName",
"=",
"$",
"this",
"->",
"assetHandlerFactory",
"->",
"getFormObject",
"(",
")",
"->",
"getName",
"(",
")",
";",
"$",
"javaScriptCode",
"=",
"$",
"this",
"->",
"getFormR... | Here we generate the JavaScript code containing the submitted values, and
the existing errors, which is dynamically created at each request.
The code is then injected as inline code in the DOM.
@return $this | [
"Here",
"we",
"generate",
"the",
"JavaScript",
"code",
"containing",
"the",
"submitted",
"values",
"and",
"the",
"existing",
"errors",
"which",
"is",
"dynamically",
"created",
"at",
"each",
"request",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L200-L221 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.includeJavaScriptValidationAndConditionFiles | public function includeJavaScriptValidationAndConditionFiles()
{
$javaScriptValidationFiles = $this->getJavaScriptFiles();
$assetHandlerConnectorStates = $this->assetHandlerConnectorManager
->getAssetHandlerConnectorStates();
foreach ($javaScriptValidationFiles as $file) {
if (false === in_array($file, $assetHandlerConnectorStates->getAlreadyIncludedValidationJavaScriptFiles())) {
$assetHandlerConnectorStates->registerIncludedValidationJavaScriptFiles($file);
$this->includeJsFile(StringService::get()->getResourceRelativePath($file));
}
}
return $this;
} | php | public function includeJavaScriptValidationAndConditionFiles()
{
$javaScriptValidationFiles = $this->getJavaScriptFiles();
$assetHandlerConnectorStates = $this->assetHandlerConnectorManager
->getAssetHandlerConnectorStates();
foreach ($javaScriptValidationFiles as $file) {
if (false === in_array($file, $assetHandlerConnectorStates->getAlreadyIncludedValidationJavaScriptFiles())) {
$assetHandlerConnectorStates->registerIncludedValidationJavaScriptFiles($file);
$this->includeJsFile(StringService::get()->getResourceRelativePath($file));
}
}
return $this;
} | [
"public",
"function",
"includeJavaScriptValidationAndConditionFiles",
"(",
")",
"{",
"$",
"javaScriptValidationFiles",
"=",
"$",
"this",
"->",
"getJavaScriptFiles",
"(",
")",
";",
"$",
"assetHandlerConnectorStates",
"=",
"$",
"this",
"->",
"assetHandlerConnectorManager",
... | Will include all new JavaScript files given, by checking that every given
file was not already included.
@return $this | [
"Will",
"include",
"all",
"new",
"JavaScript",
"files",
"given",
"by",
"checking",
"that",
"every",
"given",
"file",
"was",
"not",
"already",
"included",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L229-L243 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.getJavaScriptFiles | protected function getJavaScriptFiles()
{
$formObject = $this->assetHandlerFactory->getFormObject();
$javaScriptFiles = $this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptValidationFiles();
$conditionProcessor = $this->getConditionProcessor($formObject);
$javaScriptFiles = array_merge($javaScriptFiles, $conditionProcessor->getJavaScriptFiles());
return $javaScriptFiles;
} | php | protected function getJavaScriptFiles()
{
$formObject = $this->assetHandlerFactory->getFormObject();
$javaScriptFiles = $this->getFieldsValidationJavaScriptAssetHandler()
->getJavaScriptValidationFiles();
$conditionProcessor = $this->getConditionProcessor($formObject);
$javaScriptFiles = array_merge($javaScriptFiles, $conditionProcessor->getJavaScriptFiles());
return $javaScriptFiles;
} | [
"protected",
"function",
"getJavaScriptFiles",
"(",
")",
"{",
"$",
"formObject",
"=",
"$",
"this",
"->",
"assetHandlerFactory",
"->",
"getFormObject",
"(",
")",
";",
"$",
"javaScriptFiles",
"=",
"$",
"this",
"->",
"getFieldsValidationJavaScriptAssetHandler",
"(",
... | Returns the list of JavaScript files which are used for the current form
object.
@return array | [
"Returns",
"the",
"list",
"of",
"JavaScript",
"files",
"which",
"are",
"used",
"for",
"the",
"current",
"form",
"object",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L251-L263 | train |
romm/formz | Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php | JavaScriptAssetHandlerConnector.includeJsFile | protected function includeJsFile($path)
{
$pageRenderer = $this->assetHandlerConnectorManager->getPageRenderer();
if ($this->environmentService->isEnvironmentInFrontendMode()) {
$pageRenderer->addJsFooterFile($path);
} else {
$pageRenderer->addJsFile($path);
}
} | php | protected function includeJsFile($path)
{
$pageRenderer = $this->assetHandlerConnectorManager->getPageRenderer();
if ($this->environmentService->isEnvironmentInFrontendMode()) {
$pageRenderer->addJsFooterFile($path);
} else {
$pageRenderer->addJsFile($path);
}
} | [
"protected",
"function",
"includeJsFile",
"(",
"$",
"path",
")",
"{",
"$",
"pageRenderer",
"=",
"$",
"this",
"->",
"assetHandlerConnectorManager",
"->",
"getPageRenderer",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"environmentService",
"->",
"isEnvironmentInF... | We need an abstraction function because the footer inclusion for assets
does not work in backend. It means we include every JavaScript asset in
the header when the request is in a backend context.
@see https://forge.typo3.org/issues/60213
@param string $path | [
"We",
"need",
"an",
"abstraction",
"function",
"because",
"the",
"footer",
"inclusion",
"for",
"assets",
"does",
"not",
"work",
"in",
"backend",
".",
"It",
"means",
"we",
"include",
"every",
"JavaScript",
"asset",
"in",
"the",
"header",
"when",
"the",
"reque... | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/AssetHandler/Connector/JavaScriptAssetHandlerConnector.php#L274-L283 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.validatePath | public static function validatePath(string $path = null): void
{
if (empty($path)) {
throw new InvalidArgumentException("Cannot validate empty path");
}
if (!file_exists($path)) {
throw new InvalidArgumentException("Path does not exist [$path]");
}
if (!is_readable($path)) {
throw new InvalidArgumentException("Path is not readable [$path]");
}
} | php | public static function validatePath(string $path = null): void
{
if (empty($path)) {
throw new InvalidArgumentException("Cannot validate empty path");
}
if (!file_exists($path)) {
throw new InvalidArgumentException("Path does not exist [$path]");
}
if (!is_readable($path)) {
throw new InvalidArgumentException("Path is not readable [$path]");
}
} | [
"public",
"static",
"function",
"validatePath",
"(",
"string",
"$",
"path",
"=",
"null",
")",
":",
"void",
"{",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"\"Cannot validate empty path\"",
")",
";",
... | Check validity of the given path
@throws \InvalidArgumentException when path does not exist or is not readable
@param string $path Path to validate
@return void | [
"Check",
"validity",
"of",
"the",
"given",
"path"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L35-L47 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getControllers | public static function getControllers(bool $includePlugins = true): array
{
// get application controllers
$result = static::getDirControllers(APP . 'Controller' . DS);
if ($includePlugins === false) {
return $result;
}
$plugins = Plugin::loaded();
if (!is_array($plugins)) {
return $result;
}
// get plugins controllers
foreach ($plugins as $plugin) {
$path = Plugin::path($plugin) . 'src' . DS . 'Controller' . DS;
$result = array_merge($result, static::getDirControllers($path, $plugin));
}
return $result;
} | php | public static function getControllers(bool $includePlugins = true): array
{
// get application controllers
$result = static::getDirControllers(APP . 'Controller' . DS);
if ($includePlugins === false) {
return $result;
}
$plugins = Plugin::loaded();
if (!is_array($plugins)) {
return $result;
}
// get plugins controllers
foreach ($plugins as $plugin) {
$path = Plugin::path($plugin) . 'src' . DS . 'Controller' . DS;
$result = array_merge($result, static::getDirControllers($path, $plugin));
}
return $result;
} | [
"public",
"static",
"function",
"getControllers",
"(",
"bool",
"$",
"includePlugins",
"=",
"true",
")",
":",
"array",
"{",
"// get application controllers",
"$",
"result",
"=",
"static",
"::",
"getDirControllers",
"(",
"APP",
".",
"'Controller'",
".",
"DS",
")",... | Method that returns all controller names.
@param bool $includePlugins Flag for including plugin controllers
@return mixed[] | [
"Method",
"that",
"returns",
"all",
"controller",
"names",
"."
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L55-L76 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getApiVersions | public static function getApiVersions(string $path = ''): array
{
$apis = [];
$apiPath = (!empty($path)) ? $path : App::path('Controller/Api')[0];
$dir = new Folder();
// get folders in Controller/Api directory
$tree = $dir->tree($apiPath, false, 'dir');
foreach ($tree as $treePath) {
if ($treePath === $apiPath) {
continue;
}
$path = str_replace($apiPath, '', $treePath);
preg_match('/V(\d+)\/V(\d+)/', $path, $matches);
if (empty($matches)) {
continue;
}
unset($matches[0]);
$number = implode('.', $matches);
$apis[] = [
'number' => $number,
'prefix' => self::getApiRoutePrefix($matches),
'path' => self::getApiRoutePath($number),
];
}
if (!empty($apis)) {
$apis = self::sortApiVersions($apis);
}
return $apis;
} | php | public static function getApiVersions(string $path = ''): array
{
$apis = [];
$apiPath = (!empty($path)) ? $path : App::path('Controller/Api')[0];
$dir = new Folder();
// get folders in Controller/Api directory
$tree = $dir->tree($apiPath, false, 'dir');
foreach ($tree as $treePath) {
if ($treePath === $apiPath) {
continue;
}
$path = str_replace($apiPath, '', $treePath);
preg_match('/V(\d+)\/V(\d+)/', $path, $matches);
if (empty($matches)) {
continue;
}
unset($matches[0]);
$number = implode('.', $matches);
$apis[] = [
'number' => $number,
'prefix' => self::getApiRoutePrefix($matches),
'path' => self::getApiRoutePath($number),
];
}
if (!empty($apis)) {
$apis = self::sortApiVersions($apis);
}
return $apis;
} | [
"public",
"static",
"function",
"getApiVersions",
"(",
"string",
"$",
"path",
"=",
"''",
")",
":",
"array",
"{",
"$",
"apis",
"=",
"[",
"]",
";",
"$",
"apiPath",
"=",
"(",
"!",
"empty",
"(",
"$",
"path",
")",
")",
"?",
"$",
"path",
":",
"App",
... | Get Api Directory Tree with prefixes
@param string $path for setting origin directory
@return mixed[] $apis with all versioned api directories | [
"Get",
"Api",
"Directory",
"Tree",
"with",
"prefixes"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L85-L121 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getDirControllers | public static function getDirControllers(string $path, string $plugin = null, bool $fqcn = true): array
{
$result = [];
try {
static::validatePath($path);
$dir = new DirectoryIterator($path);
} catch (InvalidArgumentException $e) {
return $result;
} catch (UnexpectedValueException $e) {
return $result;
}
foreach ($dir as $fileinfo) {
// skip directories
if (!$fileinfo->isFile()) {
continue;
}
$className = $fileinfo->getBasename('.php');
// skip AppController
if ('AppController' === $className) {
continue;
}
if (!empty($plugin)) {
$className = $plugin . '.' . $className;
}
if ($fqcn) {
$className = App::className($className, 'Controller');
}
if ($className) {
$result[] = $className;
}
}
return $result;
} | php | public static function getDirControllers(string $path, string $plugin = null, bool $fqcn = true): array
{
$result = [];
try {
static::validatePath($path);
$dir = new DirectoryIterator($path);
} catch (InvalidArgumentException $e) {
return $result;
} catch (UnexpectedValueException $e) {
return $result;
}
foreach ($dir as $fileinfo) {
// skip directories
if (!$fileinfo->isFile()) {
continue;
}
$className = $fileinfo->getBasename('.php');
// skip AppController
if ('AppController' === $className) {
continue;
}
if (!empty($plugin)) {
$className = $plugin . '.' . $className;
}
if ($fqcn) {
$className = App::className($className, 'Controller');
}
if ($className) {
$result[] = $className;
}
}
return $result;
} | [
"public",
"static",
"function",
"getDirControllers",
"(",
"string",
"$",
"path",
",",
"string",
"$",
"plugin",
"=",
"null",
",",
"bool",
"$",
"fqcn",
"=",
"true",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"try",
"{",
"static",
"::",
... | Method that retrieves controller names found on the provided directory path.
@param string $path Directory path
@param string $plugin Plugin name
@param bool $fqcn Flag for using fqcn
@return mixed[] | [
"Method",
"that",
"retrieves",
"controller",
"names",
"found",
"on",
"the",
"provided",
"directory",
"path",
"."
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L131-L171 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getModels | public static function getModels(string $connectionManager = 'default', bool $excludePhinxlog = true): array
{
$result = [];
$tables = ConnectionManager::get($connectionManager)->getSchemaCollection()->listTables();
if (empty($tables)) {
return $result;
}
foreach ($tables as $table) {
if ($excludePhinxlog && preg_match('/phinxlog/', $table)) {
continue;
}
$result[$table] = Inflector::humanize($table);
}
return $result;
} | php | public static function getModels(string $connectionManager = 'default', bool $excludePhinxlog = true): array
{
$result = [];
$tables = ConnectionManager::get($connectionManager)->getSchemaCollection()->listTables();
if (empty($tables)) {
return $result;
}
foreach ($tables as $table) {
if ($excludePhinxlog && preg_match('/phinxlog/', $table)) {
continue;
}
$result[$table] = Inflector::humanize($table);
}
return $result;
} | [
"public",
"static",
"function",
"getModels",
"(",
"string",
"$",
"connectionManager",
"=",
"'default'",
",",
"bool",
"$",
"excludePhinxlog",
"=",
"true",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"tables",
"=",
"ConnectionManager",
":... | Get All Models
Fetch the list of database models escaping phinxlog
@param string $connectionManager to know which schema to fetch
@param bool $excludePhinxlog flag to exclude phinxlog tables.
@return mixed[] $result containing the list of models from database | [
"Get",
"All",
"Models"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L183-L201 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getModelColumns | public static function getModelColumns(string $model = '', string $connectionManager = 'default'): array
{
$result = $columns = [];
if (empty($model)) {
return $result;
}
// making sure that model is in table naming conventions.
$model = Inflector::tableize($model);
try {
$connection = ConnectionManager::get($connectionManager);
$schema = $connection->getSchemaCollection();
$table = $schema->describe($model);
$columns = $table->columns();
} catch (MissingDatasourceConfigException $e) {
return $result;
} catch (Exception $e) {
return $result;
}
// A table with no columns?
if (empty($columns)) {
return $result;
}
foreach ($columns as $column) {
$result[$column] = $column;
}
return $result;
} | php | public static function getModelColumns(string $model = '', string $connectionManager = 'default'): array
{
$result = $columns = [];
if (empty($model)) {
return $result;
}
// making sure that model is in table naming conventions.
$model = Inflector::tableize($model);
try {
$connection = ConnectionManager::get($connectionManager);
$schema = $connection->getSchemaCollection();
$table = $schema->describe($model);
$columns = $table->columns();
} catch (MissingDatasourceConfigException $e) {
return $result;
} catch (Exception $e) {
return $result;
}
// A table with no columns?
if (empty($columns)) {
return $result;
}
foreach ($columns as $column) {
$result[$column] = $column;
}
return $result;
} | [
"public",
"static",
"function",
"getModelColumns",
"(",
"string",
"$",
"model",
"=",
"''",
",",
"string",
"$",
"connectionManager",
"=",
"'default'",
")",
":",
"array",
"{",
"$",
"result",
"=",
"$",
"columns",
"=",
"[",
"]",
";",
"if",
"(",
"empty",
"(... | Get Model Columns
@param string $model name of the table
@param string $connectionManager of the datasource
@return mixed[] $result containing key/value pairs of model columns. | [
"Get",
"Model",
"Columns"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L211-L243 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.getColors | public static function getColors(array $config = [], bool $pretty = true): array
{
$result = [];
$config = empty($config) ? Configure::read('Colors') : $config;
if (!$pretty) {
return $config;
}
if (!$config) {
return $result;
}
foreach ($config as $k => $v) {
$result[$k] = '<div><div style="width:20px;height:20px;margin:0;border:1px solid #eee;float:left;background:' . $k . ';"></div> ' . $v . '</div><div style="clear:all"></div>';
}
return $result;
} | php | public static function getColors(array $config = [], bool $pretty = true): array
{
$result = [];
$config = empty($config) ? Configure::read('Colors') : $config;
if (!$pretty) {
return $config;
}
if (!$config) {
return $result;
}
foreach ($config as $k => $v) {
$result[$k] = '<div><div style="width:20px;height:20px;margin:0;border:1px solid #eee;float:left;background:' . $k . ';"></div> ' . $v . '</div><div style="clear:all"></div>';
}
return $result;
} | [
"public",
"static",
"function",
"getColors",
"(",
"array",
"$",
"config",
"=",
"[",
"]",
",",
"bool",
"$",
"pretty",
"=",
"true",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"config",
"=",
"empty",
"(",
"$",
"config",
")",
"?"... | Get colors for Select2 dropdown
@param mixed[] $config containing colors array
@param bool $pretty to append color identifiers to values.
@return mixed[] $result containing colors list. | [
"Get",
"colors",
"for",
"Select2",
"dropdown"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L286-L305 | train |
QoboLtd/cakephp-utils | src/Utility.php | Utility.sortApiVersions | protected static function sortApiVersions(array $versions = []): array
{
usort($versions, function ($first, $second) {
$firstVersion = (float)$first['number'];
$secondVersion = (float)$second['number'];
if ($firstVersion == $secondVersion) {
return 0;
}
return ($firstVersion > $secondVersion) ? 1 : -1;
});
return $versions;
} | php | protected static function sortApiVersions(array $versions = []): array
{
usort($versions, function ($first, $second) {
$firstVersion = (float)$first['number'];
$secondVersion = (float)$second['number'];
if ($firstVersion == $secondVersion) {
return 0;
}
return ($firstVersion > $secondVersion) ? 1 : -1;
});
return $versions;
} | [
"protected",
"static",
"function",
"sortApiVersions",
"(",
"array",
"$",
"versions",
"=",
"[",
"]",
")",
":",
"array",
"{",
"usort",
"(",
"$",
"versions",
",",
"function",
"(",
"$",
"first",
",",
"$",
"second",
")",
"{",
"$",
"firstVersion",
"=",
"(",
... | Sorting API Versions ascendingly
@param mixed[] $versions of found API sub-directories
@return mixed[] $versions sorted in ascending order. | [
"Sorting",
"API",
"Versions",
"ascendingly"
] | 4b07a3e6f2e611e7c6909c913e6166d280f3c751 | https://github.com/QoboLtd/cakephp-utils/blob/4b07a3e6f2e611e7c6909c913e6166d280f3c751/src/Utility.php#L458-L472 | train |
Rarst/meadow | src/Core.php | Core.undefined_function | public static function undefined_function( $function_name ) {
if ( \function_exists( $function_name ) ) {
return new \Twig_Function(
$function_name,
function () use ( $function_name ) {
ob_start();
$return = \call_user_func_array( $function_name, \func_get_args() );
$echo = ob_get_clean();
return empty( $echo ) ? $return : $echo;
},
array( 'is_safe' => array( 'all' ) )
);
}
return false;
} | php | public static function undefined_function( $function_name ) {
if ( \function_exists( $function_name ) ) {
return new \Twig_Function(
$function_name,
function () use ( $function_name ) {
ob_start();
$return = \call_user_func_array( $function_name, \func_get_args() );
$echo = ob_get_clean();
return empty( $echo ) ? $return : $echo;
},
array( 'is_safe' => array( 'all' ) )
);
}
return false;
} | [
"public",
"static",
"function",
"undefined_function",
"(",
"$",
"function_name",
")",
"{",
"if",
"(",
"\\",
"function_exists",
"(",
"$",
"function_name",
")",
")",
"{",
"return",
"new",
"\\",
"Twig_Function",
"(",
"$",
"function_name",
",",
"function",
"(",
... | Handler for undefined functions in Twig to pass them through to PHP and buffer echoing versions.
@param string $function_name Name of the function to handle.
@return bool|\Twig_Function | [
"Handler",
"for",
"undefined",
"functions",
"in",
"Twig",
"to",
"pass",
"them",
"through",
"to",
"PHP",
"and",
"buffer",
"echoing",
"versions",
"."
] | cad0b159d927f953cd02090a99b5a62add71b626 | https://github.com/Rarst/meadow/blob/cad0b159d927f953cd02090a99b5a62add71b626/src/Core.php#L92-L110 | train |
romm/formz | Classes/Configuration/ConfigurationFactory.php | ConfigurationFactory.getFormzConfiguration | public function getFormzConfiguration()
{
$cacheIdentifier = $this->getCacheIdentifier();
if (false === array_key_exists($cacheIdentifier, $this->instances)) {
$this->instances[$cacheIdentifier] = $this->getFormzConfigurationFromCache($cacheIdentifier);
}
return $this->instances[$cacheIdentifier];
} | php | public function getFormzConfiguration()
{
$cacheIdentifier = $this->getCacheIdentifier();
if (false === array_key_exists($cacheIdentifier, $this->instances)) {
$this->instances[$cacheIdentifier] = $this->getFormzConfigurationFromCache($cacheIdentifier);
}
return $this->instances[$cacheIdentifier];
} | [
"public",
"function",
"getFormzConfiguration",
"(",
")",
"{",
"$",
"cacheIdentifier",
"=",
"$",
"this",
"->",
"getCacheIdentifier",
"(",
")",
";",
"if",
"(",
"false",
"===",
"array_key_exists",
"(",
"$",
"cacheIdentifier",
",",
"$",
"this",
"->",
"instances",
... | Returns the global FormZ configuration.
Two cache layers are used:
- A local cache which will avoid fetching the configuration every time
the current script needs it.
- A system cache, which will store the configuration instance when it has
been built, improving performance for next scripts.
@return ConfigurationObjectInstance | [
"Returns",
"the",
"global",
"FormZ",
"configuration",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Configuration/ConfigurationFactory.php#L59-L68 | train |
romm/formz | Classes/Configuration/ConfigurationFactory.php | ConfigurationFactory.getFormzConfigurationFromCache | protected function getFormzConfigurationFromCache($cacheIdentifier)
{
$cacheInstance = CacheService::get()->getCacheInstance();
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
} else {
$instance = $this->buildFormzConfiguration();
if (false === $instance->getValidationResult()->hasErrors()) {
$cacheInstance->set($cacheIdentifier, $instance);
}
}
return $instance;
} | php | protected function getFormzConfigurationFromCache($cacheIdentifier)
{
$cacheInstance = CacheService::get()->getCacheInstance();
if ($cacheInstance->has($cacheIdentifier)) {
$instance = $cacheInstance->get($cacheIdentifier);
} else {
$instance = $this->buildFormzConfiguration();
if (false === $instance->getValidationResult()->hasErrors()) {
$cacheInstance->set($cacheIdentifier, $instance);
}
}
return $instance;
} | [
"protected",
"function",
"getFormzConfigurationFromCache",
"(",
"$",
"cacheIdentifier",
")",
"{",
"$",
"cacheInstance",
"=",
"CacheService",
"::",
"get",
"(",
")",
"->",
"getCacheInstance",
"(",
")",
";",
"if",
"(",
"$",
"cacheInstance",
"->",
"has",
"(",
"$",... | Will fetch the configuration from cache, and build it if not found. It
won't be stored in cache if any error is found. This is done this way to
avoid the integrator to be forced to flush caches when errors are found.
@param string $cacheIdentifier
@return ConfigurationObjectInstance | [
"Will",
"fetch",
"the",
"configuration",
"from",
"cache",
"and",
"build",
"it",
"if",
"not",
"found",
".",
"It",
"won",
"t",
"be",
"stored",
"in",
"cache",
"if",
"any",
"error",
"is",
"found",
".",
"This",
"is",
"done",
"this",
"way",
"to",
"avoid",
... | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Configuration/ConfigurationFactory.php#L78-L93 | train |
romm/formz | Classes/Exceptions/FormzException.php | FormzException.getNewExceptionInstance | final protected static function getNewExceptionInstance($message, $code, array $arguments = [])
{
$exceptionClassName = get_called_class();
return new $exceptionClassName(
vsprintf($message, $arguments),
$code
);
} | php | final protected static function getNewExceptionInstance($message, $code, array $arguments = [])
{
$exceptionClassName = get_called_class();
return new $exceptionClassName(
vsprintf($message, $arguments),
$code
);
} | [
"final",
"protected",
"static",
"function",
"getNewExceptionInstance",
"(",
"$",
"message",
",",
"$",
"code",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
")",
"{",
"$",
"exceptionClassName",
"=",
"get_called_class",
"(",
")",
";",
"return",
"new",
"$",
... | Creates a new exception instance.
@param string $message
@param int $code
@param array $arguments
@return FormzException | [
"Creates",
"a",
"new",
"exception",
"instance",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Exceptions/FormzException.php#L29-L37 | train |
QuickenLoans/mcp-panthor | src/ErrorHandling/ContentHandler/LoggingContentHandler.php | LoggingContentHandler.shouldLog | private function shouldLog($event)
{
$level = isset($this->configuration[$event]) ? $this->configuration[$event] : '';
$level = strtolower($level);
if (!$level) {
return '';
}
if (!isset(self::$levels[$level])) {
return '';
}
return $level;
} | php | private function shouldLog($event)
{
$level = isset($this->configuration[$event]) ? $this->configuration[$event] : '';
$level = strtolower($level);
if (!$level) {
return '';
}
if (!isset(self::$levels[$level])) {
return '';
}
return $level;
} | [
"private",
"function",
"shouldLog",
"(",
"$",
"event",
")",
"{",
"$",
"level",
"=",
"isset",
"(",
"$",
"this",
"->",
"configuration",
"[",
"$",
"event",
"]",
")",
"?",
"$",
"this",
"->",
"configuration",
"[",
"$",
"event",
"]",
":",
"''",
";",
"$",... | Should the event be logged?
If yes - return the log level to log the event as.
If no - return a falsey value
@param string $event
@return string | [
"Should",
"the",
"event",
"be",
"logged?"
] | b73e22d83d21b8ed4296bee6aebc66c8b07f292c | https://github.com/QuickenLoans/mcp-panthor/blob/b73e22d83d21b8ed4296bee6aebc66c8b07f292c/src/ErrorHandling/ContentHandler/LoggingContentHandler.php#L160-L174 | train |
romm/formz | Classes/Service/ViewHelper/Slot/SlotContextEntry.php | SlotContextEntry.addSlot | public function addSlot($name, Closure $closure, array $arguments)
{
$this->closures[$name] = $closure;
$this->arguments[$name] = $arguments;
} | php | public function addSlot($name, Closure $closure, array $arguments)
{
$this->closures[$name] = $closure;
$this->arguments[$name] = $arguments;
} | [
"public",
"function",
"addSlot",
"(",
"$",
"name",
",",
"Closure",
"$",
"closure",
",",
"array",
"$",
"arguments",
")",
"{",
"$",
"this",
"->",
"closures",
"[",
"$",
"name",
"]",
"=",
"$",
"closure",
";",
"$",
"this",
"->",
"arguments",
"[",
"$",
"... | Adds a closure - used to render the slot with the given name - to the
private storage in this class.
@param string $name
@param Closure $closure
@param array $arguments | [
"Adds",
"a",
"closure",
"-",
"used",
"to",
"render",
"the",
"slot",
"with",
"the",
"given",
"name",
"-",
"to",
"the",
"private",
"storage",
"in",
"this",
"class",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Service/ViewHelper/Slot/SlotContextEntry.php#L67-L71 | train |
romm/formz | Classes/Service/ViewHelper/Slot/SlotContextEntry.php | SlotContextEntry.addTemplateVariables | public function addTemplateVariables($slotName, array $arguments)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$savedArguments = [];
ArrayUtility::mergeRecursiveWithOverrule(
$arguments,
$this->getSlotArguments($slotName)
);
foreach ($arguments as $key => $value) {
if ($templateVariableContainer->exists($key)) {
$savedArguments[$key] = $templateVariableContainer->get($key);
$templateVariableContainer->remove($key);
}
$templateVariableContainer->add($key, $value);
}
$this->injectedVariables[$slotName] = $arguments;
$this->savedVariables[$slotName] = $savedArguments;
} | php | public function addTemplateVariables($slotName, array $arguments)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$savedArguments = [];
ArrayUtility::mergeRecursiveWithOverrule(
$arguments,
$this->getSlotArguments($slotName)
);
foreach ($arguments as $key => $value) {
if ($templateVariableContainer->exists($key)) {
$savedArguments[$key] = $templateVariableContainer->get($key);
$templateVariableContainer->remove($key);
}
$templateVariableContainer->add($key, $value);
}
$this->injectedVariables[$slotName] = $arguments;
$this->savedVariables[$slotName] = $savedArguments;
} | [
"public",
"function",
"addTemplateVariables",
"(",
"$",
"slotName",
",",
"array",
"$",
"arguments",
")",
"{",
"$",
"templateVariableContainer",
"=",
"$",
"this",
"->",
"renderingContext",
"->",
"getTemplateVariableContainer",
"(",
")",
";",
"$",
"savedArguments",
... | Will merge the given arguments with the ones registered by the given
slot, and inject them in the template variable container.
Note that the variables that are already defined are first saved before
being overridden, so they can be restored later.
@param string $slotName
@param array $arguments | [
"Will",
"merge",
"the",
"given",
"arguments",
"with",
"the",
"ones",
"registered",
"by",
"the",
"given",
"slot",
"and",
"inject",
"them",
"in",
"the",
"template",
"variable",
"container",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Service/ViewHelper/Slot/SlotContextEntry.php#L124-L145 | train |
romm/formz | Classes/Service/ViewHelper/Slot/SlotContextEntry.php | SlotContextEntry.restoreTemplateVariables | public function restoreTemplateVariables($slotName)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$mergedArguments = (isset($this->injectedVariables[$slotName])) ? $this->injectedVariables[$slotName] : [];
$savedArguments = (isset($this->savedVariables[$slotName])) ? $this->savedVariables[$slotName] : [];
foreach (array_keys($mergedArguments) as $key) {
$templateVariableContainer->remove($key);
}
foreach ($savedArguments as $key => $value) {
$templateVariableContainer->add($key, $value);
}
} | php | public function restoreTemplateVariables($slotName)
{
$templateVariableContainer = $this->renderingContext->getTemplateVariableContainer();
$mergedArguments = (isset($this->injectedVariables[$slotName])) ? $this->injectedVariables[$slotName] : [];
$savedArguments = (isset($this->savedVariables[$slotName])) ? $this->savedVariables[$slotName] : [];
foreach (array_keys($mergedArguments) as $key) {
$templateVariableContainer->remove($key);
}
foreach ($savedArguments as $key => $value) {
$templateVariableContainer->add($key, $value);
}
} | [
"public",
"function",
"restoreTemplateVariables",
"(",
"$",
"slotName",
")",
"{",
"$",
"templateVariableContainer",
"=",
"$",
"this",
"->",
"renderingContext",
"->",
"getTemplateVariableContainer",
"(",
")",
";",
"$",
"mergedArguments",
"=",
"(",
"isset",
"(",
"$"... | Will remove all variables previously injected in the template variable
container, and restore the ones that were saved before being overridden.
@param string $slotName | [
"Will",
"remove",
"all",
"variables",
"previously",
"injected",
"in",
"the",
"template",
"variable",
"container",
"and",
"restore",
"the",
"ones",
"that",
"were",
"saved",
"before",
"being",
"overridden",
"."
] | b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f | https://github.com/romm/formz/blob/b0bc266a1c86377ab43ef8d1c07a4b5f54d5fc3f/Classes/Service/ViewHelper/Slot/SlotContextEntry.php#L153-L166 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.stripLanguage | public function stripLanguage($path, $language = null)
{
$strip = '/' . ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($strip) > 1 && strpos($path, $strip) === 0 ) {
$path = substr($path, strlen($strip));
}
return $path;
} | php | public function stripLanguage($path, $language = null)
{
$strip = '/' . ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($strip) > 1 && strpos($path, $strip) === 0 ) {
$path = substr($path, strlen($strip));
}
return $path;
} | [
"public",
"function",
"stripLanguage",
"(",
"$",
"path",
",",
"$",
"language",
"=",
"null",
")",
"{",
"$",
"strip",
"=",
"'/'",
".",
"(",
"isset",
"(",
"$",
"language",
")",
"?",
"$",
"language",
":",
"$",
"this",
"->",
"getLanguage",
"(",
")",
")"... | Strip the language from the URI
@param string $path
@param string $language Optional. Defaults to the current language.
@return string | [
"Strip",
"the",
"language",
"from",
"the",
"URI"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L392-L401 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.prependLanguage | public function prependLanguage($path, $language = null)
{
$prepend = ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($prepend) > 1 ) {
return $prepend . (strpos($path, '/') === 0 ? $path : '/' . $path);
}
return $path;
} | php | public function prependLanguage($path, $language = null)
{
$prepend = ( isset($language) ? $language : $this->getLanguage() );
if ( strlen($prepend) > 1 ) {
return $prepend . (strpos($path, '/') === 0 ? $path : '/' . $path);
}
return $path;
} | [
"public",
"function",
"prependLanguage",
"(",
"$",
"path",
",",
"$",
"language",
"=",
"null",
")",
"{",
"$",
"prepend",
"=",
"(",
"isset",
"(",
"$",
"language",
")",
"?",
"$",
"language",
":",
"$",
"this",
"->",
"getLanguage",
"(",
")",
")",
";",
"... | Prepend the language to the URI
@param string $path
@param string $language Optional. The language tho prepend. Defaults to the current language.
@return string | [
"Prepend",
"the",
"language",
"to",
"the",
"URI"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L411-L420 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.replaceLanguage | public function replaceLanguage($path, $language, $replacement = null)
{
$path = $this->stripLanguage($path, $language);
$path = $this->prependLanguage($path, $replacement);
return $path;
} | php | public function replaceLanguage($path, $language, $replacement = null)
{
$path = $this->stripLanguage($path, $language);
$path = $this->prependLanguage($path, $replacement);
return $path;
} | [
"public",
"function",
"replaceLanguage",
"(",
"$",
"path",
",",
"$",
"language",
",",
"$",
"replacement",
"=",
"null",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"stripLanguage",
"(",
"$",
"path",
",",
"$",
"language",
")",
";",
"$",
"path",
"=",... | Replace the language in the URI
@param string $path
@param string $language The language being searched for.
@param string $replacement Optional. The language that replaces $lang. Defaults to the current language.
@return string | [
"Replace",
"the",
"language",
"in",
"the",
"URI"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L431-L437 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.getFromHeader | protected function getFromHeader(ServerRequestInterface $request)
{
$accept = $request->getHeaderLine('Accept-Language');
if ( empty($accept) || empty($this->languages) ) {
return;
}
$language = (new Negotiator())->getBest($accept, $this->languages);
if ( $language ) {
return $language->getValue();
}
} | php | protected function getFromHeader(ServerRequestInterface $request)
{
$accept = $request->getHeaderLine('Accept-Language');
if ( empty($accept) || empty($this->languages) ) {
return;
}
$language = (new Negotiator())->getBest($accept, $this->languages);
if ( $language ) {
return $language->getValue();
}
} | [
"protected",
"function",
"getFromHeader",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"accept",
"=",
"$",
"request",
"->",
"getHeaderLine",
"(",
"'Accept-Language'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"accept",
")",
"||",
"empty",
"(",... | Retrieve the language using the Accept-Language header.
@param RequestInterface $request PSR7 request object
@return null|string | [
"Retrieve",
"the",
"language",
"using",
"the",
"Accept",
"-",
"Language",
"header",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L446-L459 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.getFromPath | protected function getFromPath(ServerRequestInterface $request)
{
$uri = $request->getUri();
$regex = '~^\/?' . $this->getRegEx() . '\b~';
$path = rtrim( $uri->getPath(), '/\\' ) . '/';
if ( preg_match($regex, $path, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
} | php | protected function getFromPath(ServerRequestInterface $request)
{
$uri = $request->getUri();
$regex = '~^\/?' . $this->getRegEx() . '\b~';
$path = rtrim( $uri->getPath(), '/\\' ) . '/';
if ( preg_match($regex, $path, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
} | [
"protected",
"function",
"getFromPath",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"uri",
"=",
"$",
"request",
"->",
"getUri",
"(",
")",
";",
"$",
"regex",
"=",
"'~^\\/?'",
".",
"$",
"this",
"->",
"getRegEx",
"(",
")",
".",
"'\\b~'",
... | Retrieve the language from the requested URI.
@param RequestInterface $request PSR7 request object
@return null|string | [
"Retrieve",
"the",
"language",
"from",
"the",
"requested",
"URI",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L468-L481 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.getFromQuery | protected function getFromQuery(ServerRequestInterface $request)
{
$params = array_intersect_key($request->getQueryParams(), array_flip($this->getQueryKeys()));
$regex = '~^\/?' . $this->getRegEx() . '\b~';
foreach ($params as $key => $value) {
if ( preg_match($regex, $value, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
}
} | php | protected function getFromQuery(ServerRequestInterface $request)
{
$params = array_intersect_key($request->getQueryParams(), array_flip($this->getQueryKeys()));
$regex = '~^\/?' . $this->getRegEx() . '\b~';
foreach ($params as $key => $value) {
if ( preg_match($regex, $value, $matches) ) {
if (isset($matches['language'])) {
return $matches['language'];
} else {
throw new RuntimeException('The regular expression pattern is missing a named subpattern "language".');
}
}
}
} | [
"protected",
"function",
"getFromQuery",
"(",
"ServerRequestInterface",
"$",
"request",
")",
"{",
"$",
"params",
"=",
"array_intersect_key",
"(",
"$",
"request",
"->",
"getQueryParams",
"(",
")",
",",
"array_flip",
"(",
"$",
"this",
"->",
"getQueryKeys",
"(",
... | Retrieve the language from the requested URI's query string.
@param RequestInterface $request PSR7 request object
@return null|string | [
"Retrieve",
"the",
"language",
"from",
"the",
"requested",
"URI",
"s",
"query",
"string",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L490-L504 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.setSupportedLanguages | public function setSupportedLanguages(array $languages)
{
$this->languages = $languages;
$this->fallbackLanguage = reset($languages);
return $this;
} | php | public function setSupportedLanguages(array $languages)
{
$this->languages = $languages;
$this->fallbackLanguage = reset($languages);
return $this;
} | [
"public",
"function",
"setSupportedLanguages",
"(",
"array",
"$",
"languages",
")",
"{",
"$",
"this",
"->",
"languages",
"=",
"$",
"languages",
";",
"$",
"this",
"->",
"fallbackLanguage",
"=",
"reset",
"(",
"$",
"languages",
")",
";",
"return",
"$",
"this"... | Set the supported languages
@param array $languages
@return self
@throws RuntimeException if the variable isn't an array | [
"Set",
"the",
"supported",
"languages"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L525-L531 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.setFallbackLanguage | public function setFallbackLanguage($language)
{
if ( $this->isSupported($language) ) {
$this->fallbackLanguage = $language;
}
else {
throw new RuntimeException('Variable must be one of the supported languages.');
}
return $this;
} | php | public function setFallbackLanguage($language)
{
if ( $this->isSupported($language) ) {
$this->fallbackLanguage = $language;
}
else {
throw new RuntimeException('Variable must be one of the supported languages.');
}
return $this;
} | [
"public",
"function",
"setFallbackLanguage",
"(",
"$",
"language",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isSupported",
"(",
"$",
"language",
")",
")",
"{",
"$",
"this",
"->",
"fallbackLanguage",
"=",
"$",
"language",
";",
"}",
"else",
"{",
"throw",
... | Set the fallback language
Must be one of the supported languages.
@param string $language The fallback language.
@return self
@throws RuntimeException if the variable isn't a supported language | [
"Set",
"the",
"fallback",
"language"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L568-L578 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.getUserLanguage | public function getUserLanguage(ServerRequestInterface $request = null)
{
if (
$this->saveInSession &&
isset($_SESSION['language']) &&
$this->isSupported($_SESSION['language'])
) {
return $_SESSION['language'];
}
if ( empty($language) && $request instanceof ServerRequestInterface ) {
return $this->getFromHeader($request);
}
return null;
} | php | public function getUserLanguage(ServerRequestInterface $request = null)
{
if (
$this->saveInSession &&
isset($_SESSION['language']) &&
$this->isSupported($_SESSION['language'])
) {
return $_SESSION['language'];
}
if ( empty($language) && $request instanceof ServerRequestInterface ) {
return $this->getFromHeader($request);
}
return null;
} | [
"public",
"function",
"getUserLanguage",
"(",
"ServerRequestInterface",
"$",
"request",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"saveInSession",
"&&",
"isset",
"(",
"$",
"_SESSION",
"[",
"'language'",
"]",
")",
"&&",
"$",
"this",
"->",
"isSupp... | Retrieve the user's preferred language
Looks in the user session and the Accept-Language header
if a request is provided. If the language is not part of
the supported set, returns the fallback language.
@param RequestInterface $request PSR7 request object
@return string|null | [
"Retrieve",
"the",
"user",
"s",
"preferred",
"language"
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L591-L606 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.setCallbacks | public function setCallbacks(array $callables)
{
$this->callbacks = [];
foreach ($callables as $callable) {
if (is_callable($callable)) {
$this->addCallback($callable);
}
}
return $this;
} | php | public function setCallbacks(array $callables)
{
$this->callbacks = [];
foreach ($callables as $callable) {
if (is_callable($callable)) {
$this->addCallback($callable);
}
}
return $this;
} | [
"public",
"function",
"setCallbacks",
"(",
"array",
"$",
"callables",
")",
"{",
"$",
"this",
"->",
"callbacks",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"callables",
"as",
"$",
"callable",
")",
"{",
"if",
"(",
"is_callable",
"(",
"$",
"callable",
")",
... | Set the callbacks used to assign the current language to.
@param callable[] $callbacks The callable to be called.
@return self | [
"Set",
"the",
"callbacks",
"used",
"to",
"assign",
"the",
"current",
"language",
"to",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L647-L658 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.setQueryKeys | public function setQueryKeys(array $keys)
{
$this->queryKeys = [];
foreach ($keys as $key) {
if (is_string($key)) {
$this->addQueryKey($key);
}
}
return $this;
} | php | public function setQueryKeys(array $keys)
{
$this->queryKeys = [];
foreach ($keys as $key) {
if (is_string($key)) {
$this->addQueryKey($key);
}
}
return $this;
} | [
"public",
"function",
"setQueryKeys",
"(",
"array",
"$",
"keys",
")",
"{",
"$",
"this",
"->",
"queryKeys",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"key",
")",
")",
"{",
"$",
... | Set the query string keys to look for when resolving the current language.
@param string[] $keys The query string keys.
@return self | [
"Set",
"the",
"query",
"string",
"keys",
"to",
"look",
"for",
"when",
"resolving",
"the",
"current",
"language",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L691-L702 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.sanitizeLanguage | public function sanitizeLanguage($language)
{
if ( 0 === count($this->languages) ) {
throw new RuntimeException('Polyglot features no supported languages.');
}
if ( ! $this->isSupported($language) ) {
$language = $this->getFallbackLanguage();
}
return $language;
} | php | public function sanitizeLanguage($language)
{
if ( 0 === count($this->languages) ) {
throw new RuntimeException('Polyglot features no supported languages.');
}
if ( ! $this->isSupported($language) ) {
$language = $this->getFallbackLanguage();
}
return $language;
} | [
"public",
"function",
"sanitizeLanguage",
"(",
"$",
"language",
")",
"{",
"if",
"(",
"0",
"===",
"count",
"(",
"$",
"this",
"->",
"languages",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Polyglot features no supported languages.'",
")",
";",
"}",... | Retrieve the fallback language if the variable isn't a supported language.
@param string $anguage
@return string
@throws RuntimeException if there are no available languages | [
"Retrieve",
"the",
"fallback",
"language",
"if",
"the",
"variable",
"isn",
"t",
"a",
"supported",
"language",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L762-L773 | train |
mcaskill/Slim-Polyglot | src/Polyglot.php | Polyglot.isLanguageRequiredInUri | public function isLanguageRequiredInUri($state = null)
{
if (isset($state)) {
$this->languageRequiredInUri = (bool) $state;
}
return $this->languageRequiredInUri;
} | php | public function isLanguageRequiredInUri($state = null)
{
if (isset($state)) {
$this->languageRequiredInUri = (bool) $state;
}
return $this->languageRequiredInUri;
} | [
"public",
"function",
"isLanguageRequiredInUri",
"(",
"$",
"state",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"state",
")",
")",
"{",
"$",
"this",
"->",
"languageRequiredInUri",
"=",
"(",
"bool",
")",
"$",
"state",
";",
"}",
"return",
"$",
... | Determine if languages are required in a URI.
@param bool|null $state
@return bool | [
"Determine",
"if",
"languages",
"are",
"required",
"in",
"a",
"URI",
"."
] | 4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45 | https://github.com/mcaskill/Slim-Polyglot/blob/4c2355f3835dcbf17b57cfc7d7cb8b61b5e26f45/src/Polyglot.php#L782-L789 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.