repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
ekyna/AdminBundle | Menu/MenuGroup.php | MenuGroup.addEntry | public function addEntry(MenuEntry $entry)
{
if ($this->prepared) {
throw new \RuntimeException('MenuGroup has been prepared and can\'t receive new entries.');
}
$this->entries[] = $entry;
return $this;
} | php | public function addEntry(MenuEntry $entry)
{
if ($this->prepared) {
throw new \RuntimeException('MenuGroup has been prepared and can\'t receive new entries.');
}
$this->entries[] = $entry;
return $this;
} | Adds an entry.
@param MenuEntry $entry
@throws \RuntimeException
@return MenuGroup | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Menu/MenuGroup.php#L236-L244 |
ekyna/AdminBundle | Menu/MenuGroup.php | MenuGroup.prepare | public function prepare()
{
if ($this->prepared) {
return;
}
usort($this->entries, function(MenuEntry $a, MenuEntry $b) {
if ($a->getPosition() == $b->getPosition()) {
return 0;
}
return $a->getPosition() > $b->getPosition() ? 1 : -1;
});
$this->prepared = true;
} | php | public function prepare()
{
if ($this->prepared) {
return;
}
usort($this->entries, function(MenuEntry $a, MenuEntry $b) {
if ($a->getPosition() == $b->getPosition()) {
return 0;
}
return $a->getPosition() > $b->getPosition() ? 1 : -1;
});
$this->prepared = true;
} | Prepares the group for rendering. | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Menu/MenuGroup.php#L259-L271 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.generarId | private function generarId()
{
if (function_exists('random_bytes')) {
$semilla = random_bytes(32);
} elseif (function_exists('mcrypt_create_iv')) {
$semilla = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$semilla = openssl_random_pseudo_bytes(32);
} else {
$semilla = uniqid('armazon', true);
}
return hash('sha256', $semilla);
} | php | private function generarId()
{
if (function_exists('random_bytes')) {
$semilla = random_bytes(32);
} elseif (function_exists('mcrypt_create_iv')) {
$semilla = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$semilla = openssl_random_pseudo_bytes(32);
} else {
$semilla = uniqid('armazon', true);
}
return hash('sha256', $semilla);
} | Genera un identificador nuevo usando una semilla aleatoria
@return string | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L34-L47 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.iniciar | public function iniciar()
{
if ($this->iniciado) {
return true;
}
if (!$this->adaptador->abrir($this->nombre)) {
throw new \RuntimeException('Hubo un error inicializando el adaptador de sesión.');
}
if (!$this->id) {
$this->id = $this->generarId();
}
$this->datos = $this->adaptador->leer($this->id);
return $this->iniciado = true;
} | php | public function iniciar()
{
if ($this->iniciado) {
return true;
}
if (!$this->adaptador->abrir($this->nombre)) {
throw new \RuntimeException('Hubo un error inicializando el adaptador de sesión.');
}
if (!$this->id) {
$this->id = $this->generarId();
}
$this->datos = $this->adaptador->leer($this->id);
return $this->iniciado = true;
} | Inicia la sesión si no se ha iniciado todavía.
@throws \RuntimeException | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L54-L71 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.escribirCerrar | public function escribirCerrar()
{
if (!$this->iniciado) {
throw new \RuntimeException('La sesión no fue iniciada previamente.');
}
if (!$this->adaptador->escribir($this->id, $this->datos)) {
throw new \RuntimeException('Hubo un error escribiendo la sesión.');
}
$this->adaptador->cerrar();
$this->iniciado = false;
return true;
} | php | public function escribirCerrar()
{
if (!$this->iniciado) {
throw new \RuntimeException('La sesión no fue iniciada previamente.');
}
if (!$this->adaptador->escribir($this->id, $this->datos)) {
throw new \RuntimeException('Hubo un error escribiendo la sesión.');
}
$this->adaptador->cerrar();
$this->iniciado = false;
return true;
} | Guarda los datos de la sesión actual para luego cerrarla. | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L76-L90 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.destruir | public function destruir()
{
if (!$this->iniciado) {
throw new \RuntimeException('La sesión no fue iniciada previamente.');
}
$this->adaptador->destruir($this->id);
$this->iniciado = false;
} | php | public function destruir()
{
if (!$this->iniciado) {
throw new \RuntimeException('La sesión no fue iniciada previamente.');
}
$this->adaptador->destruir($this->id);
$this->iniciado = false;
} | Libera y destruye la sesion actual y su contenido. | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L95-L103 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.anunciar | public function anunciar($mensaje, $tipo = 'error')
{
$this->requerirInicio();
$this->datos['__anuncio']['mensaje'] = $mensaje;
$this->datos['__anuncio']['tipo'] = $tipo;
} | php | public function anunciar($mensaje, $tipo = 'error')
{
$this->requerirInicio();
$this->datos['__anuncio']['mensaje'] = $mensaje;
$this->datos['__anuncio']['tipo'] = $tipo;
} | Define anuncio importante para el usuario.
@param string $mensaje
@param string $tipo | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L126-L132 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.obtener | public function obtener($llave, $valorAlterno = null)
{
$this->requerirInicio();
return isset($this->datos[$llave]) ? $this->datos[$llave] : $valorAlterno;
} | php | public function obtener($llave, $valorAlterno = null)
{
$this->requerirInicio();
return isset($this->datos[$llave]) ? $this->datos[$llave] : $valorAlterno;
} | Obtiene una variable de la sesion.
@param string $llave
@param mixed $valorAlterno
@return mixed | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L167-L172 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.eliminar | public function eliminar($llave)
{
$this->requerirInicio();
if (isset($this->datos[$llave])) {
$valor = $this->datos[$llave];
unset($this->datos[$llave]);
return $valor;
} else {
return null;
}
} | php | public function eliminar($llave)
{
$this->requerirInicio();
if (isset($this->datos[$llave])) {
$valor = $this->datos[$llave];
unset($this->datos[$llave]);
return $valor;
} else {
return null;
}
} | Elimina una variable en la sesion.
@param string $llave
@return mixed el valor de la variable eliminada o nulo si no existe variable | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L194-L205 |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.regenerarId | public function regenerarId()
{
$this->requerirInicio();
$this->adaptador->destruir($this->id);
$this->id = $this->generarId();
$this->adaptador->escribir($this->id, $this->datos);
return $this->id;
} | php | public function regenerarId()
{
$this->requerirInicio();
$this->adaptador->destruir($this->id);
$this->id = $this->generarId();
$this->adaptador->escribir($this->id, $this->datos);
return $this->id;
} | Actualiza el identificador de sesión actual con uno generado más reciente.
@return string Devueve el identificador nuevo | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L236-L245 |
chilimatic/chilimatic-framework | lib/route/parser/UrlParser.php | UrlParser.getCleanPath | private function getCleanPath($path)
{
// remove the first slash for safety reasons [delimitor mapping] based on the web-server Rewrite
if (mb_strpos($path, $this->delimiter) === 0) {
$path = mb_substr($path, 1);
}
// if the last character is a delimiter remove it as well
if (mb_strpos($path, $this->delimiter) == mb_strlen($path) - 1) {
$path = mb_substr($path, 0, -1);
}
//remove the get parameter so it's clean
if (($ppos = mb_strpos($path, '?')) && $ppos > 0) {
$path = mb_substr($path, 0, $ppos);
}
unset($ppos);
return $path;
} | php | private function getCleanPath($path)
{
// remove the first slash for safety reasons [delimitor mapping] based on the web-server Rewrite
if (mb_strpos($path, $this->delimiter) === 0) {
$path = mb_substr($path, 1);
}
// if the last character is a delimiter remove it as well
if (mb_strpos($path, $this->delimiter) == mb_strlen($path) - 1) {
$path = mb_substr($path, 0, -1);
}
//remove the get parameter so it's clean
if (($ppos = mb_strpos($path, '?')) && $ppos > 0) {
$path = mb_substr($path, 0, $ppos);
}
unset($ppos);
return $path;
} | @param $path
@return string | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/parser/UrlParser.php#L32-L53 |
chilimatic/chilimatic-framework | lib/route/parser/UrlParser.php | UrlParser.parse | public function parse($content)
{
// if there is no path it's not needed to try to get a clean one
if (empty($content)) return [];
$path = $this->getCleanPath($content);
$pathParts = [$this->delimiter];
// check if there is even a need for further checks
if (mb_strpos($path, $this->delimiter) === false) {
if (!$path) {
return [$this->delimiter];
}
// set the root and the path
$tmpPathParts = [
$this->delimiter,
$path
];
return $tmpPathParts;
}
// if there's a deeper path it's time to walk through it and clean the empty parts etc
$tmpPathParts = explode($this->delimiter, $path);
// walk through the array and remove the empty entries
for ($i = 0, $c = count($tmpPathParts); $i < $c; $i++) {
if (!$tmpPathParts[$i]) unset($tmpPathParts[$i]);
}
// prepend the default delimiter
$pathParts = array_merge($pathParts, $tmpPathParts);
// path parts
return $pathParts;
} | php | public function parse($content)
{
// if there is no path it's not needed to try to get a clean one
if (empty($content)) return [];
$path = $this->getCleanPath($content);
$pathParts = [$this->delimiter];
// check if there is even a need for further checks
if (mb_strpos($path, $this->delimiter) === false) {
if (!$path) {
return [$this->delimiter];
}
// set the root and the path
$tmpPathParts = [
$this->delimiter,
$path
];
return $tmpPathParts;
}
// if there's a deeper path it's time to walk through it and clean the empty parts etc
$tmpPathParts = explode($this->delimiter, $path);
// walk through the array and remove the empty entries
for ($i = 0, $c = count($tmpPathParts); $i < $c; $i++) {
if (!$tmpPathParts[$i]) unset($tmpPathParts[$i]);
}
// prepend the default delimiter
$pathParts = array_merge($pathParts, $tmpPathParts);
// path parts
return $pathParts;
} | parse method that fills the collection
@param string $content
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/parser/UrlParser.php#L62-L98 |
phpalchemy/phpalchemy | Alchemy/Component/Http/File/File.php | File.guessExtension | public function guessExtension()
{
$type = $this->getMimeType();
return isset(static::$defaultExtensions[$type]) ? static::$defaultExtensions[$type] : null;
} | php | public function guessExtension()
{
$type = $this->getMimeType();
return isset(static::$defaultExtensions[$type]) ? static::$defaultExtensions[$type] : null;
} | Returns the extension based on the mime type.
If the mime type is unknown, returns null.
@return string|null The guessed extension or null if it cannot be guessed | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/Http/File/File.php#L529-L534 |
phpalchemy/phpalchemy | Alchemy/Component/Http/File/File.php | File.move | public function move($directory, $name = null)
{
if (! is_dir($directory)) {
if (false === @mkdir($directory, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the "%s" directory', $directory));
}
} elseif (! is_writable($directory)) {
throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $directory));
}
$target = $directory.DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : basename($name));
if (! @rename($this->getPathname(), $target)) {
$error = error_get_last();
throw new \RuntimeException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
}
chmod($target, 0666);
return new File($target);
} | php | public function move($directory, $name = null)
{
if (! is_dir($directory)) {
if (false === @mkdir($directory, 0777, true)) {
throw new \RuntimeException(sprintf('Unable to create the "%s" directory', $directory));
}
} elseif (! is_writable($directory)) {
throw new \RuntimeException(sprintf('Unable to write in the "%s" directory', $directory));
}
$target = $directory.DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : basename($name));
if (! @rename($this->getPathname(), $target)) {
$error = error_get_last();
throw new \RuntimeException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, strip_tags($error['message'])));
}
chmod($target, 0666);
return new File($target);
} | Moves the file to a new location.
@param string $directory The destination folder
@param string $name The new file name
@return File A File object representing the new file | https://github.com/phpalchemy/phpalchemy/blob/5b7e9b13acfda38c61b2da2639e8a56f298dc32e/Alchemy/Component/Http/File/File.php#L587-L607 |
evispa/TranslationEditorBundle | Form/Type/TranslationsEditorType.php | TranslationsEditorType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (empty($options['locales'])) {
throw new \LogicException('The translation editor requires at least a single locale specified.');
}
$prototype = $builder->create(
$options['prototype_name'],
$options['type'],
$options['options']
);
// Translation data sort listener is used to sort and add missing entities in the list based on the locales.
$translationDataSorter = new \Nercury\TranslationEditorBundle\Form\Listener\TranslationDataSortListener(
$options['locale_field_name'],
$prototype->getDataClass(),
$options['locales'],
$options['null_locale_enabled'],
$this->doctrine->getManager(),
$options['auto_remove_ignore_fields']
);
$builder->addEventSubscriber($translationDataSorter);
// Resize form listener is used to create forms for each collection entity.
if (defined('Symfony\Component\Form\FormEvents::POST_SUBMIT')) {
$resizeListener = new ResizeFormListener(
$options['type'],
$options['options'],
false,
false
);
} else {
$resizeListener = new ResizeFormListener(
$builder->getFormFactory(),
$options['type'],
$options['options'],
false,
false
);
}
$builder->addEventSubscriber($resizeListener);
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
if (empty($options['locales'])) {
throw new \LogicException('The translation editor requires at least a single locale specified.');
}
$prototype = $builder->create(
$options['prototype_name'],
$options['type'],
$options['options']
);
// Translation data sort listener is used to sort and add missing entities in the list based on the locales.
$translationDataSorter = new \Nercury\TranslationEditorBundle\Form\Listener\TranslationDataSortListener(
$options['locale_field_name'],
$prototype->getDataClass(),
$options['locales'],
$options['null_locale_enabled'],
$this->doctrine->getManager(),
$options['auto_remove_ignore_fields']
);
$builder->addEventSubscriber($translationDataSorter);
// Resize form listener is used to create forms for each collection entity.
if (defined('Symfony\Component\Form\FormEvents::POST_SUBMIT')) {
$resizeListener = new ResizeFormListener(
$options['type'],
$options['options'],
false,
false
);
} else {
$resizeListener = new ResizeFormListener(
$builder->getFormFactory(),
$options['type'],
$options['options'],
false,
false
);
}
$builder->addEventSubscriber($resizeListener);
} | {@inheritdoc} | https://github.com/evispa/TranslationEditorBundle/blob/312040605c331fc2520f5d042bc00b05608554b5/Form/Type/TranslationsEditorType.php#L59-L104 |
evispa/TranslationEditorBundle | Form/Type/TranslationsEditorType.php | TranslationsEditorType.finishView | public function finishView(FormView $view, FormInterface $form, array $options)
{
if ($form->getConfig()->hasAttribute('prototype') && $view->vars['prototype']->vars['multipart']) {
$view->vars['multipart'] = true;
}
$options = $form->getConfig()->getOptions();
$view->vars['null_locale_enabled'] = $options['null_locale_enabled'];
$view->vars['null_locale_selected'] = $options['null_locale_selected'];
$requestLocale = $this->getRequestLocale();
$view->vars['locale_titles'] = array();
foreach ($options['locales'] as $locale) {
$view->vars['locale_titles'][$locale] = \Locale::getDisplayName($locale, $requestLocale);
}
$request = $this->getRequest();
if (null === $request) {
$current_selected_lang = $options['locales'][0];
} else {
$current_selected_lang = $request->cookies->get(
'current_selected_translation_lang',
null
);
$selectedLanguageIsNotValid = $current_selected_lang !== '__all__' && !in_array(
$current_selected_lang,
$options['locales']
);
if ($current_selected_lang === null || $selectedLanguageIsNotValid) {
$current_selected_lang = $options['locales'][0];
}
}
$view->vars['current_selected_lang'] = $current_selected_lang;
} | php | public function finishView(FormView $view, FormInterface $form, array $options)
{
if ($form->getConfig()->hasAttribute('prototype') && $view->vars['prototype']->vars['multipart']) {
$view->vars['multipart'] = true;
}
$options = $form->getConfig()->getOptions();
$view->vars['null_locale_enabled'] = $options['null_locale_enabled'];
$view->vars['null_locale_selected'] = $options['null_locale_selected'];
$requestLocale = $this->getRequestLocale();
$view->vars['locale_titles'] = array();
foreach ($options['locales'] as $locale) {
$view->vars['locale_titles'][$locale] = \Locale::getDisplayName($locale, $requestLocale);
}
$request = $this->getRequest();
if (null === $request) {
$current_selected_lang = $options['locales'][0];
} else {
$current_selected_lang = $request->cookies->get(
'current_selected_translation_lang',
null
);
$selectedLanguageIsNotValid = $current_selected_lang !== '__all__' && !in_array(
$current_selected_lang,
$options['locales']
);
if ($current_selected_lang === null || $selectedLanguageIsNotValid) {
$current_selected_lang = $options['locales'][0];
}
}
$view->vars['current_selected_lang'] = $current_selected_lang;
} | {@inheritdoc} | https://github.com/evispa/TranslationEditorBundle/blob/312040605c331fc2520f5d042bc00b05608554b5/Form/Type/TranslationsEditorType.php#L109-L146 |
evispa/TranslationEditorBundle | Form/Type/TranslationsEditorType.php | TranslationsEditorType.setDefaultOptions | public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$optionsNormalizer = function (Options $options, $value) {
$value['block_name'] = 'entry';
return $value;
};
$resolver->setDefaults(
array(
'allow_add' => false,
'allow_delete' => false,
'prototype' => false,
'prototype_name' => '__protname__',
'type' => 'text',
'options' => array(),
// List of all locales to manage.
'locales' => $this->getDefaultEditorLocales(), // should pass yourself
// A locale field name in related entity. If it is private, getLang and setLang are used.
// This option uses property path notation. Also works with arrays (use "[lang]").
'locale_field_name' => 'lang',
// Allow editing "null" language.
'null_locale_enabled' => false,
// Editor has "null" language selected.
'null_locale_selected' => false,
// Automatically remove translation entity from db if it is empty.
'auto_remove_empty_translations' => true,
'auto_remove_ignore_fields' => array('created_at', 'updated_at'),
'error_bubbling' => false,
)
);
$resolver->setNormalizers(
array(
'options' => $optionsNormalizer,
)
);
} | php | public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$optionsNormalizer = function (Options $options, $value) {
$value['block_name'] = 'entry';
return $value;
};
$resolver->setDefaults(
array(
'allow_add' => false,
'allow_delete' => false,
'prototype' => false,
'prototype_name' => '__protname__',
'type' => 'text',
'options' => array(),
// List of all locales to manage.
'locales' => $this->getDefaultEditorLocales(), // should pass yourself
// A locale field name in related entity. If it is private, getLang and setLang are used.
// This option uses property path notation. Also works with arrays (use "[lang]").
'locale_field_name' => 'lang',
// Allow editing "null" language.
'null_locale_enabled' => false,
// Editor has "null" language selected.
'null_locale_selected' => false,
// Automatically remove translation entity from db if it is empty.
'auto_remove_empty_translations' => true,
'auto_remove_ignore_fields' => array('created_at', 'updated_at'),
'error_bubbling' => false,
)
);
$resolver->setNormalizers(
array(
'options' => $optionsNormalizer,
)
);
} | {@inheritdoc} | https://github.com/evispa/TranslationEditorBundle/blob/312040605c331fc2520f5d042bc00b05608554b5/Form/Type/TranslationsEditorType.php#L156-L192 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.getMenuIdFor | public function getMenuIdFor(int $itemId): int
{
// Find parent identifier
$menuId = (int)$this
->database
->query(
"SELECT menu_id FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$menuId) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
return $menuId;
} | php | public function getMenuIdFor(int $itemId): int
{
// Find parent identifier
$menuId = (int)$this
->database
->query(
"SELECT menu_id FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$menuId) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
return $menuId;
} | Get menu identifier for item
@param int $itemId
@return int | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L115-L132 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.insert | public function insert(int $menuId, int $nodeId, string $title, $description = null): int
{
list($menuId, $siteId) = $this->validateMenu($menuId, $title, $nodeId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE menu_id = ? AND (parent_id IS NULL OR parent_id = 0)",
[$menuId]
)
->fetchField()
;
return (int)$this
->database
->insert('umenu_item')
->fields([
'menu_id' => $menuId,
'site_id' => $siteId,
'node_id' => $nodeId,
'parent_id' => null,
'weight' => $weight,
'title' => $title,
'description' => $description,
])
->execute()
;
} | php | public function insert(int $menuId, int $nodeId, string $title, $description = null): int
{
list($menuId, $siteId) = $this->validateMenu($menuId, $title, $nodeId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE menu_id = ? AND (parent_id IS NULL OR parent_id = 0)",
[$menuId]
)
->fetchField()
;
return (int)$this
->database
->insert('umenu_item')
->fields([
'menu_id' => $menuId,
'site_id' => $siteId,
'node_id' => $nodeId,
'parent_id' => null,
'weight' => $weight,
'title' => $title,
'description' => $description,
])
->execute()
;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L137-L164 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.update | public function update(int $itemId, $nodeId = null, $title = null, $description = null)
{
$exists = (bool)$this
->database
->query(
"SELECT 1 FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$exists) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
$values = [];
if (null !== $nodeId) {
$values['node_id'] = $nodeId;
}
if (null !== $title) {
$values['title'] = $title;
}
if (null !== $description) {
$values['description'] = $description;
}
if (empty($values)) {
return;
}
$this
->database
->update('umenu_item')
->fields($values)
->condition('id', $itemId)
->execute()
;
} | php | public function update(int $itemId, $nodeId = null, $title = null, $description = null)
{
$exists = (bool)$this
->database
->query(
"SELECT 1 FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$exists) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
$values = [];
if (null !== $nodeId) {
$values['node_id'] = $nodeId;
}
if (null !== $title) {
$values['title'] = $title;
}
if (null !== $description) {
$values['description'] = $description;
}
if (empty($values)) {
return;
}
$this
->database
->update('umenu_item')
->fields($values)
->condition('id', $itemId)
->execute()
;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L297-L334 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.moveAsChild | public function moveAsChild(int $itemId, int $otherItemId)
{
$this->validateMove($itemId, $otherItemId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE parent_id = ?",
[$otherItemId]
)
->fetchField()
;
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = :parent, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':parent' => $otherItemId,
':weight' => $weight,
]
)
;
} | php | public function moveAsChild(int $itemId, int $otherItemId)
{
$this->validateMove($itemId, $otherItemId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE parent_id = ?",
[$otherItemId]
)
->fetchField()
;
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = :parent, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':parent' => $otherItemId,
':weight' => $weight,
]
)
;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L339-L363 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.moveToRoot | public function moveToRoot(int $itemId)
{
$menuId = $this->getMenuIdFor($itemId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE (parent_id IS NULL OR parent_id = 0) AND menu_id = ?",
[$menuId]
)
->fetchField()
;
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = NULL, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':weight' => $weight,
]
)
;
} | php | public function moveToRoot(int $itemId)
{
$menuId = $this->getMenuIdFor($itemId);
$weight = (int)$this
->database
->query(
"SELECT MAX(weight) + 1 FROM {umenu_item} WHERE (parent_id IS NULL OR parent_id = 0) AND menu_id = ?",
[$menuId]
)
->fetchField()
;
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = NULL, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':weight' => $weight,
]
)
;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L368-L391 |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.moveAfter | public function moveAfter(int $itemId, int $otherItemId)
{
list(,, $parentId, $weight) = $this->validateMove($itemId, $otherItemId);
if ($parentId) {
$this
->database
->query(
"UPDATE {umenu_item} SET weight = weight + 2 WHERE parent_id = :parent AND id <> :id AND weight >= :weight",
[
':id' => $otherItemId,
':parent' => $parentId,
':weight' => $weight,
]
)
;
} else {
$this
->database
->query(
"UPDATE {umenu_item} SET weight = weight + 2 WHERE (parent_id IS NULL OR parent_id = 0) AND id <> :id AND weight >= :weight",
[
':id' => $otherItemId,
':weight' => $weight,
]
)
;
}
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = :parent, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':parent' => $parentId,
':weight' => $weight + 1,
]
)
;
} | php | public function moveAfter(int $itemId, int $otherItemId)
{
list(,, $parentId, $weight) = $this->validateMove($itemId, $otherItemId);
if ($parentId) {
$this
->database
->query(
"UPDATE {umenu_item} SET weight = weight + 2 WHERE parent_id = :parent AND id <> :id AND weight >= :weight",
[
':id' => $otherItemId,
':parent' => $parentId,
':weight' => $weight,
]
)
;
} else {
$this
->database
->query(
"UPDATE {umenu_item} SET weight = weight + 2 WHERE (parent_id IS NULL OR parent_id = 0) AND id <> :id AND weight >= :weight",
[
':id' => $otherItemId,
':weight' => $weight,
]
)
;
}
$this
->database
->query(
"UPDATE {umenu_item} SET parent_id = :parent, weight = :weight WHERE id = :id",
[
':id' => $itemId,
':parent' => $parentId,
':weight' => $weight + 1,
]
)
;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L396-L436 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_attrs | private function get_attrs()
{
$this->attrs = new \stdClass;
foreach($this->dom_element->attributes as $name => $node)
{
$this->attrs->{strtolower($name)} = $node->nodeValue;
}
return $this;
} | php | private function get_attrs()
{
$this->attrs = new \stdClass;
foreach($this->dom_element->attributes as $name => $node)
{
$this->attrs->{strtolower($name)} = $node->nodeValue;
}
return $this;
} | Metodo que permite obtener todos atributos del elementos y convertirlos en un objeto stdClass.
@return self | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L64-L73 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_childs | private function get_childs()
{
$this->childs = new \PHPTools\PHPHtmlDom\Core\PHPHtmlDomList($this->dom_element->childNodes);
return $this;
} | php | private function get_childs()
{
$this->childs = new \PHPTools\PHPHtmlDom\Core\PHPHtmlDomList($this->dom_element->childNodes);
return $this;
} | Metodo que permite obtener los elementos hijos y convertirlos en un objeto lista PHPHtmlDomList.
@return self | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L79-L84 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_Text | private function get_Text()
{
$text_formatting = array('b','strong','em','i','small','strong','sub','sup','ins','del','mark','br','hr');
foreach ($this->dom_element->childNodes as $node)
{
if($node->nodeType == 3)
{
$this->set_text(trim($node->textContent));
$this->textFormatting.=$node->textContent;
}
else if($node->nodeType == 1 && !!in_array($node->tagName, $text_formatting))
{
if(!!in_array($node->tagName, ['br','hr']))
{
$this->textFormatting.= sprintf('<%s>',$node->tagName);
}
else
{
$tag = $node->tagName;
$attrs = $this->attrs_to_string($node->attributes);
$text = $node->textContent;
$this->textFormatting.= sprintf('<%1$s%2$s>%3$s</%1$s>',$tag,$attrs,$text);
}
}
}
return $this;
} | php | private function get_Text()
{
$text_formatting = array('b','strong','em','i','small','strong','sub','sup','ins','del','mark','br','hr');
foreach ($this->dom_element->childNodes as $node)
{
if($node->nodeType == 3)
{
$this->set_text(trim($node->textContent));
$this->textFormatting.=$node->textContent;
}
else if($node->nodeType == 1 && !!in_array($node->tagName, $text_formatting))
{
if(!!in_array($node->tagName, ['br','hr']))
{
$this->textFormatting.= sprintf('<%s>',$node->tagName);
}
else
{
$tag = $node->tagName;
$attrs = $this->attrs_to_string($node->attributes);
$text = $node->textContent;
$this->textFormatting.= sprintf('<%1$s%2$s>%3$s</%1$s>',$tag,$attrs,$text);
}
}
}
return $this;
} | Metodo que permite obtener el texto que se encuentra dentro del elemento.
@return self | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L90-L119 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.set_text | private function set_text($text)
{
if(!!$text)
{
if(!!$this->text)
{
if(!!is_array($this->text))
{
$this->text[] = $text;
}
else
{
$this->text = array($this->text,$text);
}
}
else
{
$this->text = $text;
}
}
return $this;
} | php | private function set_text($text)
{
if(!!$text)
{
if(!!$this->text)
{
if(!!is_array($this->text))
{
$this->text[] = $text;
}
else
{
$this->text = array($this->text,$text);
}
}
else
{
$this->text = $text;
}
}
return $this;
} | Metodo que permite definir e texto del elemento.
@param string $text Cden de texto a definirse.
@return self | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L126-L148 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.attrs_to_string | private function attrs_to_string($attrs)
{
$attrs_string ='';
foreach($attrs as $name => $node)
{
$attrs_string.= sprintf(' %s="%s"',$name,$node->nodeValue);
}
return $attrs_string;
} | php | private function attrs_to_string($attrs)
{
$attrs_string ='';
foreach($attrs as $name => $node)
{
$attrs_string.= sprintf(' %s="%s"',$name,$node->nodeValue);
}
return $attrs_string;
} | Este metodo permite concatenar un objeto de atributos en una sola cadena.
@param attay $attrs Arreglo de atributos.
@return string | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L155-L165 |
courtney-miles/schnoop-schema | src/MySQL/Routine/RoutineFunction.php | RoutineFunction.getCreateStatement | public function getCreateStatement()
{
$dropDDL = $setSqlMode = $createDDL = $revertSqlMode = '';
$functionName = $this->makeRoutineName();
if ($this->dropPolicy) {
switch ($this->dropPolicy) {
case self::DDL_DROP_POLICY_DROP:
$dropDDL = <<<SQL
DROP FUNCTION {$functionName}{$this->delimiter}
SQL;
break;
case self::DDL_DROP_POLICY_DROP_IF_EXISTS:
$dropDDL = <<<SQL
DROP FUNCTION IF EXISTS {$functionName}{$this->delimiter}
SQL;
break;
}
}
if ($this->hasSqlMode()) {
$prevDelimiter = $this->sqlMode->getDelimiter();
$this->sqlMode->setDelimiter($this->delimiter);
$setSqlMode = $this->sqlMode->getSetStatements();
$revertSqlMode = $this->sqlMode->getRestoreStatements();
$this->sqlMode->setDelimiter($prevDelimiter);
}
$paramsDDL = count($this->parameters) > 1
? "\n " . $this->makeParametersDDL("\n ") . "\n"
: $this->makeParametersDDL();
$functionSignature = "FUNCTION {$functionName} ({$paramsDDL})";
$createDDL .= 'CREATE ' . implode(
"\n",
array_filter(
[
(!empty($this->definer)) ? 'DEFINER = ' . $this->definer : null,
$functionSignature,
'RETURNS ' . $this->returns->getDDL(),
$this->makeCharacteristicsDDL(),
'BEGIN',
$this->body,
'END' . $this->delimiter
]
)
);
$createDDL = implode(
"\n",
array_filter(
[
$setSqlMode,
$dropDDL,
$createDDL,
$revertSqlMode
]
)
);
return $createDDL;
} | php | public function getCreateStatement()
{
$dropDDL = $setSqlMode = $createDDL = $revertSqlMode = '';
$functionName = $this->makeRoutineName();
if ($this->dropPolicy) {
switch ($this->dropPolicy) {
case self::DDL_DROP_POLICY_DROP:
$dropDDL = <<<SQL
DROP FUNCTION {$functionName}{$this->delimiter}
SQL;
break;
case self::DDL_DROP_POLICY_DROP_IF_EXISTS:
$dropDDL = <<<SQL
DROP FUNCTION IF EXISTS {$functionName}{$this->delimiter}
SQL;
break;
}
}
if ($this->hasSqlMode()) {
$prevDelimiter = $this->sqlMode->getDelimiter();
$this->sqlMode->setDelimiter($this->delimiter);
$setSqlMode = $this->sqlMode->getSetStatements();
$revertSqlMode = $this->sqlMode->getRestoreStatements();
$this->sqlMode->setDelimiter($prevDelimiter);
}
$paramsDDL = count($this->parameters) > 1
? "\n " . $this->makeParametersDDL("\n ") . "\n"
: $this->makeParametersDDL();
$functionSignature = "FUNCTION {$functionName} ({$paramsDDL})";
$createDDL .= 'CREATE ' . implode(
"\n",
array_filter(
[
(!empty($this->definer)) ? 'DEFINER = ' . $this->definer : null,
$functionSignature,
'RETURNS ' . $this->returns->getDDL(),
$this->makeCharacteristicsDDL(),
'BEGIN',
$this->body,
'END' . $this->delimiter
]
)
);
$createDDL = implode(
"\n",
array_filter(
[
$setSqlMode,
$dropDDL,
$createDDL,
$revertSqlMode
]
)
);
return $createDDL;
} | {@inheritdoc} | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Routine/RoutineFunction.php#L85-L149 |
courtney-miles/schnoop-schema | src/MySQL/Routine/RoutineFunction.php | RoutineFunction.makeParametersDDL | protected function makeParametersDDL($separator = " ")
{
$params = [];
foreach ($this->parameters as $parameter) {
$params[] = $parameter->getDDL();
}
return implode(',' . $separator, $params);
} | php | protected function makeParametersDDL($separator = " ")
{
$params = [];
foreach ($this->parameters as $parameter) {
$params[] = $parameter->getDDL();
}
return implode(',' . $separator, $params);
} | Make the portion of DDL for describing the parameters.
@param string $separator String to apply between parameters.
@return string Parameters DDL. | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Routine/RoutineFunction.php#L161-L170 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/MenuStrategy.php | MenuStrategy.show | public function show(ReadBlockInterface $block)
{
$nodes = $this->getNodes();
return $this->render(
'OpenOrchestraDisplayBundle:Block/Menu:tree.html.twig',
array(
'tree' => $nodes,
'id' => $block->getId(),
'class' => $block->getStyle(),
)
);
} | php | public function show(ReadBlockInterface $block)
{
$nodes = $this->getNodes();
return $this->render(
'OpenOrchestraDisplayBundle:Block/Menu:tree.html.twig',
array(
'tree' => $nodes,
'id' => $block->getId(),
'class' => $block->getStyle(),
)
);
} | Perform the show action for a block
@param ReadBlockInterface $block
@return Response | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/MenuStrategy.php#L70-L82 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/MenuStrategy.php | MenuStrategy.getNodes | protected function getNodes()
{
$language = $this->currentSiteManager->getSiteLanguage();
$siteId = $this->currentSiteManager->getSiteId();
$nodes = $this->nodeRepository->getMenuTree($language, $siteId);
return $this->getGrantedNodes($nodes);
} | php | protected function getNodes()
{
$language = $this->currentSiteManager->getSiteLanguage();
$siteId = $this->currentSiteManager->getSiteId();
$nodes = $this->nodeRepository->getMenuTree($language, $siteId);
return $this->getGrantedNodes($nodes);
} | Get Nodes to display
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/MenuStrategy.php#L89-L96 |
yii2lab/yii2-rbac | src/domain/repositories/disc/AssignmentRepository.php | AssignmentRepository.saveAssignments | protected function saveAssignments()
{
$assignmentData = [];
foreach ($this->assignments as $userId => $assignments) {
foreach ($assignments as $name => $assignment) {
/* @var $assignment Assignment */
$assignmentData[$userId][] = $assignment->roleName;
}
}
DiscHelper::saveToFile($assignmentData, $this->assignmentFile);
$this->domain->const->generateAll();
} | php | protected function saveAssignments()
{
$assignmentData = [];
foreach ($this->assignments as $userId => $assignments) {
foreach ($assignments as $name => $assignment) {
/* @var $assignment Assignment */
$assignmentData[$userId][] = $assignment->roleName;
}
}
DiscHelper::saveToFile($assignmentData, $this->assignmentFile);
$this->domain->const->generateAll();
} | Saves assignments data into persistent storage. | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/disc/AssignmentRepository.php#L197-L209 |
yii2lab/yii2-rbac | src/domain/repositories/disc/AssignmentRepository.php | AssignmentRepository.load | protected function load()
{
$this->assignments = [];
$assignments = DiscHelper::loadFromFile($this->assignmentFile);
$assignmentsMtime = @filemtime($this->assignmentFile);
foreach ($assignments as $userId => $roles) {
foreach ($roles as $role) {
$this->assignments[$userId][$role] = new Assignment([
'userId' => $userId,
'roleName' => $role,
'createdAt' => $assignmentsMtime,
]);
}
}
} | php | protected function load()
{
$this->assignments = [];
$assignments = DiscHelper::loadFromFile($this->assignmentFile);
$assignmentsMtime = @filemtime($this->assignmentFile);
foreach ($assignments as $userId => $roles) {
foreach ($roles as $role) {
$this->assignments[$userId][$role] = new Assignment([
'userId' => $userId,
'roleName' => $role,
'createdAt' => $assignmentsMtime,
]);
}
}
} | Loads authorization data from persistent storage. | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/disc/AssignmentRepository.php#L222-L237 |
tigron/skeleton-migrate | console/create.php | Migrate_Create.execute | protected function execute(InputInterface $input, OutputInterface $output) {
if (!file_exists(\Skeleton\Database\Migration\Config::$migration_directory)) {
throw new \Exception('Config::$migration_directory is not set to a valid directory');
}
$name = $input->getArgument('name');
if (strpos($name, "\\") !== false) {
$name = str_replace('\\', '/', $name);
}
if (strpos($name, '/') === false) {
$path = $this->create_project_migration($name);
} else {
$path = $this->create_package_migration($name);
}
$output->writeln('New migration template created at ' . $path );
} | php | protected function execute(InputInterface $input, OutputInterface $output) {
if (!file_exists(\Skeleton\Database\Migration\Config::$migration_directory)) {
throw new \Exception('Config::$migration_directory is not set to a valid directory');
}
$name = $input->getArgument('name');
if (strpos($name, "\\") !== false) {
$name = str_replace('\\', '/', $name);
}
if (strpos($name, '/') === false) {
$path = $this->create_project_migration($name);
} else {
$path = $this->create_package_migration($name);
}
$output->writeln('New migration template created at ' . $path );
} | Execute the Command
@access protected
@param InputInterface $input
@param OutputInterface $output | https://github.com/tigron/skeleton-migrate/blob/53b6ea56e928d4f925257949e59467d2d9cbafd4/console/create.php#L37-L55 |
tigron/skeleton-migrate | console/create.php | Migrate_Create.create_package_migration | private function create_package_migration($name) {
list($packagename, $name) = explode('/', $name);
$skeleton_packages = \Skeleton\Core\Skeleton::get_all();
$package = null;
foreach ($skeleton_packages as $skeleton_package) {
if ($skeleton_package->name == $packagename) {
$package = $skeleton_package;
}
}
if ($package === null) {
throw new \Exception('Package ' . $packagename . ' not found');
}
if (!file_exists($package->migration_path)) {
mkdir($package->migration_path);
}
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$namespace_parts = explode('-', $package->name);
foreach ($namespace_parts as $key => $namespace_part) {
$namespace_parts[$key] = ucfirst($namespace_part);
}
$namespace = implode('\\', $namespace_parts);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', 'namespace ' . $namespace . ';' . "\n", $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents($package->migration_path . '/' . $filename, $template);
return $package->migration_path . '/' . $filename;
} | php | private function create_package_migration($name) {
list($packagename, $name) = explode('/', $name);
$skeleton_packages = \Skeleton\Core\Skeleton::get_all();
$package = null;
foreach ($skeleton_packages as $skeleton_package) {
if ($skeleton_package->name == $packagename) {
$package = $skeleton_package;
}
}
if ($package === null) {
throw new \Exception('Package ' . $packagename . ' not found');
}
if (!file_exists($package->migration_path)) {
mkdir($package->migration_path);
}
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$namespace_parts = explode('-', $package->name);
foreach ($namespace_parts as $key => $namespace_part) {
$namespace_parts[$key] = ucfirst($namespace_part);
}
$namespace = implode('\\', $namespace_parts);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', 'namespace ' . $namespace . ';' . "\n", $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents($package->migration_path . '/' . $filename, $template);
return $package->migration_path . '/' . $filename;
} | Create package migration
@access private
@param string $name
@return string $path | https://github.com/tigron/skeleton-migrate/blob/53b6ea56e928d4f925257949e59467d2d9cbafd4/console/create.php#L64-L100 |
tigron/skeleton-migrate | console/create.php | Migrate_Create.create_project_migration | private function create_project_migration($name) {
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', '', $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents(\Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename, $template);
return \Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename;
} | php | private function create_project_migration($name) {
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', '', $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents(\Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename, $template);
return \Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename;
} | Create project migration
@access private
@param string $name
@return string $path | https://github.com/tigron/skeleton-migrate/blob/53b6ea56e928d4f925257949e59467d2d9cbafd4/console/create.php#L109-L121 |
digital-canvas/recurly-client-laravel | src/DigitalCanvas/Recurly/RecurlyServiceProvider.php | RecurlyServiceProvider.register | public function register()
{
$this->app['config']->package('digital-canvas/recurly-client-laravel', __DIR__.'/../../config');
Recurly_Client::$subdomain = $this->app['config']->get('recurly-client-laravel::config.subdomain', null);
Recurly_Client::$apiKey = $this->app['config']->get('recurly-client-laravel::config.apiKey', null);
Recurly_js::$privateKey = $this->app['config']->get('recurly-client-laravel::config.privateKey', null);
} | php | public function register()
{
$this->app['config']->package('digital-canvas/recurly-client-laravel', __DIR__.'/../../config');
Recurly_Client::$subdomain = $this->app['config']->get('recurly-client-laravel::config.subdomain', null);
Recurly_Client::$apiKey = $this->app['config']->get('recurly-client-laravel::config.apiKey', null);
Recurly_js::$privateKey = $this->app['config']->get('recurly-client-laravel::config.privateKey', null);
} | Register the service provider.
@return void | https://github.com/digital-canvas/recurly-client-laravel/blob/fa2dc60ea199a712b666faa0db57244098ef4392/src/DigitalCanvas/Recurly/RecurlyServiceProvider.php#L31-L37 |
LoggerEssentials/LoggerEssentials | src/Formatters/MessagePrefixFormatter.php | MessagePrefixFormatter.log | public function log($level, $message, array $context = array()) {
$parts = array();
if(is_array($this->caption)) {
$parts[] = join($this->concatenator, $this->caption);
} elseif(is_scalar($this->caption)) {
/** @var mixed $caption */
$caption = $this->caption;
$parts[] = (string) $caption;
}
$parts[] = $message;
$parts = array_filter($parts);
$newMessage = join($this->endingConcatenator, $parts);
$this->logger()->log($level, $newMessage, $context);
} | php | public function log($level, $message, array $context = array()) {
$parts = array();
if(is_array($this->caption)) {
$parts[] = join($this->concatenator, $this->caption);
} elseif(is_scalar($this->caption)) {
/** @var mixed $caption */
$caption = $this->caption;
$parts[] = (string) $caption;
}
$parts[] = $message;
$parts = array_filter($parts);
$newMessage = join($this->endingConcatenator, $parts);
$this->logger()->log($level, $newMessage, $context);
} | Logs with an arbitrary level.
@param mixed $level
@param string $message
@param array $context
@return void | https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Formatters/MessagePrefixFormatter.php#L35-L48 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.table | public static function table($table)
{
//as all calls will start with this function, first check if database connection has being established
if(Connect::getConn()==null){
//lets just return the object of the class in-case of connection error (developer will handle the rest)
return new static ;
}
self::$table = self::sanitize($table);
return new static;
} | php | public static function table($table)
{
//as all calls will start with this function, first check if database connection has being established
if(Connect::getConn()==null){
//lets just return the object of the class in-case of connection error (developer will handle the rest)
return new static ;
}
self::$table = self::sanitize($table);
return new static;
} | Sets the table on to which the various statements are executed.
@param $table
@return string | $this | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L34-L44 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.sanitize | private static function sanitize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} | php | private static function sanitize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} | Sanitizes the data input values
@param $data
@return string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L51-L57 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.select | public function select($columns = "")
{
//check if columns were passed as individual string parameters
if (func_num_args() > 1) {
$this->columns = $this->columnize(func_get_args());
} else {
//check if a simgle array of columns was passed(a hack)
$this->columns = is_array($columns) ? $this->columnize($columns)
: self::sanitize($columns);
}
return $this;
} | php | public function select($columns = "")
{
//check if columns were passed as individual string parameters
if (func_num_args() > 1) {
$this->columns = $this->columnize(func_get_args());
} else {
//check if a simgle array of columns was passed(a hack)
$this->columns = is_array($columns) ? $this->columnize($columns)
: self::sanitize($columns);
}
return $this;
} | Sets which columns to select
@param string $columns
@return $this | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L65-L78 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.where | public function where($params)
{
if (func_num_args() == 3) {
$operator = strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby = self::sanitize(func_get_arg(0))
.' '.$operator .' \''
. self::sanitize(func_get_arg(2)). '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby =self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)). '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | php | public function where($params)
{
if (func_num_args() == 3) {
$operator = strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby = self::sanitize(func_get_arg(0))
.' '.$operator .' \''
. self::sanitize(func_get_arg(2)). '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby =self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)). '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | Add conditional evaluation of where clause
$column, $operator = "", $value
@return $this | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L109-L133 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.orWhere | public function orWhere($param){
if (func_num_args() == 3) {
$operator =strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby .=' or '.self::sanitize(func_get_arg(0))
.' '. $operator . ' \''
. self::sanitize(func_get_arg(2)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby .= ' or '.self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | php | public function orWhere($param){
if (func_num_args() == 3) {
$operator =strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby .=' or '.self::sanitize(func_get_arg(0))
.' '. $operator . ' \''
. self::sanitize(func_get_arg(2)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby .= ' or '.self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | Adds condition for or in where clause
@see where
@param $param
@return $this | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L172-L195 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.orderBy | public function orderBy($column = '', $sort = 'desc')
{
$column=self::sanitize($column);
$sort=strtoupper(self::sanitize($sort));
/*check if the sort method passed is valid */
if (!(hash_equals('DESC',$sort) || hash_equals('ASC',$sort))){
static::$response["status"] = "error";
static::$response["response"] = "The sort order in order by clause is invalid";
static::$response['code'] = 6050;
return static::terminate(static::$response);
}
if ($this->order == null) {
$this->order = " ORDER BY $column $sort";
} else {
$this->order .= ", $column $sort";
}
return $this;
} | php | public function orderBy($column = '', $sort = 'desc')
{
$column=self::sanitize($column);
$sort=strtoupper(self::sanitize($sort));
/*check if the sort method passed is valid */
if (!(hash_equals('DESC',$sort) || hash_equals('ASC',$sort))){
static::$response["status"] = "error";
static::$response["response"] = "The sort order in order by clause is invalid";
static::$response['code'] = 6050;
return static::terminate(static::$response);
}
if ($this->order == null) {
$this->order = " ORDER BY $column $sort";
} else {
$this->order .= ", $column $sort";
}
return $this;
} | Set order in which the return results will be return
@param string $column :column to base the order on
@param string $sort :asc or desc
@return $this|mixed | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L203-L222 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.get | public function get($limit = 0, $offset = 0)
{
//check if there is an error
if (static::$response['status'] == "error") {
return static::terminate(static::$response);
}
//check if the limit is a number
if (!is_numeric($limit)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter limit should be numeric at function get()";
static::$response["code"] = 6000;
return static::terminate(static::$response);
}
//check if the offset is a number
if (!is_numeric($offset)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter offset should be numeric at function get()";
static::$response["code"] = 6001;
return static::terminate(static::$response);
}
$table_name = self::$table;
/* if no column passed as param, select all */
$columns = empty($this->columns) ? "*" : $this->columns;
$query = /** @lang text */
"SELECT {$columns} FROM {$table_name}";
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
if (!empty($limit)) {
$query = $query . ' LIMIT ' . $limit;
}
if (!empty($offset)) {
$query = $query . ' OFFSET ' . $offset;
}
return $this->fetch($query);
} | php | public function get($limit = 0, $offset = 0)
{
//check if there is an error
if (static::$response['status'] == "error") {
return static::terminate(static::$response);
}
//check if the limit is a number
if (!is_numeric($limit)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter limit should be numeric at function get()";
static::$response["code"] = 6000;
return static::terminate(static::$response);
}
//check if the offset is a number
if (!is_numeric($offset)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter offset should be numeric at function get()";
static::$response["code"] = 6001;
return static::terminate(static::$response);
}
$table_name = self::$table;
/* if no column passed as param, select all */
$columns = empty($this->columns) ? "*" : $this->columns;
$query = /** @lang text */
"SELECT {$columns} FROM {$table_name}";
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
if (!empty($limit)) {
$query = $query . ' LIMIT ' . $limit;
}
if (!empty($offset)) {
$query = $query . ' OFFSET ' . $offset;
}
return $this->fetch($query);
} | Fetch records form database
@param int $limit :optional limit of records to be retrieved
@param int $offset :the index which the record should be retrieved from
@return array|string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L245-L302 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.fetch | protected function fetch($sql)
{
try {
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute();
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$data = null;
// set the resulting array to associative
$stm->setFetchMode(PDO::FETCH_ASSOC);
foreach (new RecursiveArrayIterator($stm->fetchAll()) as $k => $v) {
$data[] = $v;
}
if ($data == null) {
static::$response["status"] = "success";
static::$response["response"] = Null;
static::$response['code'] = 300;
return static::terminate(static::$response);
}
static::$response["status"] = "success";
static::$response["response"] = $data;
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (PDOException $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | protected function fetch($sql)
{
try {
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute();
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$data = null;
// set the resulting array to associative
$stm->setFetchMode(PDO::FETCH_ASSOC);
foreach (new RecursiveArrayIterator($stm->fetchAll()) as $k => $v) {
$data[] = $v;
}
if ($data == null) {
static::$response["status"] = "success";
static::$response["response"] = Null;
static::$response['code'] = 300;
return static::terminate(static::$response);
}
static::$response["status"] = "success";
static::$response["response"] = $data;
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (PDOException $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | Executes a query that returns data
@param $sql
@return array|string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L310-L365 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.all | public function all()
{
$table = trim(self::$table);
if (!empty($table)) {
$query = /** @lang text */
"SELECT * FROM {$table}";
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
//execute the query and return the data or error message
return $this->fetch($query);
} else {
static::$response["status"] = "error";
static::$response["response"] = "Table name cannot be empty";
static::$response["code"] = 5000;
return static::terminate(static::$response);
}
} | php | public function all()
{
$table = trim(self::$table);
if (!empty($table)) {
$query = /** @lang text */
"SELECT * FROM {$table}";
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
//execute the query and return the data or error message
return $this->fetch($query);
} else {
static::$response["status"] = "error";
static::$response["response"] = "Table name cannot be empty";
static::$response["code"] = 5000;
return static::terminate(static::$response);
}
} | Fetch all data without limits or offset | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L370-L397 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.insert | public function insert($values)
{
try {
if (func_num_args() > 0 && !is_array($values)) {
$this->values = array_merge($this->values, self::sanitizeAV(func_get_args()));
} else if (is_array($values)) {
$this->values = self::sanitize($values);
} else {
static::$response["status"] = "error";
static::$response["response"] = "unrecognized parameter options in the insert values";
static::$response["code"] = 7004;
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return $this;
} | php | public function insert($values)
{
try {
if (func_num_args() > 0 && !is_array($values)) {
$this->values = array_merge($this->values, self::sanitizeAV(func_get_args()));
} else if (is_array($values)) {
$this->values = self::sanitize($values);
} else {
static::$response["status"] = "error";
static::$response["response"] = "unrecognized parameter options in the insert values";
static::$response["code"] = 7004;
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return $this;
} | Sets the values to be inserted
@param $values
@return $this|string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L413-L434 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.into | public function into($columns)
{
//if columns count does not match values count, throw an error.
$valuesCount = count($this->values);
$colStringCount = 0;
if (is_string($columns)) {
try {
$colStringCount = count(
explode(',', $columns)
);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized characters. Please refer to documentation on how to insert a record";
static::$response["code"] = 4001;
return static::terminate(static::$response);
}
}
if (func_num_args() > 1 && func_num_args() == $valuesCount) {
$this->columns = $this->columnize(func_get_args());
} else if (is_array($columns) && count($columns) == $valuesCount) {
$this->columns = $this->columnize($columns);
} else if ($colStringCount == $valuesCount) {
$this->columns = $columns;
} else {
static::$response["status"] = "error";
static::$response["response"] = "Columns count does not equal the values count";
static::$response['code'] = 4005;
return static::terminate(static::$response);
}
return $this->doInsert();
} | php | public function into($columns)
{
//if columns count does not match values count, throw an error.
$valuesCount = count($this->values);
$colStringCount = 0;
if (is_string($columns)) {
try {
$colStringCount = count(
explode(',', $columns)
);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized characters. Please refer to documentation on how to insert a record";
static::$response["code"] = 4001;
return static::terminate(static::$response);
}
}
if (func_num_args() > 1 && func_num_args() == $valuesCount) {
$this->columns = $this->columnize(func_get_args());
} else if (is_array($columns) && count($columns) == $valuesCount) {
$this->columns = $this->columnize($columns);
} else if ($colStringCount == $valuesCount) {
$this->columns = $columns;
} else {
static::$response["status"] = "error";
static::$response["response"] = "Columns count does not equal the values count";
static::$response['code'] = 4005;
return static::terminate(static::$response);
}
return $this->doInsert();
} | Sets the column to which the values will be inserted
@param $columns
@return string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L441-L477 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.doInsert | protected function doInsert()
{
//check if there is an error from previous function execution
if (static::$response["status"] == "error") {
return static::terminate(static::$response);
}
//convert each columns to ? parameter
$columnParam = array_map(function () {
return '?';
}, $this->values);
$sql = /** @lang sql */
'INSERT INTO ' . self::$table .
' (' . $this->columns .
') VALUES(' . implode(',', $columnParam) . ')';
$ext=array_map(function ($column){
return $column.'=VALUES('.$column.')';
},explode(',',$this->columns));
if($this->updateOrInsert){ //if update when duplicate is found is set to true
$sql.=' ON DUPLICATE KEY UPDATE '.implode(',',$ext);
}
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | protected function doInsert()
{
//check if there is an error from previous function execution
if (static::$response["status"] == "error") {
return static::terminate(static::$response);
}
//convert each columns to ? parameter
$columnParam = array_map(function () {
return '?';
}, $this->values);
$sql = /** @lang sql */
'INSERT INTO ' . self::$table .
' (' . $this->columns .
') VALUES(' . implode(',', $columnParam) . ')';
$ext=array_map(function ($column){
return $column.'=VALUES('.$column.')';
},explode(',',$this->columns));
if($this->updateOrInsert){ //if update when duplicate is found is set to true
$sql.=' ON DUPLICATE KEY UPDATE '.implode(',',$ext);
}
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | Performs the actual database insert
@return string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L483-L530 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.update | public function update($data)
{
if (is_array($data)) {
if ($this->isAssocStr($data)) {
$query = "UPDATE " . self::$table . ' SET ';
$this->values = array_values(array_map(function ($c) {
return self::sanitize($c);
}, $data));
$this->columns = array_keys($data);
$columnParam = array_map(function ($column) {
return self::sanitize($column) . '=?';
}, $this->columns);
$query .= $this->columnize($columnParam);
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
try {
$stm = Connect::getConn()->prepare($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"]=$e->getCode();
return self::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"]=$e->getCode();
return self::terminate(static::$response);
}
}
static::$response["status"] = "error";
static::$response["response"] = "Associative array expected in update function but sequential array passed";
static::$response["code"]=6501;
return self::terminate(static::$response);
}
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized data. Associative array expected in update function";
static::$response["code"]=6500;
return self::terminate(static::$response);
} | php | public function update($data)
{
if (is_array($data)) {
if ($this->isAssocStr($data)) {
$query = "UPDATE " . self::$table . ' SET ';
$this->values = array_values(array_map(function ($c) {
return self::sanitize($c);
}, $data));
$this->columns = array_keys($data);
$columnParam = array_map(function ($column) {
return self::sanitize($column) . '=?';
}, $this->columns);
$query .= $this->columnize($columnParam);
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
try {
$stm = Connect::getConn()->prepare($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"]=$e->getCode();
return self::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"]=$e->getCode();
return self::terminate(static::$response);
}
}
static::$response["status"] = "error";
static::$response["response"] = "Associative array expected in update function but sequential array passed";
static::$response["code"]=6501;
return self::terminate(static::$response);
}
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized data. Associative array expected in update function";
static::$response["code"]=6500;
return self::terminate(static::$response);
} | Warning: call the where clause first or all table data will be updated!
@param $data :associative array of column to value to be updated
@return string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L537-L600 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.isAssocStr | private function isAssocStr($array)
{
if(!is_array($array)){
return false;
}
for (reset($array); is_int(key($array));
next($array)) {
if (is_null(key($array)))
return false;
}
return true;
} | php | private function isAssocStr($array)
{
if(!is_array($array)){
return false;
}
for (reset($array); is_int(key($array));
next($array)) {
if (is_null(key($array)))
return false;
}
return true;
} | Function to check if an array is association or sequential
@param $array
@return bool | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L607-L618 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.delete | public function delete(){
$query= /** @lang text */
'DELETE FROM '.self::sanitize(static::$table);
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
try {
$this->exec($query);
static::$response["status"] = "success";
static::$response["response"] = 'success';
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} | php | public function delete(){
$query= /** @lang text */
'DELETE FROM '.self::sanitize(static::$table);
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
try {
$this->exec($query);
static::$response["status"] = "success";
static::$response["response"] = 'success';
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} | Warning: call this function after where clause or all data will be deleted
Deletes all or defined record(s) in the where clause
@return mixed | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L625-L649 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.exec | protected function exec($query)
{
try {
Connect::getConn()->exec($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return null;
} | php | protected function exec($query)
{
try {
Connect::getConn()->exec($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return null;
} | Executes a query that does not return any results
@param $query
@return null|string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L657-L669 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.valTable | private static function valTable(){
if(static::$table==null || ! is_string(static::$table)){
static::$response["status"] = "error";
static::$response["response"] = "check the table name provided";
static::$response["code"]=5000;
return self::terminate(static::$response);
}else{
static::$table=self::sanitize(static::$table);
}
return static::$table; //no effect
} | php | private static function valTable(){
if(static::$table==null || ! is_string(static::$table)){
static::$response["status"] = "error";
static::$response["response"] = "check the table name provided";
static::$response["code"]=5000;
return self::terminate(static::$response);
}else{
static::$table=self::sanitize(static::$table);
}
return static::$table; //no effect
} | Validate that the table name has been provided and is a string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L700-L711 |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.drop | public function drop()
{
static::valTable();
$sql = /** @lang text */
"DROP TABLE " . self::$table;
try {
$this->exec($sql);
static::$response["status"] = "success";
static::$response["response"] = "success";
return self::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | public function drop()
{
static::valTable();
$sql = /** @lang text */
"DROP TABLE " . self::$table;
try {
$this->exec($sql);
static::$response["status"] = "success";
static::$response["response"] = "success";
return self::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | Function to drop a table
@return string | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L717-L736 |
Etenil/assegai | src/assegai/modules/Module.php | Module.setDependencies | function setDependencies(\assegai\Server $server, ModuleContainer $modules)
{
$this->server = $server;
$this->modules = $modules;
} | php | function setDependencies(\assegai\Server $server, ModuleContainer $modules)
{
$this->server = $server;
$this->modules = $modules;
} | Default module constructor. Loads options into properties.
@param array $options is an associative array whose keys will
be mapped to properties for speed populating of the object. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/Module.php#L41-L45 |
Etenil/assegai | src/assegai/modules/Module.php | Module.getOption | protected function getOption($option, $default = false)
{
return isset($this->options[$option])? $this->options[$option] : $default;
} | php | protected function getOption($option, $default = false)
{
return isset($this->options[$option])? $this->options[$option] : $default;
} | Just a convenient wrapper to retrieve an option.
@param string $option is the option's name to retrieve.
@param mixed $default default value returned if option doesn't
exist. Default is false.
@return the value or default value. | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/Module.php#L76-L79 |
3ev/wordpress-core | src/Tev/Field/Model/PostField.php | PostField.getValue | public function getValue()
{
$val = $this->base['value'];
if (is_array($val)) {
$posts = array();
foreach ($val as $p) {
$posts[] = $this->postFactory->create($this->getPostObject($p));
}
return $posts;
} elseif (strlen($val)) {
return $this->postFactory->create($this->getPostObject($val));
} else {
if (isset($this->base['multiple']) && $this->base['multiple']) {
return array();
} else {
return null;
}
}
} | php | public function getValue()
{
$val = $this->base['value'];
if (is_array($val)) {
$posts = array();
foreach ($val as $p) {
$posts[] = $this->postFactory->create($this->getPostObject($p));
}
return $posts;
} elseif (strlen($val)) {
return $this->postFactory->create($this->getPostObject($val));
} else {
if (isset($this->base['multiple']) && $this->base['multiple']) {
return array();
} else {
return null;
}
}
} | Get a single post object or array of post objects.
If no posts are configured, returned will result will be an empty array
if this is a mutli-select, or null if not.
@return \Tev\Post\Model\Post|\Tev\Post\Model\Post[]|null | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/PostField.php#L43-L64 |
armazon/armazon | src/Armazon/Servidor/Swoole.php | Swoole.detectarNucleosCPU | private function detectarNucleosCPU()
{
$cantidad_cpu = 1;
if (is_file('/proc/cpuinfo')) {
$cpu_info = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpu_info, $matches);
$cantidad_cpu = count($matches[0]);
} else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) {
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process) {
fgets($process);
$cantidad_cpu = intval(fgets($process));
pclose($process);
}
} else {
$process = @popen('sysctl -a', 'rb');
if (false !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) {
$cantidad_cpu = intval($matches[1][0]);
}
pclose($process);
}
}
return $cantidad_cpu;
} | php | private function detectarNucleosCPU()
{
$cantidad_cpu = 1;
if (is_file('/proc/cpuinfo')) {
$cpu_info = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpu_info, $matches);
$cantidad_cpu = count($matches[0]);
} else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) {
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process) {
fgets($process);
$cantidad_cpu = intval(fgets($process));
pclose($process);
}
} else {
$process = @popen('sysctl -a', 'rb');
if (false !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) {
$cantidad_cpu = intval($matches[1][0]);
}
pclose($process);
}
}
return $cantidad_cpu;
} | Devuelve la cantidad de nucleos del CPU
@return int | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Servidor/Swoole.php#L17-L44 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.getPath | public static function getPath($data, $path)
{
$path = explode('/', $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data) || !isset($data[$part])) {
return null;
}
$data = $data[$part];
}
return $data;
} | php | public static function getPath($data, $path)
{
$path = explode('/', $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data) || !isset($data[$part])) {
return null;
}
$data = $data[$part];
}
return $data;
} | Gets a value from an array using a path syntax to retrieve nested data.
This method does not allow for keys that contain "/". You must traverse
the array manually or using something more advanced like JMESPath to
work with keys that contain "/".
// Get the bar key of a set of nested arrays.
// This is equivalent to $collection['foo']['baz']['bar'] but won't
// throw warnings for missing keys.
GuzzleHttp1\get_path($data, 'foo/baz/bar');
@param array $data Data to retrieve values from
@param string $path Path to traverse and retrieve a value from
@return mixed|null | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L31-L43 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.setPath | public static function setPath(&$data, $path, $value)
{
$queue = explode('/', $path);
// Optimization for simple sets.
if (count($queue) === 1) {
$data[$path] = $value;
return;
}
$current =& $data;
while (null !== ($key = array_shift($queue))) {
if (!is_array($current)) {
throw new \RuntimeException("Trying to setPath {$path}, but "
. "{$key} is set and is not an array");
} elseif (!$queue) {
if ($key == '[]') {
$current[] = $value;
} else {
$current[$key] = $value;
}
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = [];
$current =& $current[$key];
}
}
} | php | public static function setPath(&$data, $path, $value)
{
$queue = explode('/', $path);
// Optimization for simple sets.
if (count($queue) === 1) {
$data[$path] = $value;
return;
}
$current =& $data;
while (null !== ($key = array_shift($queue))) {
if (!is_array($current)) {
throw new \RuntimeException("Trying to setPath {$path}, but "
. "{$key} is set and is not an array");
} elseif (!$queue) {
if ($key == '[]') {
$current[] = $value;
} else {
$current[$key] = $value;
}
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = [];
$current =& $current[$key];
}
}
} | Set a value in a nested array key. Keys will be created as needed to set
the value.
This function does not support keys that contain "/" or "[]" characters
because these are special tokens used when traversing the data structure.
A value may be prepended to an existing array by using "[]" as the final
key of a path.
GuzzleHttp1\get_path($data, 'foo/baz'); // null
GuzzleHttp1\set_path($data, 'foo/baz/[]', 'a');
GuzzleHttp1\set_path($data, 'foo/baz/[]', 'b');
GuzzleHttp1\get_path($data, 'foo/baz');
// Returns ['a', 'b']
@param array $data Data to modify by reference
@param string $path Path to set
@param mixed $value Value to set at the key
@throws \RuntimeException when trying to setPath using a nested path
that travels through a scalar value. | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L67-L94 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.uriTemplate | public static function uriTemplate($template, array $variables)
{
if (function_exists('\\uri_template')) {
return \uri_template($template, $variables);
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new UriTemplate();
}
return $uriTemplate->expand($template, $variables);
} | php | public static function uriTemplate($template, array $variables)
{
if (function_exists('\\uri_template')) {
return \uri_template($template, $variables);
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new UriTemplate();
}
return $uriTemplate->expand($template, $variables);
} | Expands a URI template
@param string $template URI template
@param array $variables Template variables
@return string | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L104-L116 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.jsonDecode | public static function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
{
if ($json === '' || $json === null) {
return null;
}
static $jsonErrors = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
];
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
throw new \InvalidArgumentException(
'Unable to parse JSON data: '
. (isset($jsonErrors[$last])
? $jsonErrors[$last]
: 'Unknown error')
);
}
return $data;
} | php | public static function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
{
if ($json === '' || $json === null) {
return null;
}
static $jsonErrors = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
];
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
throw new \InvalidArgumentException(
'Unable to parse JSON data: '
. (isset($jsonErrors[$last])
? $jsonErrors[$last]
: 'Unknown error')
);
}
return $data;
} | Wrapper for JSON decode that implements error detection with helpful
error messages.
@param string $json JSON data to parse
@param bool $assoc When true, returned objects will be converted
into associative arrays.
@param int $depth User specified recursion depth.
@param int $options Bitmask of JSON decode options.
@return mixed
@throws \InvalidArgumentException if the JSON cannot be parsed.
@link http://www.php.net/manual/en/function.json-decode.php | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L132-L159 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.getDefaultUserAgent | public static function getDefaultUserAgent()
{
static $defaultAgent = '';
if (!$defaultAgent) {
$defaultAgent = 'Guzzle/' . ClientInterface::VERSION;
if (extension_loaded('curl')) {
$defaultAgent .= ' curl/' . curl_version()['version'];
}
$defaultAgent .= ' PHP/' . PHP_VERSION;
}
return $defaultAgent;
} | php | public static function getDefaultUserAgent()
{
static $defaultAgent = '';
if (!$defaultAgent) {
$defaultAgent = 'Guzzle/' . ClientInterface::VERSION;
if (extension_loaded('curl')) {
$defaultAgent .= ' curl/' . curl_version()['version'];
}
$defaultAgent .= ' PHP/' . PHP_VERSION;
}
return $defaultAgent;
} | Get the default User-Agent string to use with Guzzle
@return string | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L166-L178 |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.getDefaultHandler | public static function getDefaultHandler()
{
$default = $future = null;
if (extension_loaded('curl')) {
$config = [
'select_timeout' => getenv('GUZZLE_CURL_SELECT_TIMEOUT') ?: 1
];
if ($maxHandles = getenv('GUZZLE_CURL_MAX_HANDLES')) {
$config['max_handles'] = $maxHandles;
}
if (function_exists('curl_reset')) {
$default = new CurlHandler();
$future = new CurlMultiHandler($config);
} else {
$default = new CurlMultiHandler($config);
}
}
if (ini_get('allow_url_fopen')) {
$default = !$default
? new StreamHandler()
: Middleware::wrapStreaming($default, new StreamHandler());
} elseif (!$default) {
throw new \RuntimeException('Guzzle requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $future ? Middleware::wrapFuture($default, $future) : $default;
} | php | public static function getDefaultHandler()
{
$default = $future = null;
if (extension_loaded('curl')) {
$config = [
'select_timeout' => getenv('GUZZLE_CURL_SELECT_TIMEOUT') ?: 1
];
if ($maxHandles = getenv('GUZZLE_CURL_MAX_HANDLES')) {
$config['max_handles'] = $maxHandles;
}
if (function_exists('curl_reset')) {
$default = new CurlHandler();
$future = new CurlMultiHandler($config);
} else {
$default = new CurlMultiHandler($config);
}
}
if (ini_get('allow_url_fopen')) {
$default = !$default
? new StreamHandler()
: Middleware::wrapStreaming($default, new StreamHandler());
} elseif (!$default) {
throw new \RuntimeException('Guzzle requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $future ? Middleware::wrapFuture($default, $future) : $default;
} | Create a default handler to use based on the environment
@throws \RuntimeException if no viable Handler is available. | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L185-L214 |
fxpio/fxp-gluon | Block/Extension/AbstractTableColumnPagerExtension.php | AbstractTableColumnPagerExtension.buildView | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
$attr = $view->vars['label_attr'];
if ($options['sortable']) {
$attr['data-table-pager-sortable'] = 'true';
}
$view->vars = array_replace($view->vars, [
'sortable' => $options['sortable'],
'label_attr' => $attr,
]);
if ($options['sortable'] && !isset($attr['data-table-sort'])) {
$view->vars['value'] = \is_string($view->vars['value']) ? $view->vars['value'] : '';
$view->vars['value'] .= '<i class="table-sort-icon fa"></i>';
}
} | php | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
$attr = $view->vars['label_attr'];
if ($options['sortable']) {
$attr['data-table-pager-sortable'] = 'true';
}
$view->vars = array_replace($view->vars, [
'sortable' => $options['sortable'],
'label_attr' => $attr,
]);
if ($options['sortable'] && !isset($attr['data-table-sort'])) {
$view->vars['value'] = \is_string($view->vars['value']) ? $view->vars['value'] : '';
$view->vars['value'] .= '<i class="table-sort-icon fa"></i>';
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/AbstractTableColumnPagerExtension.php#L29-L46 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.parseDirectory | final public function parseDirectory($rootDirectory, $relativePath, $translations = null, $subParsersFilter = false, $exclude3rdParty = true)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$dir = (string) $rootDirectory;
if ($dir !== '') {
$dir = @realpath($rootDirectory);
if (($dir === false) || (!is_dir($dir))) {
$dir = '';
} else {
$dir = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/');
}
}
if ($dir === '') {
throw new \Exception("Unable to find the directory $rootDirectory");
}
if (!@is_readable($dir)) {
throw new \Exception("Directory not readable: $dir");
}
$dirRel = is_string($relativePath) ? trim(str_replace(DIRECTORY_SEPARATOR, '/', $relativePath), '/') : '';
$this->parseDirectoryDo($translations, $dir, $dirRel, $subParsersFilter, $exclude3rdParty);
return $translations;
} | php | final public function parseDirectory($rootDirectory, $relativePath, $translations = null, $subParsersFilter = false, $exclude3rdParty = true)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$dir = (string) $rootDirectory;
if ($dir !== '') {
$dir = @realpath($rootDirectory);
if (($dir === false) || (!is_dir($dir))) {
$dir = '';
} else {
$dir = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/');
}
}
if ($dir === '') {
throw new \Exception("Unable to find the directory $rootDirectory");
}
if (!@is_readable($dir)) {
throw new \Exception("Directory not readable: $dir");
}
$dirRel = is_string($relativePath) ? trim(str_replace(DIRECTORY_SEPARATOR, '/', $relativePath), '/') : '';
$this->parseDirectoryDo($translations, $dir, $dirRel, $subParsersFilter, $exclude3rdParty);
return $translations;
} | Extracts translations from a directory.
@param string $rootDirectory The base directory where we start looking translations from
@param string $relativePath The relative path (translations references will be prepended with this path)
@param \Gettext\Translations|null=null $translations The translations object where the translatable strings will be added (if null we'll create a new Translations instance)
@param array|false $subParsersFilter A list of sub-parsers handles (set to false to use all the sub-parsers)
@param bool $exclude3rdParty Exclude concrete5 3rd party directories (namely directories called 'vendor' and '3rdparty')
@throws \Exception Throws an \Exception in case of errors
@return \Gettext\Translations
@example If you want to parse the concrete5 core directory, you should call `parseDirectory('PathToTheWebroot/concrete', 'concrete')`
@example If you want to parse a concrete5 package, you should call `parseDirectory('PathToThePackageFolder', 'packages/YourPackageHandle')` | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L74-L98 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.parseRunningConcrete5 | final public function parseRunningConcrete5($translations = null, $subParsersFilter = false)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$runningVersion = '';
if (defined('\C5_EXECUTE') && defined('\APP_VERSION') && is_string(\APP_VERSION)) {
$runningVersion = \APP_VERSION;
}
if ($runningVersion === '') {
throw new \Exception('Unable to determine the current working directory');
}
$this->parseRunningConcrete5Do($translations, $runningVersion, $subParsersFilter);
return $translations;
} | php | final public function parseRunningConcrete5($translations = null, $subParsersFilter = false)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$runningVersion = '';
if (defined('\C5_EXECUTE') && defined('\APP_VERSION') && is_string(\APP_VERSION)) {
$runningVersion = \APP_VERSION;
}
if ($runningVersion === '') {
throw new \Exception('Unable to determine the current working directory');
}
$this->parseRunningConcrete5Do($translations, $runningVersion, $subParsersFilter);
return $translations;
} | Extracts translations from a running concrete5 instance.
@param \Gettext\Translations|null=null $translations The translations object where the translatable strings will be added (if null we'll create a new Translations instance)
@param array|false $subParsersFilter A list of sub-parsers handles (set to false to use all the sub-parsers)
@throws \Exception Throws an \Exception in case of errors
@return \Gettext\Translations | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L134-L149 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.getDirectoryStructure | final protected static function getDirectoryStructure($rootDirectory, $exclude3rdParty = true)
{
$rootDirectory = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $rootDirectory), '/');
if (!isset(self::$cache[__FUNCTION__])) {
self::$cache[__FUNCTION__] = array();
}
$cacheKey = $rootDirectory.'*'.($exclude3rdParty ? '1' : '0');
if (!isset(self::$cache[__FUNCTION__][$cacheKey])) {
self::$cache[__FUNCTION__][$cacheKey] = static::getDirectoryStructureDo('', $rootDirectory, $exclude3rdParty);
}
return self::$cache[__FUNCTION__][$cacheKey];
} | php | final protected static function getDirectoryStructure($rootDirectory, $exclude3rdParty = true)
{
$rootDirectory = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $rootDirectory), '/');
if (!isset(self::$cache[__FUNCTION__])) {
self::$cache[__FUNCTION__] = array();
}
$cacheKey = $rootDirectory.'*'.($exclude3rdParty ? '1' : '0');
if (!isset(self::$cache[__FUNCTION__][$cacheKey])) {
self::$cache[__FUNCTION__][$cacheKey] = static::getDirectoryStructureDo('', $rootDirectory, $exclude3rdParty);
}
return self::$cache[__FUNCTION__][$cacheKey];
} | Returns the directory structure underneath a given directory.
@param string $rootDirectory The root directory
@param bool $exclude3rdParty=true Exclude concrete5 3rd party directories (namely directories called 'vendor' and '3rdparty')
@return array | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L189-L201 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.getDirectoryStructureDo | final private static function getDirectoryStructureDo($relativePath, $rootDirectory, $exclude3rdParty)
{
$thisRoot = $rootDirectory;
if ($relativePath !== '') {
$thisRoot .= '/'.$relativePath;
}
$subDirs = array();
$hDir = @opendir($thisRoot);
if ($hDir === false) {
throw new \Exception("Unable to open directory $rootDirectory");
}
while (($entry = @readdir($hDir)) !== false) {
if ($entry[0] === '.') {
continue;
}
$fullPath = $thisRoot.'/'.$entry;
if (!is_dir($fullPath)) {
continue;
}
if ($exclude3rdParty) {
if (($entry === 'vendor') || preg_match('%/libraries/3rdparty$%', $fullPath)) {
continue;
}
}
$subDirs[] = $entry;
}
@closedir($hDir);
$result = array();
foreach ($subDirs as $subDir) {
$rel = ($relativePath === '') ? $subDir : "$relativePath/$subDir";
$result = array_merge($result, static::getDirectoryStructureDo($rel, $rootDirectory, $exclude3rdParty));
$result[] = $rel;
}
return $result;
} | php | final private static function getDirectoryStructureDo($relativePath, $rootDirectory, $exclude3rdParty)
{
$thisRoot = $rootDirectory;
if ($relativePath !== '') {
$thisRoot .= '/'.$relativePath;
}
$subDirs = array();
$hDir = @opendir($thisRoot);
if ($hDir === false) {
throw new \Exception("Unable to open directory $rootDirectory");
}
while (($entry = @readdir($hDir)) !== false) {
if ($entry[0] === '.') {
continue;
}
$fullPath = $thisRoot.'/'.$entry;
if (!is_dir($fullPath)) {
continue;
}
if ($exclude3rdParty) {
if (($entry === 'vendor') || preg_match('%/libraries/3rdparty$%', $fullPath)) {
continue;
}
}
$subDirs[] = $entry;
}
@closedir($hDir);
$result = array();
foreach ($subDirs as $subDir) {
$rel = ($relativePath === '') ? $subDir : "$relativePath/$subDir";
$result = array_merge($result, static::getDirectoryStructureDo($rel, $rootDirectory, $exclude3rdParty));
$result[] = $rel;
}
return $result;
} | Helper function called by {@link \C5TL\Parser::getDirectoryStructure()}.
@param string $relativePath
@param string $rootDirectory
@param bool $exclude3rdParty
@throws \Exception
@return array[string] | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L214-L249 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.getAllParsers | final public static function getAllParsers()
{
$result = array();
$dir = __DIR__.'/Parser';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches)) {
$fqClassName = '\\'.__NAMESPACE__.'\\Parser\\'.$matches[1];
$result[] = new $fqClassName();
}
}
}
return $result;
} | php | final public static function getAllParsers()
{
$result = array();
$dir = __DIR__.'/Parser';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches)) {
$fqClassName = '\\'.__NAMESPACE__.'\\Parser\\'.$matches[1];
$result[] = new $fqClassName();
}
}
}
return $result;
} | Retrieves all the available parsers.
@return array[\C5TL\Parser] | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L256-L271 |
mlocati/concrete5-translation-library | src/Parser.php | Parser.handlifyString | final public static function handlifyString($string)
{
$string = preg_replace('/\W+/', '_', $string);
$string = preg_replace('/([A-Z])/', '_$1', $string);
$string = strtolower($string);
$string = preg_replace('/_+/', '_', trim($string, '_'));
return $string;
} | php | final public static function handlifyString($string)
{
$string = preg_replace('/\W+/', '_', $string);
$string = preg_replace('/([A-Z])/', '_$1', $string);
$string = strtolower($string);
$string = preg_replace('/_+/', '_', trim($string, '_'));
return $string;
} | Concatenates words with an underscore and lowercases them (eg from 'HiThere' or 'HiThere' to 'hi_there'). Upper case words are prepended with an underscore too.
@param string $string
@return string
@internal | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L317-L325 |
CodeCollab/Http | src/Cookie/Cookie.php | Cookie.send | public function send()
{
setcookie(
$this->name,
$this->value,
(int) $this->expire->format('U'),
$this->path,
$this->domain,
$this->secure,
$this->httpOnly
);
} | php | public function send()
{
setcookie(
$this->name,
$this->value,
(int) $this->expire->format('U'),
$this->path,
$this->domain,
$this->secure,
$this->httpOnly
);
} | Sends the cookie header | https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Cookie/Cookie.php#L85-L96 |
luoxiaojun1992/lb_framework | components/Route.php | Route.triggerAopEvent | protected static function triggerAopEvent(
$controller_id,
$action_name,
$request = null,
$response = null
) {
$context = [
'controller_id' => $controller_id,
'action_id' => $action_name,
];
if ($request) {
$context['request'] = $request;
}
if ($response) {
$context['response'] = $response;
}
Lb::app()->trigger(
Event::AOP_EVENT . '_' . implode('@', [$controller_id, $action_name]),
new AopEvent($context)
);
Lb::app()->trigger(
Event::REQUEST_EVENT,
new RequestEvent($context)
);
} | php | protected static function triggerAopEvent(
$controller_id,
$action_name,
$request = null,
$response = null
) {
$context = [
'controller_id' => $controller_id,
'action_id' => $action_name,
];
if ($request) {
$context['request'] = $request;
}
if ($response) {
$context['response'] = $response;
}
Lb::app()->trigger(
Event::AOP_EVENT . '_' . implode('@', [$controller_id, $action_name]),
new AopEvent($context)
);
Lb::app()->trigger(
Event::REQUEST_EVENT,
new RequestEvent($context)
);
} | Trigger AOP Event
@param $controller_id
@param $action_name
@param null $request
@param null $response | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Route.php#L295-L320 |
vincenttouzet/BootstrapFormBundle | Form/DataTransformer/DateRangeToStringTransformer.php | DateRangeToStringTransformer.transform | public function transform($value)
{
if ( $value ) {
$from = '';
if ( $value->getFrom() ) {
$from = $value->getFrom()->format('Y-m-d');
}
$to = '';
if ( $value->getTo() ) {
$to = $value->getTo()->format('Y-m-d');
}
return sprintf(
'%s%s%s',
$from,
$this->dateSeparator,
$to
);
}
} | php | public function transform($value)
{
if ( $value ) {
$from = '';
if ( $value->getFrom() ) {
$from = $value->getFrom()->format('Y-m-d');
}
$to = '';
if ( $value->getTo() ) {
$to = $value->getTo()->format('Y-m-d');
}
return sprintf(
'%s%s%s',
$from,
$this->dateSeparator,
$to
);
}
} | Transforms a DateRange into a string.
@param DateRange $value DateRange value.
@return string string value. | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/DataTransformer/DateRangeToStringTransformer.php#L48-L66 |
vincenttouzet/BootstrapFormBundle | Form/DataTransformer/DateRangeToStringTransformer.php | DateRangeToStringTransformer.reverseTransform | public function reverseTransform($value)
{
$parts = explode($this->dateSeparator, $value);
$from = isset($parts[0]) ? $parts[0] : null;
$to = isset($parts[1]) ? $parts[1] : null;
return new DAteRange($from, $to);
} | php | public function reverseTransform($value)
{
$parts = explode($this->dateSeparator, $value);
$from = isset($parts[0]) ? $parts[0] : null;
$to = isset($parts[1]) ? $parts[1] : null;
return new DAteRange($from, $to);
} | Transforms a string into a DateRange.
@param string $value String value.
@return DateRange DateRange value. | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/DataTransformer/DateRangeToStringTransformer.php#L75-L81 |
eloquent/endec | src/Base32/AbstractBase32DecodeTransform.php | AbstractBase32DecodeTransform.transform | public function transform($data, &$context, $isEnd = false)
{
$paddedLength = strlen($data);
$data = rtrim($data, '=');
$length = strlen($data);
$consumed = intval($length / 8) * 8;
$index = 0;
$output = '';
try {
while ($index < $consumed) {
$output .= $this->map8(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++)
);
}
if (($isEnd || $paddedLength > $length) && $consumed !== $length) {
$remaining = $length - $consumed;
$consumed = $length;
if (2 === $remaining) {
$output .= $this->map2(
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (4 === $remaining) {
$output .= $this->map4(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (5 === $remaining) {
$output .= $this->map5(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (7 === $remaining) {
$output .= $this->map7(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} else {
return array(
'',
0,
new InvalidEncodedDataException($this->key(), $data)
);
}
}
} catch (EncodingExceptionInterface $error) {
return array('', 0, $error);
}
return array($output, $consumed + $paddedLength - $length, null);
} | php | public function transform($data, &$context, $isEnd = false)
{
$paddedLength = strlen($data);
$data = rtrim($data, '=');
$length = strlen($data);
$consumed = intval($length / 8) * 8;
$index = 0;
$output = '';
try {
while ($index < $consumed) {
$output .= $this->map8(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++)
);
}
if (($isEnd || $paddedLength > $length) && $consumed !== $length) {
$remaining = $length - $consumed;
$consumed = $length;
if (2 === $remaining) {
$output .= $this->map2(
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (4 === $remaining) {
$output .= $this->map4(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (5 === $remaining) {
$output .= $this->map5(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} elseif (7 === $remaining) {
$output .= $this->map7(
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index++),
$this->mapByte($data, $index)
);
} else {
return array(
'',
0,
new InvalidEncodedDataException($this->key(), $data)
);
}
}
} catch (EncodingExceptionInterface $error) {
return array('', 0, $error);
}
return array($output, $consumed + $paddedLength - $length, null);
} | Transform the supplied data.
This method may transform only part of the supplied data. The return
value includes information about how much data was actually consumed. The
transform can be forced to consume all data by passing a boolean true as
the $isEnd argument.
The $context argument will initially be null, but any value assigned to
this variable will persist until the stream transformation is complete.
It can be used as a place to store state, such as a buffer.
It is guaranteed that this method will be called with $isEnd = true once,
and only once, at the end of the stream transformation.
@param string $data The data to transform.
@param mixed &$context An arbitrary context value.
@param boolean $isEnd True if all supplied data must be transformed.
@return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base32/AbstractBase32DecodeTransform.php#L47-L117 |
chilimatic/chilimatic-framework | lib/database/sql/orm/EntityObjectStorage.php | EntityObjectStorage.getAsArray | public function getAsArray($columName = null)
{
if ($columName) {
$this->rewind();
$obj = $this->current();
if ($obj) {
if (!$this->reflection) {
$this->reflection = new \ReflectionClass($this->current());
}
if ($this->columMap === null) {
$this->columMap = [];
foreach ($this->reflection->getProperties() as $property) {
$this->columMap[$property->getName()] = $property;
}
}
}
}
$this->rewind();
$arr = [];
while ($this->valid()) {
if ($columName && !empty($this->columMap[$columName])) {
$obj = $this->current();
/**
* @var \ReflectionProperty $test
*/
$this->columMap[$columName]->setAccessible(true);
$arr[] = $this->columMap[$columName]->getValue($obj);
} else {
$arr[] = $this->current();
}
$this->next();
}
return $arr;
} | php | public function getAsArray($columName = null)
{
if ($columName) {
$this->rewind();
$obj = $this->current();
if ($obj) {
if (!$this->reflection) {
$this->reflection = new \ReflectionClass($this->current());
}
if ($this->columMap === null) {
$this->columMap = [];
foreach ($this->reflection->getProperties() as $property) {
$this->columMap[$property->getName()] = $property;
}
}
}
}
$this->rewind();
$arr = [];
while ($this->valid()) {
if ($columName && !empty($this->columMap[$columName])) {
$obj = $this->current();
/**
* @var \ReflectionProperty $test
*/
$this->columMap[$columName]->setAccessible(true);
$arr[] = $this->columMap[$columName]->getValue($obj);
} else {
$arr[] = $this->current();
}
$this->next();
}
return $arr;
} | @param string $columName
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/orm/EntityObjectStorage.php#L23-L61 |
cyberspectrum/i18n-contao | src/Extractor/TableExtractor.php | TableExtractor.keys | public function keys(array $row): \Traversable
{
if (null === $content = $this->decode($row)) {
return;
}
foreach (array_keys($content) as $rowIndex) {
foreach (array_keys($content[$rowIndex]) as $col) {
if (null === $content[$rowIndex][$col]) {
continue;
}
yield 'row' . $rowIndex . '.col' . $col;
}
}
} | php | public function keys(array $row): \Traversable
{
if (null === $content = $this->decode($row)) {
return;
}
foreach (array_keys($content) as $rowIndex) {
foreach (array_keys($content[$rowIndex]) as $col) {
if (null === $content[$rowIndex][$col]) {
continue;
}
yield 'row' . $rowIndex . '.col' . $col;
}
}
} | {@inheritDoc} | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/TableExtractor.php#L65-L79 |
cyberspectrum/i18n-contao | src/Extractor/TableExtractor.php | TableExtractor.get | public function get(string $path, array $row): ?string
{
if (null === $content = $this->decode($row)) {
return null;
}
$pathChunks = explode('.', $path);
if (0 !== strpos($pathChunks[0], 'row')) {
throw new \InvalidArgumentException('Path ' . $path . ' first part must be row, found: ' . $pathChunks[0]);
}
if (0 !== strpos($pathChunks[1], 'col')) {
throw new \InvalidArgumentException('Path ' . $path . ' second part must be col, found: ' . $pathChunks[1]);
}
if ($value = ($content[(int) substr($pathChunks[0], 3)][(int) substr($pathChunks[1], 3)] ?? null)) {
return $value;
}
return null;
} | php | public function get(string $path, array $row): ?string
{
if (null === $content = $this->decode($row)) {
return null;
}
$pathChunks = explode('.', $path);
if (0 !== strpos($pathChunks[0], 'row')) {
throw new \InvalidArgumentException('Path ' . $path . ' first part must be row, found: ' . $pathChunks[0]);
}
if (0 !== strpos($pathChunks[1], 'col')) {
throw new \InvalidArgumentException('Path ' . $path . ' second part must be col, found: ' . $pathChunks[1]);
}
if ($value = ($content[(int) substr($pathChunks[0], 3)][(int) substr($pathChunks[1], 3)] ?? null)) {
return $value;
}
return null;
} | {@inheritDoc}
@throws \InvalidArgumentException When the path does not contain valid row and column chunks. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/TableExtractor.php#L86-L105 |
cyberspectrum/i18n-contao | src/Extractor/TableExtractor.php | TableExtractor.set | public function set(string $path, array &$row, string $value = null): void
{
if (null === $content = $this->decode($row)) {
$content = [];
}
$pathChunks = explode('.', $path);
if (0 !== strpos($pathChunks[0], 'row')) {
throw new \InvalidArgumentException('Path ' . $path . ' first part must be row, found: ' . $pathChunks[0]);
}
if (0 !== strpos($pathChunks[1], 'col')) {
throw new \InvalidArgumentException('Path ' . $path . ' second part must be col, found: ' . $pathChunks[1]);
}
$rowIndex = (int) substr($pathChunks[0], 3);
if (!array_key_exists($rowIndex, $content)) {
$content[$rowIndex] = [];
}
$colIndex = (int) substr($pathChunks[1], 3);
$content[$rowIndex][$colIndex] = $value;
$row[$this->name()] = serialize($content);
} | php | public function set(string $path, array &$row, string $value = null): void
{
if (null === $content = $this->decode($row)) {
$content = [];
}
$pathChunks = explode('.', $path);
if (0 !== strpos($pathChunks[0], 'row')) {
throw new \InvalidArgumentException('Path ' . $path . ' first part must be row, found: ' . $pathChunks[0]);
}
if (0 !== strpos($pathChunks[1], 'col')) {
throw new \InvalidArgumentException('Path ' . $path . ' second part must be col, found: ' . $pathChunks[1]);
}
$rowIndex = (int) substr($pathChunks[0], 3);
if (!array_key_exists($rowIndex, $content)) {
$content[$rowIndex] = [];
}
$colIndex = (int) substr($pathChunks[1], 3);
$content[$rowIndex][$colIndex] = $value;
$row[$this->name()] = serialize($content);
} | {@inheritDoc}
@throws \InvalidArgumentException When the path does not contain valid row and column chunks. | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/TableExtractor.php#L112-L135 |
cyberspectrum/i18n-contao | src/Extractor/TableExtractor.php | TableExtractor.decode | private function decode(array $row): ?array
{
if (null === ($encoded = $row[$this->name()])) {
return null;
}
if (false === ($decoded = unserialize($encoded, ['allowed_classes' => false]))) {
return null;
}
if (!\is_array($decoded)) {
return null;
}
return $decoded;
} | php | private function decode(array $row): ?array
{
if (null === ($encoded = $row[$this->name()])) {
return null;
}
if (false === ($decoded = unserialize($encoded, ['allowed_classes' => false]))) {
return null;
}
if (!\is_array($decoded)) {
return null;
}
return $decoded;
} | Decode the row value.
@param array $row The row.
@return array|null | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/TableExtractor.php#L144-L158 |
fxpio/fxp-gluon | Block/Extension/AbstractPullExtension.php | AbstractPullExtension.buildView | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if (\is_array($options['pull'])) {
foreach ($options['pull'] as $pull) {
BlockUtil::addAttributeClass($view, $options['pull_prefix'].'pull-'.$pull);
}
}
} | php | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
if (\is_array($options['pull'])) {
foreach ($options['pull'] as $pull) {
BlockUtil::addAttributeClass($view, $options['pull_prefix'].'pull-'.$pull);
}
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/AbstractPullExtension.php#L32-L39 |
fxpio/fxp-gluon | Block/Extension/AbstractPullExtension.php | AbstractPullExtension.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'pull' => null,
'pull_prefix' => null,
]);
$resolver->setAllowedTypes('pull', ['null', 'string', 'array']);
$resolver->setAllowedTypes('pull_prefix', ['null', 'string']);
$resolver->setNormalizer('pull', function (Options $options, $value) {
if (\is_string($value)) {
$value = [$value];
}
if (\is_array($value)) {
foreach ($value as $pull) {
if (!\in_array($pull, ['top', 'right'])) {
$msg = 'The option "pull" with value "%s" is invalid';
throw new InvalidOptionsException(sprintf($msg, $pull));
}
}
}
return $value;
});
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'pull' => null,
'pull_prefix' => null,
]);
$resolver->setAllowedTypes('pull', ['null', 'string', 'array']);
$resolver->setAllowedTypes('pull_prefix', ['null', 'string']);
$resolver->setNormalizer('pull', function (Options $options, $value) {
if (\is_string($value)) {
$value = [$value];
}
if (\is_array($value)) {
foreach ($value as $pull) {
if (!\in_array($pull, ['top', 'right'])) {
$msg = 'The option "pull" with value "%s" is invalid';
throw new InvalidOptionsException(sprintf($msg, $pull));
}
}
}
return $value;
});
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Extension/AbstractPullExtension.php#L44-L70 |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.render | public function render()
{
$output = $this->each(function($tag) {
/** @var Tag $tag */
return $tag->render();
});
return implode('', $output->toArray());
} | php | public function render()
{
$output = $this->each(function($tag) {
/** @var Tag $tag */
return $tag->render();
});
return implode('', $output->toArray());
} | Render tag elements
@return string | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L56-L64 |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.getNextItem | private function getNextItem(Tag $item, $items)
{
$currentItem = $items[0];
while ($currentItem !== null and $currentItem !== $item) {
$currentItem = next($items);
}
$next = next($items);
return $next !== false ? $next : null;
} | php | private function getNextItem(Tag $item, $items)
{
$currentItem = $items[0];
while ($currentItem !== null and $currentItem !== $item) {
$currentItem = next($items);
}
$next = next($items);
return $next !== false ? $next : null;
} | Get next item from items array
@param Tag $item
@param array $items
@return Tag|null | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L78-L89 |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.remove | public function remove($tag)
{
if ($this->count() == 0) {
return [$this, null];
}
$deleted = null;
foreach ($this->items as $key => $element) {
if ($element === $tag) {
$this->forget($key);
$deleted = $tag;
break;
}
}
return [$this, $deleted];
} | php | public function remove($tag)
{
if ($this->count() == 0) {
return [$this, null];
}
$deleted = null;
foreach ($this->items as $key => $element) {
if ($element === $tag) {
$this->forget($key);
$deleted = $tag;
break;
}
}
return [$this, $deleted];
} | Remove tag element from collection
@param Tag $tag
@return array | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L98-L117 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/Bootstrap.php | Bootstrap.buildServiceContainer | private function buildServiceContainer() {
$serviceConfigs = $this->appSetting->getServices();
if (is_null($serviceConfigs)) {
$serviceConfigs = [];
}
$this->container = new ServiceContainer($serviceConfigs);
} | php | private function buildServiceContainer() {
$serviceConfigs = $this->appSetting->getServices();
if (is_null($serviceConfigs)) {
$serviceConfigs = [];
}
$this->container = new ServiceContainer($serviceConfigs);
} | 构造服务容器 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Bootstrap.php#L66-L74 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/Bootstrap.php | Bootstrap.loadExtensions | private function loadExtensions() {
$extensions = $this->appSetting->getExtensions();
if (empty($extensions)) {
return;
}
foreach ($extensions as $extensionClass) {
$extension = new $extensionClass();
if (!$extension instanceof ExtensionInterface) {
throw new Exception("“{$extensionClass}”不是“ExtensionInterface”的实例");
}
//注入AppContext
$extension->setAppContext($this->appContext);
//加载扩展
$extension->load();
}
} | php | private function loadExtensions() {
$extensions = $this->appSetting->getExtensions();
if (empty($extensions)) {
return;
}
foreach ($extensions as $extensionClass) {
$extension = new $extensionClass();
if (!$extension instanceof ExtensionInterface) {
throw new Exception("“{$extensionClass}”不是“ExtensionInterface”的实例");
}
//注入AppContext
$extension->setAppContext($this->appContext);
//加载扩展
$extension->load();
}
} | 加载扩展 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Bootstrap.php#L79-L97 |
alekitto/metadata | lib/Loader/Processor/CompositeProcessor.php | CompositeProcessor.process | public function process(MetadataInterface $metadata, $subject): void
{
foreach ($this->processors as $processor) {
$processor->process($metadata, $subject);
}
} | php | public function process(MetadataInterface $metadata, $subject): void
{
foreach ($this->processors as $processor) {
$processor->process($metadata, $subject);
}
} | {@inheritdoc} | https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Loader/Processor/CompositeProcessor.php#L32-L37 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.process | public function process(File $file, $stackPtr)
{
$tokens = $file->getTokens();
$find = PHP_CodeSniffer_Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $file->findPrevious($find, ($stackPtr - 1), null, true);
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
// Inline comments might just be closing comments for
// control structures or functions instead of function comments
// using the wrong comment type. If there is other code on the line,
// assume they relate to that code.
$prev = $file->findPrevious($find, ($commentEnd - 1), null, true);
if ($prev !== false
&& $tokens[$prev]['line'] === $tokens[$commentEnd]['line']
) {
$commentEnd = $prev;
}
}
// Should we ignore the missing comment? Only for tests.
$functionNamePos = $file->findNext(T_STRING, $stackPtr);
if (substr($tokens[$functionNamePos]['content'], 0, 4) === 'test') {
return;
}
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT
) {
$file->addError(
'Missing function doc comment',
$stackPtr,
'Missing'
);
$file->recordMetric(
$stackPtr,
'Function has doc comment',
'no'
);
return;
} else {
$file->recordMetric(
$stackPtr,
'Function has doc comment',
'yes'
);
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$file->addError(
'You must use "/**" style comments for a function comment',
$stackPtr,
'WrongStyle'
);
return;
}
if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) {
$error = 'There must be no blank lines after the function comment';
$file->addError($error, $commentEnd, 'SpacingAfter');
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@see') {
// Make sure the tag isn't empty.
$string = $file->findNext(
T_DOC_COMMENT_STRING,
$tag,
$commentEnd
);
if ($string === false
|| $tokens[$string]['line'] !== $tokens[$tag]['line']
) {
$error = 'Content missing for @see tag in function comment';
$file->addError($error, $tag, 'EmptySees');
}
}
}
$this->processReturn($file, $stackPtr, $commentStart);
$this->processThrows($file, $stackPtr, $commentStart);
$this->processParams($file, $stackPtr, $commentStart);
} | php | public function process(File $file, $stackPtr)
{
$tokens = $file->getTokens();
$find = PHP_CodeSniffer_Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $file->findPrevious($find, ($stackPtr - 1), null, true);
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
// Inline comments might just be closing comments for
// control structures or functions instead of function comments
// using the wrong comment type. If there is other code on the line,
// assume they relate to that code.
$prev = $file->findPrevious($find, ($commentEnd - 1), null, true);
if ($prev !== false
&& $tokens[$prev]['line'] === $tokens[$commentEnd]['line']
) {
$commentEnd = $prev;
}
}
// Should we ignore the missing comment? Only for tests.
$functionNamePos = $file->findNext(T_STRING, $stackPtr);
if (substr($tokens[$functionNamePos]['content'], 0, 4) === 'test') {
return;
}
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT
) {
$file->addError(
'Missing function doc comment',
$stackPtr,
'Missing'
);
$file->recordMetric(
$stackPtr,
'Function has doc comment',
'no'
);
return;
} else {
$file->recordMetric(
$stackPtr,
'Function has doc comment',
'yes'
);
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$file->addError(
'You must use "/**" style comments for a function comment',
$stackPtr,
'WrongStyle'
);
return;
}
if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) {
$error = 'There must be no blank lines after the function comment';
$file->addError($error, $commentEnd, 'SpacingAfter');
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@see') {
// Make sure the tag isn't empty.
$string = $file->findNext(
T_DOC_COMMENT_STRING,
$tag,
$commentEnd
);
if ($string === false
|| $tokens[$string]['line'] !== $tokens[$tag]['line']
) {
$error = 'Content missing for @see tag in function comment';
$file->addError($error, $tag, 'EmptySees');
}
}
}
$this->processReturn($file, $stackPtr, $commentStart);
$this->processThrows($file, $stackPtr, $commentStart);
$this->processParams($file, $stackPtr, $commentStart);
} | Processes this test, when one of its tokens is encountered.
@param PHP_CodeSniffer_File $file The file being scanned.
@param int $stackPtr The position of the current token in the stack
passed in $tokens. | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L23-L108 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.processParams | protected function processParams(
File $phpcsFile,
$stackPtr,
$commentStart
) {
$tokens = $phpcsFile->getTokens();
$params = [];
$maxType = 0;
$maxVar = 0;
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@param') {
continue;
}
$type = '';
$typeSpace = 0;
$var = '';
$varSpace = 0;
$comment = '';
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = [];
preg_match(
'/([^$&\.]+)(?:((?:\$|&|\.)[^\s]+)(?:(\s+)(.*))?)?/',
$tokens[($tag + 2)]['content'],
$matches
);
$typeLen = strlen($matches[1]);
$type = trim($matches[1]);
$typeSpace = ($typeLen - strlen($type));
$typeLen = strlen($type);
if ($typeLen > $maxType) {
$maxType = $typeLen;
}
if (isset($matches[2]) === true) {
$var = str_replace('...', '', $matches[2]);
$varLen = strlen($var);
if ($varLen > $maxVar) {
$maxVar = $varLen;
}
if (isset($matches[4]) === true) {
$varSpace = strlen($matches[3]);
$comment = $matches[4];
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos
+ 1)]) === true
) {
$end = $tokens[$commentStart]['comment_tags'][($pos
+ 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$comment .= ' ' . $tokens[$i]['content'];
}
}
}
//$error = 'Missing parameter comment';
//$phpcsFile->addError($error, $tag, 'MissingParamComment');
} else {
$error = 'Missing parameter name';
$phpcsFile->addError($error, $tag, 'MissingParamName');
}
} else {
$error = 'Missing parameter type';
$phpcsFile->addError($error, $tag, 'MissingParamType');
}
$params[] = [
'tag' => $tag,
'type' => $type,
'var' => $var,
'comment' => $comment,
'type_space' => $typeSpace,
'var_space' => $varSpace,
];
}
$realParams = $phpcsFile->getMethodParameters($stackPtr);
$foundParams = [];
foreach ($params as $pos => $param) {
if ($param['var'] === '') {
continue;
}
if (array_key_exists('type', $param)) {
$types = explode('|', $param['type']);
foreach ($types as $type) {
$this->checkParamType($type, $param['tag'], $phpcsFile);
}
}
$foundParams[] = $param['var'];
// Check number of spaces after the type.
$spaces = 1;
if ($param['type_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter type; %s found';
$data = [
$spaces,
$param['type_space'],
];
$fix = $phpcsFile->addFixableError(
$error,
$param['tag'],
'SpacingAfterParamType',
$data
);
if ($fix === true) {
$content = $param['type'];
$content .= str_repeat(' ', $spaces);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
$content .= $param['comment'];
$phpcsFile->fixer->replaceToken(
($param['tag'] + 2),
$content
);
}
}
// Make sure the param name is correct.
if (isset($realParams[$pos]) === true) {
$realName = $realParams[$pos]['name'];
if ($realName !== $param['var']) {
$code = 'ParamNameNoMatch';
$data = [
$param['var'],
$realName,
];
$error = 'Doc comment for parameter %s does not match ';
if (strtolower($param['var']) === strtolower($realName)) {
$error .= 'case of ';
$code = 'ParamNameNoCaseMatch';
}
$error .= 'actual variable name %s';
$phpcsFile->addError($error, $param['tag'], $code, $data);
}
} else {
if (substr($param['var'], -4) !== ',...') {
// We must have an extra parameter comment.
$error = 'Superfluous parameter comment';
$phpcsFile->addError(
$error,
$param['tag'],
'ExtraParamComment'
);
}
}
if ($param['comment'] === '') {
continue;
}
// Check number of spaces after the var name.
$spaces = 1;
if ($param['var_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter name; %s found';
$data = [
$spaces,
$param['var_space'],
];
$fix = $phpcsFile->addFixableError(
$error,
$param['tag'],
'SpacingAfterParamName',
$data
);
if ($fix === true) {
$content = $param['type'];
$content .= str_repeat(' ', $param['type_space']);
$content .= $param['var'];
$content .= str_repeat(' ', $spaces);
$content .= $param['comment'];
$phpcsFile->fixer->replaceToken(
($param['tag'] + 2),
$content
);
}
}
}
} | php | protected function processParams(
File $phpcsFile,
$stackPtr,
$commentStart
) {
$tokens = $phpcsFile->getTokens();
$params = [];
$maxType = 0;
$maxVar = 0;
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@param') {
continue;
}
$type = '';
$typeSpace = 0;
$var = '';
$varSpace = 0;
$comment = '';
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = [];
preg_match(
'/([^$&\.]+)(?:((?:\$|&|\.)[^\s]+)(?:(\s+)(.*))?)?/',
$tokens[($tag + 2)]['content'],
$matches
);
$typeLen = strlen($matches[1]);
$type = trim($matches[1]);
$typeSpace = ($typeLen - strlen($type));
$typeLen = strlen($type);
if ($typeLen > $maxType) {
$maxType = $typeLen;
}
if (isset($matches[2]) === true) {
$var = str_replace('...', '', $matches[2]);
$varLen = strlen($var);
if ($varLen > $maxVar) {
$maxVar = $varLen;
}
if (isset($matches[4]) === true) {
$varSpace = strlen($matches[3]);
$comment = $matches[4];
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos
+ 1)]) === true
) {
$end = $tokens[$commentStart]['comment_tags'][($pos
+ 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$comment .= ' ' . $tokens[$i]['content'];
}
}
}
//$error = 'Missing parameter comment';
//$phpcsFile->addError($error, $tag, 'MissingParamComment');
} else {
$error = 'Missing parameter name';
$phpcsFile->addError($error, $tag, 'MissingParamName');
}
} else {
$error = 'Missing parameter type';
$phpcsFile->addError($error, $tag, 'MissingParamType');
}
$params[] = [
'tag' => $tag,
'type' => $type,
'var' => $var,
'comment' => $comment,
'type_space' => $typeSpace,
'var_space' => $varSpace,
];
}
$realParams = $phpcsFile->getMethodParameters($stackPtr);
$foundParams = [];
foreach ($params as $pos => $param) {
if ($param['var'] === '') {
continue;
}
if (array_key_exists('type', $param)) {
$types = explode('|', $param['type']);
foreach ($types as $type) {
$this->checkParamType($type, $param['tag'], $phpcsFile);
}
}
$foundParams[] = $param['var'];
// Check number of spaces after the type.
$spaces = 1;
if ($param['type_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter type; %s found';
$data = [
$spaces,
$param['type_space'],
];
$fix = $phpcsFile->addFixableError(
$error,
$param['tag'],
'SpacingAfterParamType',
$data
);
if ($fix === true) {
$content = $param['type'];
$content .= str_repeat(' ', $spaces);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
$content .= $param['comment'];
$phpcsFile->fixer->replaceToken(
($param['tag'] + 2),
$content
);
}
}
// Make sure the param name is correct.
if (isset($realParams[$pos]) === true) {
$realName = $realParams[$pos]['name'];
if ($realName !== $param['var']) {
$code = 'ParamNameNoMatch';
$data = [
$param['var'],
$realName,
];
$error = 'Doc comment for parameter %s does not match ';
if (strtolower($param['var']) === strtolower($realName)) {
$error .= 'case of ';
$code = 'ParamNameNoCaseMatch';
}
$error .= 'actual variable name %s';
$phpcsFile->addError($error, $param['tag'], $code, $data);
}
} else {
if (substr($param['var'], -4) !== ',...') {
// We must have an extra parameter comment.
$error = 'Superfluous parameter comment';
$phpcsFile->addError(
$error,
$param['tag'],
'ExtraParamComment'
);
}
}
if ($param['comment'] === '') {
continue;
}
// Check number of spaces after the var name.
$spaces = 1;
if ($param['var_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter name; %s found';
$data = [
$spaces,
$param['var_space'],
];
$fix = $phpcsFile->addFixableError(
$error,
$param['tag'],
'SpacingAfterParamName',
$data
);
if ($fix === true) {
$content = $param['type'];
$content .= str_repeat(' ', $param['type_space']);
$content .= $param['var'];
$content .= str_repeat(' ', $spaces);
$content .= $param['comment'];
$phpcsFile->fixer->replaceToken(
($param['tag'] + 2),
$content
);
}
}
}
} | Process a @param comment .
@param File $phpcsFile
@param int $stackPtr
@param int $commentStart | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L117-L314 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.findUseStatements | protected function findUseStatements(File $file)
{
if (array_key_exists($file->getFilename(), static::$useCache)) {
return static::$useCache[$file->getFilename()];
}
$tokens = $file->getTokens();
$usePosition = $file->findNext(T_USE, 0);
$useStatements = [];
while ($usePosition !== false) {
if ($this->shouldIgnoreUse($file, $usePosition)) {
$usePosition = $file->findNext(T_USE, $usePosition + 1);
continue;
}
$fullPath = '';
$lastString = '';
$alias = '';
$useEnd = $file->findNext(
[T_SEMICOLON, T_COMMA],
$usePosition
);
$useFullPathEnd = $file->findNext(
[T_SEMICOLON, T_COMMA, T_WHITESPACE],
$usePosition + 2
);
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$usePosition
);
while ($afterUse !== false) {
$fullPath .= $tokens[$afterUse]['content'];
if ($tokens[$afterUse]['code'] == T_STRING) {
$lastString = $tokens[$afterUse]['content'];
}
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$afterUse + 1,
$useFullPathEnd
);
}
if ($useFullPathEnd != $useEnd) {
if ($tokens[$useFullPathEnd + 1]['code'] !== T_AS) {
continue;
}
if ($tokens[$useFullPathEnd + 3]['code'] === T_STRING) {
$alias = $tokens[$useFullPathEnd + 3]['content'];
}
} else {
$alias = $lastString;
}
$useStatements[$fullPath] = $alias;
$usePosition = $file->findNext(T_USE, $usePosition + 1);
}
static::$useCache[$file->getFilename()] = $useStatements;
return $useStatements;
} | php | protected function findUseStatements(File $file)
{
if (array_key_exists($file->getFilename(), static::$useCache)) {
return static::$useCache[$file->getFilename()];
}
$tokens = $file->getTokens();
$usePosition = $file->findNext(T_USE, 0);
$useStatements = [];
while ($usePosition !== false) {
if ($this->shouldIgnoreUse($file, $usePosition)) {
$usePosition = $file->findNext(T_USE, $usePosition + 1);
continue;
}
$fullPath = '';
$lastString = '';
$alias = '';
$useEnd = $file->findNext(
[T_SEMICOLON, T_COMMA],
$usePosition
);
$useFullPathEnd = $file->findNext(
[T_SEMICOLON, T_COMMA, T_WHITESPACE],
$usePosition + 2
);
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$usePosition
);
while ($afterUse !== false) {
$fullPath .= $tokens[$afterUse]['content'];
if ($tokens[$afterUse]['code'] == T_STRING) {
$lastString = $tokens[$afterUse]['content'];
}
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$afterUse + 1,
$useFullPathEnd
);
}
if ($useFullPathEnd != $useEnd) {
if ($tokens[$useFullPathEnd + 1]['code'] !== T_AS) {
continue;
}
if ($tokens[$useFullPathEnd + 3]['code'] === T_STRING) {
$alias = $tokens[$useFullPathEnd + 3]['content'];
}
} else {
$alias = $lastString;
}
$useStatements[$fullPath] = $alias;
$usePosition = $file->findNext(T_USE, $usePosition + 1);
}
static::$useCache[$file->getFilename()] = $useStatements;
return $useStatements;
} | Find all use statements.
@param PHP_CodeSniffer_File $file
@return array | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L323-L391 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.shouldIgnoreUse | protected function shouldIgnoreUse(File $file, $stackPtr)
{
$tokens = $file->getTokens();
// Ignore USE keywords inside closures.
$next = $file->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) {
return true;
}
// Ignore USE keywords for traits.
if ($file->hasCondition($stackPtr, [T_CLASS, T_TRAIT]) === true) {
return true;
}
return false;
} | php | protected function shouldIgnoreUse(File $file, $stackPtr)
{
$tokens = $file->getTokens();
// Ignore USE keywords inside closures.
$next = $file->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) {
return true;
}
// Ignore USE keywords for traits.
if ($file->hasCondition($stackPtr, [T_CLASS, T_TRAIT]) === true) {
return true;
}
return false;
} | Check whether or not a USE statement should be ignored.
@param PHP_CodeSniffer_File $file
@param $stackPtr
@return bool | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L401-L417 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.resolveArrayType | protected function resolveArrayType($type)
{
if (strrpos($type, '[]', -2) !== false) {
return substr($type, 0, strlen($type) - 2);
}
return $type;
} | php | protected function resolveArrayType($type)
{
if (strrpos($type, '[]', -2) !== false) {
return substr($type, 0, strlen($type) - 2);
}
return $type;
} | Attempt to resolve the type of an array.
@param $type
@return string | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L468-L475 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.processReturn | protected function processReturn(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$commentStart
) {
$tokens = $phpcsFile->getTokens();
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error =
'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
if ($tokens[$tag + 2]['code'] === T_DOC_COMMENT_STRING) {
$types = explode('|', $tokens[$tag + 2]['content']);
foreach ($types as $type) {
$this->checkParamType($type, $tag + 2, $phpcsFile);
}
}
$return = $tag;
}
}
return;
} | php | protected function processReturn(
PHP_CodeSniffer_File $phpcsFile,
$stackPtr,
$commentStart
) {
$tokens = $phpcsFile->getTokens();
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error =
'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
if ($tokens[$tag + 2]['code'] === T_DOC_COMMENT_STRING) {
$types = explode('|', $tokens[$tag + 2]['content']);
foreach ($types as $type) {
$this->checkParamType($type, $tag + 2, $phpcsFile);
}
}
$return = $tag;
}
}
return;
} | Process the return comment of this function comment.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in
$tokens.
@param int $commentStart The position in the stack where the comment
started.
@return void | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L521-L552 |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.extractNamespace | protected function extractNamespace(
File $file
) {
$namespace = '';
$tokens = $file->getTokens();
$prev = $file->findNext(T_NAMESPACE, 0);
for ($i = $prev + 2; $i < count($tokens); $i++) {
if (!in_array($tokens[$i]['code'], [T_STRING, T_NS_SEPARATOR])) {
break;
}
$namespace .= $tokens[$i]['content'];
}
return $namespace;
} | php | protected function extractNamespace(
File $file
) {
$namespace = '';
$tokens = $file->getTokens();
$prev = $file->findNext(T_NAMESPACE, 0);
for ($i = $prev + 2; $i < count($tokens); $i++) {
if (!in_array($tokens[$i]['code'], [T_STRING, T_NS_SEPARATOR])) {
break;
}
$namespace .= $tokens[$i]['content'];
}
return $namespace;
} | Extract the first namespace found in the file.
@param PHP_CodeSniffer_File $file
@return string | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L561-L579 |
LapaLabs/YoutubeHelper | Resource/YoutubeResource.php | YoutubeResource.buildEmbedUrl | public function buildEmbedUrl(array $parameters = [])
{
$parameters = array_merge($this->parameters, $parameters);
// https://www.youtube.com/embed/5qanlirrRWs
$url = 'https://'.static::HOST_DEFAULT.'/embed/'.$this->id;
if (count($parameters)) {
$parameterStrings = [];
foreach ($parameters as $name => $value) {
$parameterString = urlencode($name);
if (null !== $value) {
$parameterString .= '='.urlencode($value);
}
$parameterStrings[] = $parameterString;
}
$url .= '?'.implode('&', $parameterStrings);
}
return $url;
} | php | public function buildEmbedUrl(array $parameters = [])
{
$parameters = array_merge($this->parameters, $parameters);
// https://www.youtube.com/embed/5qanlirrRWs
$url = 'https://'.static::HOST_DEFAULT.'/embed/'.$this->id;
if (count($parameters)) {
$parameterStrings = [];
foreach ($parameters as $name => $value) {
$parameterString = urlencode($name);
if (null !== $value) {
$parameterString .= '='.urlencode($value);
}
$parameterStrings[] = $parameterString;
}
$url .= '?'.implode('&', $parameterStrings);
}
return $url;
} | @param array $parameters
@return string | https://github.com/LapaLabs/YoutubeHelper/blob/b94fd4700881494d24f14fb39ed8093215d0b25b/Resource/YoutubeResource.php#L201-L220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.