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
atelierspierrot/internationalization
src/I18n/Loader.php
Loader.addPath
public function addPath($db_filename = null, $db_directory = null, $file = null) { if (!empty($db_filename) && !in_array($db_filename, $this->_paths['language_strings_db_filename'])) { $this->_paths['language_strings_db_filename'][] = $db_filename; } if (!empty($db_directory) && !in_array($db_directory, $this->_paths['language_strings_db_directory'])) { $this->_paths['language_strings_db_directory'][] = $db_directory; } if (!empty($file) && !in_array($file, $this->_paths['loaded_files'])) { $this->_paths['loaded_files'][] = $file; } return $this; }
php
public function addPath($db_filename = null, $db_directory = null, $file = null) { if (!empty($db_filename) && !in_array($db_filename, $this->_paths['language_strings_db_filename'])) { $this->_paths['language_strings_db_filename'][] = $db_filename; } if (!empty($db_directory) && !in_array($db_directory, $this->_paths['language_strings_db_directory'])) { $this->_paths['language_strings_db_directory'][] = $db_directory; } if (!empty($file) && !in_array($file, $this->_paths['loaded_files'])) { $this->_paths['loaded_files'][] = $file; } return $this; }
Add a path to the registry @param null|string $db_filename @param null|string $db_directory @param null|string $file @return $this
https://github.com/atelierspierrot/internationalization/blob/334ebf75020d9e66b4b38a1eeab7b411f1ffe198/src/I18n/Loader.php#L88-L100
atelierspierrot/internationalization
src/I18n/Loader.php
Loader.getParsedOption
public function getParsedOption($name, $lang = null, $default = null) { $val = $this->getOption($name, $default); if (false!==strpos($val, '%s')) { if (is_null($lang)) { $i18n = I18n::getInstance(); $lang = $i18n->getLanguage(); } if (is_array($lang)) { array_unshift($lang, $val); $val = call_user_func_array('sprintf', $lang); } else { $val = sprintf($val, $lang); } } return $val; }
php
public function getParsedOption($name, $lang = null, $default = null) { $val = $this->getOption($name, $default); if (false!==strpos($val, '%s')) { if (is_null($lang)) { $i18n = I18n::getInstance(); $lang = $i18n->getLanguage(); } if (is_array($lang)) { array_unshift($lang, $val); $val = call_user_func_array('sprintf', $lang); } else { $val = sprintf($val, $lang); } } return $val; }
Parse an option value replacing `%s` by the actual language code @param string $name The option name @param string|array $lang The language code to use or an array to pass to the 'sprintf()' method @param mixed $default The value to return if the option can't be found @return mixed The value of the option if found, with replacement if so
https://github.com/atelierspierrot/internationalization/blob/334ebf75020d9e66b4b38a1eeab7b411f1ffe198/src/I18n/Loader.php#L111-L127
atelierspierrot/internationalization
src/I18n/Loader.php
Loader.buildLanguageFileName
public function buildLanguageFileName($lang, $db_filename = null) { if (empty($db_filename)) { $db_filename = $this->getParsedOption('language_strings_db_filename'); } $filename = pathinfo($db_filename, PATHINFO_FILENAME); return $this->getParsedOption('language_filename', array($filename, $lang)); }
php
public function buildLanguageFileName($lang, $db_filename = null) { if (empty($db_filename)) { $db_filename = $this->getParsedOption('language_strings_db_filename'); } $filename = pathinfo($db_filename, PATHINFO_FILENAME); return $this->getParsedOption('language_filename', array($filename, $lang)); }
Build the file name for the language database @param string $lang The language code to use @param string $db_filename A base filename to use @return string The file name for the concerned language
https://github.com/atelierspierrot/internationalization/blob/334ebf75020d9e66b4b38a1eeab7b411f1ffe198/src/I18n/Loader.php#L140-L147
atelierspierrot/internationalization
src/I18n/Loader.php
Loader.findLanguageDBFile
public function findLanguageDBFile($db_filename = null, $db_directory = null) { if (empty($db_filename)) { $db_filename = $this->buildLanguageDBFileName(); } if (empty($db_directory)) { $db_directory = $this->buildLanguageDBDirName(); } $_file = null; $tmp_file = DirectoryHelper::slashDirname($db_directory).$db_filename; if (file_exists($tmp_file)) { $_file = $tmp_file; } else { foreach ($this->_paths['language_strings_db_directory'] as $dir) { $tmp_file = DirectoryHelper::slashDirname($dir).$db_filename; if (file_exists($tmp_file)) { $_file = $tmp_file; } } } $this->addPath($db_filename, $db_directory, $_file); return $_file; }
php
public function findLanguageDBFile($db_filename = null, $db_directory = null) { if (empty($db_filename)) { $db_filename = $this->buildLanguageDBFileName(); } if (empty($db_directory)) { $db_directory = $this->buildLanguageDBDirName(); } $_file = null; $tmp_file = DirectoryHelper::slashDirname($db_directory).$db_filename; if (file_exists($tmp_file)) { $_file = $tmp_file; } else { foreach ($this->_paths['language_strings_db_directory'] as $dir) { $tmp_file = DirectoryHelper::slashDirname($dir).$db_filename; if (file_exists($tmp_file)) { $_file = $tmp_file; } } } $this->addPath($db_filename, $db_directory, $_file); return $_file; }
Find (and add if needed) a language file from options directories @param string $db_filename @param string $db_directory @return null|string
https://github.com/atelierspierrot/internationalization/blob/334ebf75020d9e66b4b38a1eeab7b411f1ffe198/src/I18n/Loader.php#L219-L243
armazon/armazon
src/Armazon/Http/Respuesta.php
Respuesta.agregarCabecera
public function agregarCabecera($nombre, $valor) { if (isset($this->cabeceras[$nombre])) { $this->cabeceras[$nombre][] = $valor; } else { $this->cabeceras[$nombre] = [$valor]; } }
php
public function agregarCabecera($nombre, $valor) { if (isset($this->cabeceras[$nombre])) { $this->cabeceras[$nombre][] = $valor; } else { $this->cabeceras[$nombre] = [$valor]; } }
Agrega una cabecera a la respuesta. @param string $nombre @param string $valor
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Respuesta.php#L65-L73
armazon/armazon
src/Armazon/Http/Respuesta.php
Respuesta.agregarGalleta
public function agregarGalleta($nombre, $valor, $expira = 0, $camino = '/', $dominio = null, $seguro = false, $soloHttp = false) { $extras = ''; if ($expira) { $extras .= ';Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $expira); } if ($camino) { $extras .= ';Path=' . $camino; } if ($dominio) { $extras .= ';Domain=' . $dominio; } if ($seguro) { $extras .= ';Secure'; } if ($soloHttp) { $extras .= ';HttpOnly'; } $this->agregarCabecera('Set-Cookie', "{$nombre}={$valor}{$extras}"); }
php
public function agregarGalleta($nombre, $valor, $expira = 0, $camino = '/', $dominio = null, $seguro = false, $soloHttp = false) { $extras = ''; if ($expira) { $extras .= ';Expires=' . gmdate('D, d M Y H:i:s \G\M\T', $expira); } if ($camino) { $extras .= ';Path=' . $camino; } if ($dominio) { $extras .= ';Domain=' . $dominio; } if ($seguro) { $extras .= ';Secure'; } if ($soloHttp) { $extras .= ';HttpOnly'; } $this->agregarCabecera('Set-Cookie', "{$nombre}={$valor}{$extras}"); }
Agrega una galleta a la respuesta. @param $nombre @param $valor @param int $expira @param string $camino @param string $dominio @param bool $seguro @param bool $soloHttp
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Respuesta.php#L86-L106
armazon/armazon
src/Armazon/Http/Respuesta.php
Respuesta.enviar
public function enviar() { if ($this->enviado) { return false; } http_response_code($this->estadoHttp); // Enviamos cabeceras foreach ($this->cabeceras as $cabecera => $valores) { foreach ($valores as $valor) { header($cabecera . ': ' . $valor, false); } } if (!empty($this->contenido)) { echo $this->contenido; } return $this->enviado = true; }
php
public function enviar() { if ($this->enviado) { return false; } http_response_code($this->estadoHttp); // Enviamos cabeceras foreach ($this->cabeceras as $cabecera => $valores) { foreach ($valores as $valor) { header($cabecera . ': ' . $valor, false); } } if (!empty($this->contenido)) { echo $this->contenido; } return $this->enviado = true; }
Envia la respuesta al navegador usando la forma clásica. @return bool
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Respuesta.php#L179-L199
armazon/armazon
src/Armazon/Http/Respuesta.php
Respuesta.enviarArchivo
public function enviarArchivo($nombre) { $this->definirCabecera('Pragma', 'public'); $this->definirCabecera('Expires', '0'); $this->definirCabecera('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); $this->definirCabecera('Content-Length', (function_exists('mb_strlen') ? mb_strlen($this->contenido, '8bit') : strlen($this->contenido))); $this->definirCabecera('Content-Disposition', 'attachment; filename="' . $nombre . '"'); $this->definirCabecera('Content-Transfer-Encoding', 'binary'); $this->enviar(); }
php
public function enviarArchivo($nombre) { $this->definirCabecera('Pragma', 'public'); $this->definirCabecera('Expires', '0'); $this->definirCabecera('Cache-Control', 'must-revalidate, post-check=0, pre-check=0'); $this->definirCabecera('Content-Length', (function_exists('mb_strlen') ? mb_strlen($this->contenido, '8bit') : strlen($this->contenido))); $this->definirCabecera('Content-Disposition', 'attachment; filename="' . $nombre . '"'); $this->definirCabecera('Content-Transfer-Encoding', 'binary'); $this->enviar(); }
Envia un archivo al navegador. @param string $nombre
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Respuesta.php#L214-L224
armazon/armazon
src/Armazon/Http/Respuesta.php
Respuesta.redirigir
public function redirigir($url, $estadoHttp = 302) { $this->definirCabecera('Location', $url); $this->definirEstadoHttp($estadoHttp); $this->definirContenido(null); return $this; }
php
public function redirigir($url, $estadoHttp = 302) { $this->definirCabecera('Location', $url); $this->definirEstadoHttp($estadoHttp); $this->definirContenido(null); return $this; }
Redirige el navegador a la URL especificada. @param string $url @param int $estadoHttp @return self
https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Respuesta.php#L233-L239
andrelohmann/silverstripe-geoform
code/forms/HiddenLocationField.php
HiddenLocationField.FieldHolder
public function FieldHolder($properties = array()) { $obj = ($properties) ? $this->customise($properties) : $this; return $obj->renderWith($this->getFieldHolderTemplates()); }
php
public function FieldHolder($properties = array()) { $obj = ($properties) ? $this->customise($properties) : $this; return $obj->renderWith($this->getFieldHolderTemplates()); }
Returns a "field holder" for this field - used by templates. Forms are constructed by concatenating a number of these field holders. The default field holder is a label and a form field inside a div. @see FieldHolder.ss @param array $properties key value pairs of template variables @return string
https://github.com/andrelohmann/silverstripe-geoform/blob/4b8ca69d094dca985c059fb35a159673c39af8d3/code/forms/HiddenLocationField.php#L57-L61
andrelohmann/silverstripe-geoform
code/forms/HiddenLocationField.php
HiddenLocationField.saveInto
public function saveInto(DataObjectInterface $dataObject) { $fieldName = $this->name; if($dataObject->hasMethod("set$fieldName")) { $dataObject->$fieldName = DBField::create_field('Location', array( "Latitude" => $this->fieldLatitude->Value(), "Longditude" => $this->fieldLongditude->Value() )); } else { $dataObject->$fieldName->setLatitude($this->fieldLatitude->Value()); $dataObject->$fieldName->setLongditude($this->fieldLongditude->Value()); } }
php
public function saveInto(DataObjectInterface $dataObject) { $fieldName = $this->name; if($dataObject->hasMethod("set$fieldName")) { $dataObject->$fieldName = DBField::create_field('Location', array( "Latitude" => $this->fieldLatitude->Value(), "Longditude" => $this->fieldLongditude->Value() )); } else { $dataObject->$fieldName->setLatitude($this->fieldLatitude->Value()); $dataObject->$fieldName->setLongditude($this->fieldLongditude->Value()); } }
30/06/2009 - Enhancement: SaveInto checks if set-methods are available and use them instead of setting the values in the money class directly. saveInto initiates a new Money class object to pass through the values to the setter method. (see @link MoneyFieldTest_CustomSetter_Object for more information)
https://github.com/andrelohmann/silverstripe-geoform/blob/4b8ca69d094dca985c059fb35a159673c39af8d3/code/forms/HiddenLocationField.php#L117-L128
andrelohmann/silverstripe-geoform
code/forms/HiddenLocationField.php
HiddenLocationField.validate
public function validate($validator){ $name = $this->name; $latitudeField = $this->fieldLatitude; $longditudeField = $this->fieldLongditude; $positionSetField = $this->fieldPositionSet; $latitudeField->setValue($_POST[$name]['Latitude']); $longditudeField->setValue($_POST[$name]['Longditude']); $positionSetField->setValue($_POST[$name]['PositionSet']); // Result was unique if($latitudeField->Value() != '' && is_numeric($latitudeField->Value()) && $longditudeField->Value() != '' && is_numeric($longditudeField->Value()) && $positionSetField->Value() == 1){ return true; } if($this->isRequired){ $validator->validationError($name, _t('HiddenLocationField.LOCATIONREQUIRED', 'Please allow access to your location'), "validation"); $this->form->sessionMessage(_t('HiddenLocationField.LOCATIONREQUIRED', 'Please allow access to your location'), 'bad'); return false; } }
php
public function validate($validator){ $name = $this->name; $latitudeField = $this->fieldLatitude; $longditudeField = $this->fieldLongditude; $positionSetField = $this->fieldPositionSet; $latitudeField->setValue($_POST[$name]['Latitude']); $longditudeField->setValue($_POST[$name]['Longditude']); $positionSetField->setValue($_POST[$name]['PositionSet']); // Result was unique if($latitudeField->Value() != '' && is_numeric($latitudeField->Value()) && $longditudeField->Value() != '' && is_numeric($longditudeField->Value()) && $positionSetField->Value() == 1){ return true; } if($this->isRequired){ $validator->validationError($name, _t('HiddenLocationField.LOCATIONREQUIRED', 'Please allow access to your location'), "validation"); $this->form->sessionMessage(_t('HiddenLocationField.LOCATIONREQUIRED', 'Please allow access to your location'), 'bad'); return false; } }
Validates PostCodeLocation against GoogleMaps Serverside @return String
https://github.com/andrelohmann/silverstripe-geoform/blob/4b8ca69d094dca985c059fb35a159673c39af8d3/code/forms/HiddenLocationField.php#L154-L176
gregorybesson/AdfabCore
src/AdfabCore/Controller/Plugin/ShortenUrl.php
ShortenUrl.getService
public function getService() { if (!$this->service) { $this->setService($this->getServiceLocator()->get('adfabcore_shortenurl_service')); } return $this->service; }
php
public function getService() { if (!$this->service) { $this->setService($this->getServiceLocator()->get('adfabcore_shortenurl_service')); } return $this->service; }
get mapper @return Service
https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Controller/Plugin/ShortenUrl.php#L49-L56
MovingImage24/VM6ApiClient
lib/Factory/AbstractApiClientFactory.php
AbstractApiClientFactory.create
public function create( ClientInterface $httpClient, Serializer $serializer, UnlockTokenGenerator $unlockTokenGenerator = null, LoggerInterface $logger = null ) { $cls = $this->getApiClientClass(); $apiClient = new $cls($httpClient, $serializer, $unlockTokenGenerator); if (!is_null($logger)) { $apiClient->setLogger($logger); } return $apiClient; }
php
public function create( ClientInterface $httpClient, Serializer $serializer, UnlockTokenGenerator $unlockTokenGenerator = null, LoggerInterface $logger = null ) { $cls = $this->getApiClientClass(); $apiClient = new $cls($httpClient, $serializer, $unlockTokenGenerator); if (!is_null($logger)) { $apiClient->setLogger($logger); } return $apiClient; }
{@inheritdoc}
https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/Factory/AbstractApiClientFactory.php#L58-L72
bruno-barros/w.eloquent-framework
src/weloquent/Core/Application.php
Application.run
public function run(SymfonyRequest $request = null) { /** * On testing environment the WordPress helpers * will not have context. So we stop here. */ if(defined('WELOQUENT_TEST_ENV') && WELOQUENT_TEST_ENV) { return; } $request = $request ?: $this['request']; $response = with($stack = $this->getStackedClient())->handle($request); // just set headers, but the content if(! is_admin()) { $response->sendHeaders(); } if ('cli' !== PHP_SAPI) { $response::closeOutputBuffers(0, false); } /** * Save the session data until the application dies */ add_action('wp_footer', function () use ($stack, $request, $response) { $stack->terminate($request, $response); Session::save('wp_footer'); }); }
php
public function run(SymfonyRequest $request = null) { /** * On testing environment the WordPress helpers * will not have context. So we stop here. */ if(defined('WELOQUENT_TEST_ENV') && WELOQUENT_TEST_ENV) { return; } $request = $request ?: $this['request']; $response = with($stack = $this->getStackedClient())->handle($request); // just set headers, but the content if(! is_admin()) { $response->sendHeaders(); } if ('cli' !== PHP_SAPI) { $response::closeOutputBuffers(0, false); } /** * Save the session data until the application dies */ add_action('wp_footer', function () use ($stack, $request, $response) { $stack->terminate($request, $response); Session::save('wp_footer'); }); }
Run the application and save headers. The response is up to WordPress @param \Symfony\Component\HttpFoundation\Request $request @return void
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Application.php#L44-L82
graze/csv-token
src/Buffer/StreamBuffer.php
StreamBuffer.move
public function move($length) { $this->contents = substr($this->contents, $length); $newLen = max(0, $this->length - $length); $this->position += $this->length - $newLen; $this->length = $newLen; return true; }
php
public function move($length) { $this->contents = substr($this->contents, $length); $newLen = max(0, $this->length - $length); $this->position += $this->length - $newLen; $this->length = $newLen; return true; }
Remove the first $length characters from the buffer @param int $length @return bool
https://github.com/graze/csv-token/blob/ad11cfc83e7f0cae56da6844f9216bbaf5c8dcb8/src/Buffer/StreamBuffer.php#L102-L109
gregorybesson/PlaygroundFlow
src/Form/Admin/StoryMapping.php
StoryMapping.getLeaderboardTypes
public function getLeaderboardTypes() { $leaderboardTypesArray = array(); $leaderboardTypesService = $this->getServiceManager()->get('playgroundreward_leaderboardtype_service'); $leaderboardTypes = $leaderboardTypesService->getLeaderboardTypeMapper()->findAll(); foreach ($leaderboardTypes as $leaderboardType) { $leaderboardTypesArray[$leaderboardType->getId()] = $leaderboardType->getName(); } return $leaderboardTypesArray; }
php
public function getLeaderboardTypes() { $leaderboardTypesArray = array(); $leaderboardTypesService = $this->getServiceManager()->get('playgroundreward_leaderboardtype_service'); $leaderboardTypes = $leaderboardTypesService->getLeaderboardTypeMapper()->findAll(); foreach ($leaderboardTypes as $leaderboardType) { $leaderboardTypesArray[$leaderboardType->getId()] = $leaderboardType->getName(); } return $leaderboardTypesArray; }
retrieve all leaderboard type for associate to storyMapping @return array $leaderboardTypesArray
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Form/Admin/StoryMapping.php#L317-L328
vi-kon/laravel-parser-markdown
src/ViKon/ParserMarkdown/Skin/Markdown/Format/StrikethroughMarkdownRenderer.php
StrikethroughMarkdownRenderer.register
public function register(Renderer $renderer) { $this->registerTokenRenderer(StrikethroughRule::NAME . StrikethroughRule::OPEN, 'renderOpen', $renderer); $this->registerTokenRenderer(StrikethroughRule::NAME . StrikethroughRule::CLOSE, 'renderClose', $renderer); }
php
public function register(Renderer $renderer) { $this->registerTokenRenderer(StrikethroughRule::NAME . StrikethroughRule::OPEN, 'renderOpen', $renderer); $this->registerTokenRenderer(StrikethroughRule::NAME . StrikethroughRule::CLOSE, 'renderClose', $renderer); }
Register renderer @param \ViKon\Parser\Renderer\Renderer $renderer @return mixed
https://github.com/vi-kon/laravel-parser-markdown/blob/4b258b407df95f6b6be284252762ef3ddbef1e35/src/ViKon/ParserMarkdown/Skin/Markdown/Format/StrikethroughMarkdownRenderer.php#L25-L29
schpill/thin
src/Inflector.php
Inflector.rules
public static function rules($type, $config = array()) { $var = '_' . $type; if (!isset(static::${$var})) { return null; } if (empty($config)) { return static::${$var}; } switch ($type) { case 'transliteration': $_config = array(); foreach ($config as $key => $val) { if ($key[0] != '/') { $key = '/' . join('|', array_filter(preg_split('//u', $key))) . '/'; } $_config[$key] = $val; } static::$_transliteration = array_merge( $_config, static::$_transliteration, $_config ); break; case 'uninflected': static::$_uninflected = array_merge(static::$_uninflected, (array) $config); static::$_plural['regexUninflected'] = null; static::$_singular['regexUninflected'] = null; foreach ((array) $config as $word) { unset(static::$_singularized[$word], static::$_pluralized[$word]); } break; case 'singular': case 'plural': if (isset(static::${$var}[key($config)])) { foreach ($config as $rType => $set) { static::${$var}[$rType] = array_merge($set, static::${$var}[$rType], $set); if ($rType == 'irregular') { $swap = ($type == 'singular' ? '_plural' : '_singular'); static::${$swap}[$rType] = array_flip(static::${$var}[$rType]); } } } else { static::${$var}['rules'] = array_merge( $config, static::${$var}['rules'], $config ); } break; } }
php
public static function rules($type, $config = array()) { $var = '_' . $type; if (!isset(static::${$var})) { return null; } if (empty($config)) { return static::${$var}; } switch ($type) { case 'transliteration': $_config = array(); foreach ($config as $key => $val) { if ($key[0] != '/') { $key = '/' . join('|', array_filter(preg_split('//u', $key))) . '/'; } $_config[$key] = $val; } static::$_transliteration = array_merge( $_config, static::$_transliteration, $_config ); break; case 'uninflected': static::$_uninflected = array_merge(static::$_uninflected, (array) $config); static::$_plural['regexUninflected'] = null; static::$_singular['regexUninflected'] = null; foreach ((array) $config as $word) { unset(static::$_singularized[$word], static::$_pluralized[$word]); } break; case 'singular': case 'plural': if (isset(static::${$var}[key($config)])) { foreach ($config as $rType => $set) { static::${$var}[$rType] = array_merge($set, static::${$var}[$rType], $set); if ($rType == 'irregular') { $swap = ($type == 'singular' ? '_plural' : '_singular'); static::${$swap}[$rType] = array_flip(static::${$var}[$rType]); } } } else { static::${$var}['rules'] = array_merge( $config, static::${$var}['rules'], $config ); } break; } }
Gets or adds inflection and transliteration rules. @param string $type Either `'transliteration'`, `'uninflected'`, `'singular'` or `'plural'`. @param array $config @return mixed If `$config` is empty, returns the rules list specified by `$type`, otherwise returns `null`.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L221-L275
schpill/thin
src/Inflector.php
Inflector.pluralize
public static function pluralize($word) { if (isset(static::$_pluralized[$word])) { return static::$_pluralized[$word]; } extract(static::$_plural); if (!isset($regexUninflected) || !isset($regexIrregular)) { $regexUninflected = static::_enclose(join('|', $uninflected + static::$_uninflected)); $regexIrregular = static::_enclose(join('|', array_keys($irregular))); static::$_plural += compact('regexUninflected', 'regexIrregular'); } if (preg_match('/(' . $regexUninflected . ')$/i', $word, $regs)) { return static::$_pluralized[$word] = $word; } if (preg_match('/(.*)\\b(' . $regexIrregular . ')$/i', $word, $regs)) { $plural = substr($word, 0, 1) . substr($irregular[static::lower($regs[2])], 1); return static::$_pluralized[$word] = $regs[1] . $plural; } foreach ($rules as $rule => $replacement) { if (preg_match($rule, $word)) { return static::$_pluralized[$word] = preg_replace($rule, $replacement, $word); } } return static::$_pluralized[$word] = $word; }
php
public static function pluralize($word) { if (isset(static::$_pluralized[$word])) { return static::$_pluralized[$word]; } extract(static::$_plural); if (!isset($regexUninflected) || !isset($regexIrregular)) { $regexUninflected = static::_enclose(join('|', $uninflected + static::$_uninflected)); $regexIrregular = static::_enclose(join('|', array_keys($irregular))); static::$_plural += compact('regexUninflected', 'regexIrregular'); } if (preg_match('/(' . $regexUninflected . ')$/i', $word, $regs)) { return static::$_pluralized[$word] = $word; } if (preg_match('/(.*)\\b(' . $regexIrregular . ')$/i', $word, $regs)) { $plural = substr($word, 0, 1) . substr($irregular[static::lower($regs[2])], 1); return static::$_pluralized[$word] = $regs[1] . $plural; } foreach ($rules as $rule => $replacement) { if (preg_match($rule, $word)) { return static::$_pluralized[$word] = preg_replace($rule, $replacement, $word); } } return static::$_pluralized[$word] = $word; }
Changes the form of a word from singular to plural. @param string $word Word in singular form. @return string Word in plural form.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L283-L315
schpill/thin
src/Inflector.php
Inflector.reset
public static function reset() { static::$_singularized = static::$_pluralized = array(); static::$_camelized = static::$_underscored = array(); static::$_humanized = array(); static::$_plural['regexUninflected'] = static::$_singular['regexUninflected'] = null; static::$_plural['regexIrregular'] = static::$_singular['regexIrregular'] = null; static::$_transliteration = array( '/à|á|å|â/' => 'a', '/è|é|ê|ẽ|ë/' => 'e', '/ì|í|î/' => 'i', '/ò|ó|ô|ø/' => 'o', '/ù|ú|ů|û/' => 'u', '/ç/' => 'c', '/ñ/' => 'n', '/ä|æ/' => 'ae', '/ö/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/ß/' => 'ss' ); }
php
public static function reset() { static::$_singularized = static::$_pluralized = array(); static::$_camelized = static::$_underscored = array(); static::$_humanized = array(); static::$_plural['regexUninflected'] = static::$_singular['regexUninflected'] = null; static::$_plural['regexIrregular'] = static::$_singular['regexIrregular'] = null; static::$_transliteration = array( '/à|á|å|â/' => 'a', '/è|é|ê|ẽ|ë/' => 'e', '/ì|í|î/' => 'i', '/ò|ó|ô|ø/' => 'o', '/ù|ú|ů|û/' => 'u', '/ç/' => 'c', '/ñ/' => 'n', '/ä|æ/' => 'ae', '/ö/' => 'oe', '/ü/' => 'ue', '/Ä/' => 'Ae', '/Ü/' => 'Ue', '/Ö/' => 'Oe', '/ß/' => 'ss' ); }
Clears local in-memory caches. Can be used to force a full-cache clear when updating inflection rules mid-way through request execution. @return void
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L365-L382
schpill/thin
src/Inflector.php
Inflector.camelize
public static function camelize($string, $spacify = true, $lazy = false) { return implode('', explode(' ', ucwords(implode(' ', explode('_', $string))))); }
php
public static function camelize($string, $spacify = true, $lazy = false) { return implode('', explode(' ', ucwords(implode(' ', explode('_', $string))))); }
Takes a under_scored word and turns it into a CamelCased or camelBack word @param string $word An under_scored or slugged word (i.e. `'red_bike'` or `'red-bike'`). @param boolean $cased If false, first character is not upper cased @return string CamelCased version of the word (i.e. `'RedBike'`).
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L391-L394
schpill/thin
src/Inflector.php
Inflector.underscore
public static function underscore($word) { if (isset(static::$_underscored[$word])) { return static::$_underscored[$word]; } return static::$_underscored[$word] = static::lower(static::slug($word, '_')); }
php
public static function underscore($word) { if (isset(static::$_underscored[$word])) { return static::$_underscored[$word]; } return static::$_underscored[$word] = static::lower(static::slug($word, '_')); }
Takes a CamelCased version of a word and turns it into an under_scored one. @param string $word CamelCased version of a word (i.e. `'RedBike'`). @return string Under_scored version of the workd (i.e. `'red_bike'`).
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L409-L416
schpill/thin
src/Inflector.php
Inflector.slug
public static function slug($string, $replacement = '-') { $map = static::$_transliteration + array( '/[^\w\s]/' => ' ', '/\\s+/' => $replacement, '/(?<=[a-z])([A-Z])/' => $replacement . '\\1', repl(':rep', preg_quote($replacement, '/'), '/^[:rep]+|[:rep]+$/') => '' ); return preg_replace(array_keys($map), array_values($map), $string); }
php
public static function slug($string, $replacement = '-') { $map = static::$_transliteration + array( '/[^\w\s]/' => ' ', '/\\s+/' => $replacement, '/(?<=[a-z])([A-Z])/' => $replacement . '\\1', repl(':rep', preg_quote($replacement, '/'), '/^[:rep]+|[:rep]+$/') => '' ); return preg_replace(array_keys($map), array_values($map), $string); }
Returns a string with all spaces converted to given replacement and non word characters removed. Maps special characters to ASCII using `Inflector::$_transliteration`, which can be updated using `Inflector::rules()`. @see Inflector::rules() @param string $string An arbitrary string to convert. @param string $replacement The replacement to use for spaces. @return string The converted string.
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L428-L437
schpill/thin
src/Inflector.php
Inflector.humanize
public static function humanize($word, $separator = '_') { if (isset(static::$_humanized[$key = $word . ':' . $separator])) { return static::$_humanized[$key]; } return static::$_humanized[$key] = ucwords(repl($separator, " ", $word)); }
php
public static function humanize($word, $separator = '_') { if (isset(static::$_humanized[$key = $word . ':' . $separator])) { return static::$_humanized[$key]; } return static::$_humanized[$key] = ucwords(repl($separator, " ", $word)); }
Takes an under_scored version of a word and turns it into an human- readable form by replacing underscores with a space, and by upper casing the initial character. @param string $word Under_scored version of a word (i.e. `'red_bike'`). @param string $separator The separator character used in the initial string. @return string Human readable version of the word (i.e. `'Red Bike'`).
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L447-L454
schpill/thin
src/Inflector.php
Inflector.deNamespace
public static function deNamespace($className) { $className = trim($className, '\\'); if ($lastSeparator = strrpos($className, '\\')) { $className = substr($className, $lastSeparator + 1); } return $className; }
php
public static function deNamespace($className) { $className = trim($className, '\\'); if ($lastSeparator = strrpos($className, '\\')) { $className = substr($className, $lastSeparator + 1); } return $className; }
Takes the namespace off the given class name. @param string the class name @return string the string without the namespace
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L900-L909
schpill/thin
src/Inflector.php
Inflector.getNamespace
public static function getNamespace($className) { $className = trim($className, '\\'); if ($lastSeparator = strrpos($className, '\\')) { return substr($className, 0, $lastSeparator + 1); } return ''; }
php
public static function getNamespace($className) { $className = trim($className, '\\'); if ($lastSeparator = strrpos($className, '\\')) { return substr($className, 0, $lastSeparator + 1); } return ''; }
Returns the namespace of the given class name. @param string $class_name the class name @return string the string without the namespace
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L917-L926
schpill/thin
src/Inflector.php
Inflector.limit
public static function limit($value, $limit = 100, $end = '...') { if (static::length($value) <= $limit) { return $value; } return mb_substr($value, 0, $limit, 'utf8') . $end; }
php
public static function limit($value, $limit = 100, $end = '...') { if (static::length($value) <= $limit) { return $value; } return mb_substr($value, 0, $limit, 'utf8') . $end; }
Limit the number of characters in a string. <code> // Returns "hel..." echo Inflector::limit('hello word', 3); // Limit the number of characters and append a custom ending echo Inflector::limit('hello word', 3, '---'); </code> @param string $value @param int $limit @param string $end @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L960-L967
schpill/thin
src/Inflector.php
Inflector.limitExact
public static function limitExact($value, $limit = 100, $end = '...') { if (static::length($value) <= $limit) { return $value; } $limit -= static::length($end); return static::limit($value, $limit, $end); }
php
public static function limitExact($value, $limit = 100, $end = '...') { if (static::length($value) <= $limit) { return $value; } $limit -= static::length($end); return static::limit($value, $limit, $end); }
Limit the number of chracters in a string including custom ending <code> // Returns "hello..." echo Inflector::limitExact('hello word', 9); // Limit the number of characters and append a custom ending echo Inflector::limitExact('hello word', 9, '---'); </code> @param string $value @param int $limit @param string $end @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L985-L994
schpill/thin
src/Inflector.php
Inflector.words
public static function words($value, $words = 100, $end = '...') { if (trim($value) == '') { return ''; } preg_match('/^\s*+(?:\S++\s*+){1,' . $words . '}/u', $value, $matches); if (static::length($value) == static::length($matches[0])) { $end = ''; } return rtrim($matches[0]) . $end; }
php
public static function words($value, $words = 100, $end = '...') { if (trim($value) == '') { return ''; } preg_match('/^\s*+(?:\S++\s*+){1,' . $words . '}/u', $value, $matches); if (static::length($value) == static::length($matches[0])) { $end = ''; } return rtrim($matches[0]) . $end; }
Limit the number of words in a string. <code> // Returns "This is a..." echo Inflector::words('This is a sentence.', 3); // Limit the number of words and append a custom ending echo Inflector::words('This is a sentence.', 3, '---'); </code> @param string $value @param int $words @param string $end @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L1031-L1044
schpill/thin
src/Inflector.php
Inflector.slugify
public static function slugify($title, $separator = '-') { $title = preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $title); // Remove all characters that are not the separator, letters, numbers, or whitespace. $title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', static::lower($title)); // Replace all separator characters and whitespace by a single separator $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title); return trim($title, $separator); }
php
public static function slugify($title, $separator = '-') { $title = preg_replace('/[^\x09\x0A\x0D\x20-\x7E]/', '', $title); // Remove all characters that are not the separator, letters, numbers, or whitespace. $title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', static::lower($title)); // Replace all separator characters and whitespace by a single separator $title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title); return trim($title, $separator); }
Generate a URL friendly "slug" from a given string. <code> // Returns "this-is-my-blog-post" $slug = Inflector::slugify('This is my blog post!'); // Returns "this_is_my_blog_post" $slug = Inflector::slugify('This is my blog post!', '_'); </code> @param string $title @param string $separator @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L1061-L1072
schpill/thin
src/Inflector.php
Inflector.random2
public static function random2($length = 16) { if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length * 2); if ($bytes === false) { throw new Exception('Unable to generate random string.'); } return substr(repl(array('/', '+', '='), '', base64_encode($bytes)), 0, $length); } return static::quickRandom($length); }
php
public static function random2($length = 16) { if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length * 2); if ($bytes === false) { throw new Exception('Unable to generate random string.'); } return substr(repl(array('/', '+', '='), '', base64_encode($bytes)), 0, $length); } return static::quickRandom($length); }
Generate a more truly "random" alpha-numeric string. @param int $length @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L1179-L1192
schpill/thin
src/Inflector.php
Inflector.snake
public static function snake($value, $delimiter = '_') { $replace = '$1' . $delimiter . '$2'; return ctype_lower($value) ? $value : static::lower(preg_replace('/(.)([A-Z])/', $replace, $value)); }
php
public static function snake($value, $delimiter = '_') { $replace = '$1' . $delimiter . '$2'; return ctype_lower($value) ? $value : static::lower(preg_replace('/(.)([A-Z])/', $replace, $value)); }
Convert a string to snake case. @param string $value @param string $delimiter @return string
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Inflector.php#L1216-L1220
diatem-net/jin-social
src/Social/Google/Plus/GooglePlus.php
GooglePlus.query
public function query($query, $params = array()) { $curl = new Curl(); $params['key'] = $this->server_key; $result = json_decode($curl->call(self::GOOGLEPLUS_API_URL . trim($query, '/') . '?' . http_build_query($params), array(), 'GET', true), true); if(!isset($result['error'])) { return $result; } return $this->debug_mode ? $result['error']['message'] : null; }
php
public function query($query, $params = array()) { $curl = new Curl(); $params['key'] = $this->server_key; $result = json_decode($curl->call(self::GOOGLEPLUS_API_URL . trim($query, '/') . '?' . http_build_query($params), array(), 'GET', true), true); if(!isset($result['error'])) { return $result; } return $this->debug_mode ? $result['error']['message'] : null; }
Effectue une requête directe sur l'API @param string $query Requête @param array $params (optional) Paramètres @return array Tableau de données
https://github.com/diatem-net/jin-social/blob/c49bc8d1b28264ae58e0af9e0452c8d17623e25d/src/Social/Google/Plus/GooglePlus.php#L52-L61
Phpillip/phpillip
src/Console/Model/Logger.php
Logger.log
public function log($message) { if ($this->progress) { $this->progress->setMessage($message); $this->logs[] = $message; } else { $this->output->writeLn($message); } }
php
public function log($message) { if ($this->progress) { $this->progress->setMessage($message); $this->logs[] = $message; } else { $this->output->writeLn($message); } }
Log @param string $message
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Model/Logger.php#L50-L58
Phpillip/phpillip
src/Console/Model/Logger.php
Logger.getProgress
public function getProgress($total = null) { if (!$this->progress || $this->progress->getMaxSteps() === $this->progress->getProgress()) { $this->progress = new ProgressBar($this->output, $total); } return $this->progress; }
php
public function getProgress($total = null) { if (!$this->progress || $this->progress->getMaxSteps() === $this->progress->getProgress()) { $this->progress = new ProgressBar($this->output, $total); } return $this->progress; }
Get progress bar instance @param integer $total @return ProgressBar
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Model/Logger.php#L67-L74
Phpillip/phpillip
src/Console/Model/Logger.php
Logger.finish
public function finish() { if ($this->progress) { $this->progress->finish(); $this->progress = null; $this->flush(); } }
php
public function finish() { if ($this->progress) { $this->progress->finish(); $this->progress = null; $this->flush(); } }
Finish progress
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Model/Logger.php#L99-L106
Phpillip/phpillip
src/Console/Model/Logger.php
Logger.flush
public function flush() { if (!$this->progress) { $this->log(''); foreach ($this->logs as $message) { $this->log($message); } $this->logs = []; } }
php
public function flush() { if (!$this->progress) { $this->log(''); foreach ($this->logs as $message) { $this->log($message); } $this->logs = []; } }
Flush message queue
https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Console/Model/Logger.php#L111-L122
pilipinews/common
src/Converters/BlockquoteConverter.php
BlockquoteConverter.convert
public function convert(ElementInterface $element) { // Contents should have already been converted to Markdown by this point, // so we just need to add '>' symbols to each line. $markdown = ''; $quote = trim($element->getValue()); $lines = preg_split('/\r\n|\r|\n/', $quote); $total = count((array) $lines); foreach ($lines as $i => $line) { $markdown .= '> ' . $line . "\n"; $newline = $i + 1 === $total; $newline && $markdown .= "\n"; } return "\n\n" . $markdown; }
php
public function convert(ElementInterface $element) { // Contents should have already been converted to Markdown by this point, // so we just need to add '>' symbols to each line. $markdown = ''; $quote = trim($element->getValue()); $lines = preg_split('/\r\n|\r|\n/', $quote); $total = count((array) $lines); foreach ($lines as $i => $line) { $markdown .= '> ' . $line . "\n"; $newline = $i + 1 === $total; $newline && $markdown .= "\n"; } return "\n\n" . $markdown; }
Converts the specified element into a parsed string. @param \League\HTMLToMarkdown\ElementInterface $element @return string
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Converters/BlockquoteConverter.php#L22-L45
MovingImage24/VM6ApiClient
lib/Entity/EmbedCode.php
EmbedCode.getCode
public function getCode($className = 'video-player') { $code = $this->player_code; // HACKHACK: Replace the static width style property with a classname $code = preg_replace('#style="(.*?)"#', sprintf('class="%s"', $className), $code); // HACKHACK: Use regular expressions to magically append the unlock // token to the embed code URL if (!is_null($this->unlockToken)) { preg_match_all('#https://(.*?)&playerskin=([0-9]+)#', $code, $matches); if (count($matches[0]) > 0) { $code = str_replace( $matches[0][0], $matches[0][0].'&videounlocktoken2='.$this->unlockToken, $code ); } } if ($this->hiddenControlBar) { $code = $this->setHiddenControlBarAttribute($code); } return $code; }
php
public function getCode($className = 'video-player') { $code = $this->player_code; // HACKHACK: Replace the static width style property with a classname $code = preg_replace('#style="(.*?)"#', sprintf('class="%s"', $className), $code); // HACKHACK: Use regular expressions to magically append the unlock // token to the embed code URL if (!is_null($this->unlockToken)) { preg_match_all('#https://(.*?)&playerskin=([0-9]+)#', $code, $matches); if (count($matches[0]) > 0) { $code = str_replace( $matches[0][0], $matches[0][0].'&videounlocktoken2='.$this->unlockToken, $code ); } } if ($this->hiddenControlBar) { $code = $this->setHiddenControlBarAttribute($code); } return $code; }
{@inheritdoc}
https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/Entity/EmbedCode.php#L41-L66
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payment.php
Radial_RiskService_Sdk_Payment._serializeAccountID
protected function _serializeAccountID() { $isToken = $this->getIsToken(); $accountID = $this->getAccountID(); if( $isToken && $isToken != false && $isToken != "false" ) { return $accountID ? "<AccountID isToken=\"true\">{$accountID}</AccountID>" : ''; } else { return $accountID ? "<AccountID isToken=\"0\">{$accountID}</AccountID>" : ''; } }
php
protected function _serializeAccountID() { $isToken = $this->getIsToken(); $accountID = $this->getAccountID(); if( $isToken && $isToken != false && $isToken != "false" ) { return $accountID ? "<AccountID isToken=\"true\">{$accountID}</AccountID>" : ''; } else { return $accountID ? "<AccountID isToken=\"0\">{$accountID}</AccountID>" : ''; } }
Serialize the payment account unique id node if there's a valid value. @return string
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payment.php#L333-L344
phramework/phramework
src/Authentication/Manager.php
Manager.register
public static function register($implementation) { $object = new $implementation(); if (!($object instanceof \Phramework\Authentication\IAuthentication)) { throw new \Exception( 'Class is not implementing \Phramework\Authentication\IAuthentication' ); } self::$implementations[] = $object; }
php
public static function register($implementation) { $object = new $implementation(); if (!($object instanceof \Phramework\Authentication\IAuthentication)) { throw new \Exception( 'Class is not implementing \Phramework\Authentication\IAuthentication' ); } self::$implementations[] = $object; }
Register an authentication implementation. Implementation must implement `\Phramework\Authentication\IAuthentication` interface @param string $implementation implementation class @throws Exception
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Authentication/Manager.php#L31-L41
phramework/phramework
src/Authentication/Manager.php
Manager.check
public static function check($params, $method, $headers) { if (count(self::$implementations) !== 0 && !self::$userGetByEmailMethod) { throw new \Phramework\Exceptions\ServerException( 'getUserByEmail method is not set' ); } foreach (self::$implementations as $implementation) { if ($implementation->testProvidedMethod($params, $method, $headers)) { return $implementation->check($params, $method, $headers); } } return false; //Not found }
php
public static function check($params, $method, $headers) { if (count(self::$implementations) !== 0 && !self::$userGetByEmailMethod) { throw new \Phramework\Exceptions\ServerException( 'getUserByEmail method is not set' ); } foreach (self::$implementations as $implementation) { if ($implementation->testProvidedMethod($params, $method, $headers)) { return $implementation->check($params, $method, $headers); } } return false; //Not found }
Check user's authentication This method iterates through all available authentication implementations tests in priorioty order which of them might be provided and executes @param array $params Request parameters @param string $method Request method @param array $headers Request headers @return array|false Returns false on error or the user object on success @throws Phramework\Exceptions\ServerException
https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/Authentication/Manager.php#L61-L76
lechimp-p/flightcontrol
src/Recursor.php
Recursor.filter
public function filter(\Closure $predicate) { $filter = array(); $filter[0] = function(FixedFDirectory $obj) use ($predicate, &$filter) { return $obj ->filter($predicate) ->map(function(FSObject $obj) use ($predicate, &$filter) { if ($obj->isFile()) { return $obj; } return $filter[0]($obj); }); }; return new Recursor($filter[0]($this->directory)); }
php
public function filter(\Closure $predicate) { $filter = array(); $filter[0] = function(FixedFDirectory $obj) use ($predicate, &$filter) { return $obj ->filter($predicate) ->map(function(FSObject $obj) use ($predicate, &$filter) { if ($obj->isFile()) { return $obj; } return $filter[0]($obj); }); }; return new Recursor($filter[0]($this->directory)); }
Get a recursor that folds all files in this recursor that match the provided predicate and the objects below that match the predicate as well. Won't recurse over directories that do not match the predicate! @param \Closure $predicate (FSObject -> Bool) @return Recursor
https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/Recursor.php#L39-L52
lechimp-p/flightcontrol
src/Recursor.php
Recursor.cata
public function cata(\Closure $trans) { return $trans( $this->directory->unfix()->fmap(function(FSObject $obj) use ($trans) { if ($obj->isFile()) { return $trans($obj); } assert($obj instanceof FixedFDirectory); return $obj->cata($trans); })); }
php
public function cata(\Closure $trans) { return $trans( $this->directory->unfix()->fmap(function(FSObject $obj) use ($trans) { if ($obj->isFile()) { return $trans($obj); } assert($obj instanceof FixedFDirectory); return $obj->cata($trans); })); }
We could also use the catamorphism on this to do recursion, as we have an unfix and an underlying fmap from the FDirectory. Supply a function $trans from File|FDirectory a to a that flattens (folds) a directory. Will start the directories where only files are included, folds them and then proceeds upwards. The return type should be 'a' (from the function $trans) instead of mixed, but we can't express that fact correctly in the docstring typing. @param \Closure $trans File|FDirectory a -> a @return mixed
https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/Recursor.php#L69-L77
lechimp-p/flightcontrol
src/Recursor.php
Recursor.foldFiles
public function foldFiles($start_value, \Closure $fold_with) { foreach ($this->allFiles() as $file) { $start_value = $fold_with($start_value, $file); } return $start_value; }
php
public function foldFiles($start_value, \Closure $fold_with) { foreach ($this->allFiles() as $file) { $start_value = $fold_with($start_value, $file); } return $start_value; }
Fold over all files in this directory and subjacent directories. Start with an initial value of some type and a function from that type and File to a new value of the type. Will successively feed all files and the resulting values to that function. @param mixed $start_value @param \Closure $fold_with a -> File -> a @return Recursor
https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/Recursor.php#L100-L105
lechimp-p/flightcontrol
src/Recursor.php
Recursor.allFiles
public function allFiles() { return $this->cata(function(FSObject $obj) { if ($obj->isFile()) { return array($obj); } assert($obj instanceof FDirectory); $fcontents = $obj->fcontents(); if (empty($fcontents)) { return $fcontents; } return call_user_func_array("array_merge", $fcontents); }); }
php
public function allFiles() { return $this->cata(function(FSObject $obj) { if ($obj->isFile()) { return array($obj); } assert($obj instanceof FDirectory); $fcontents = $obj->fcontents(); if (empty($fcontents)) { return $fcontents; } return call_user_func_array("array_merge", $fcontents); }); }
Get a list of all files in the directory and subjacent directories. @return File[]
https://github.com/lechimp-p/flightcontrol/blob/be7698183b44787f1b3d4a16d739655388e569ae/src/Recursor.php#L112-L125
Ekstazi/yii2-crud-actions
src/actions/Action.php
Action.ensureAccess
protected function ensureAccess($params = []) { if (!isset($this->checkAccess)) return; $params['action'] = $this; if (call_user_func($this->checkAccess, $params)) return; $user = \Yii::$app->user; if ($user->getIsGuest()) $user->loginRequired(); else throw new ForbiddenHttpException(\Yii::t( Constants::MSG_CATEGORY_NAME, 'You are not allowed to perform this action.' )); }
php
protected function ensureAccess($params = []) { if (!isset($this->checkAccess)) return; $params['action'] = $this; if (call_user_func($this->checkAccess, $params)) return; $user = \Yii::$app->user; if ($user->getIsGuest()) $user->loginRequired(); else throw new ForbiddenHttpException(\Yii::t( Constants::MSG_CATEGORY_NAME, 'You are not allowed to perform this action.' )); }
Ensure this action is allowed for current user @param array $params Params to be passed to {$this->checkAccess} @throws ForbiddenHttpException
https://github.com/Ekstazi/yii2-crud-actions/blob/38029fcfc1fac662604b3cabc08ec6ccacb94c57/src/actions/Action.php#L66-L86
tigron/skeleton-error
lib/Skeleton/Error/Detector/Whoops.php
Whoops.detect
public static function detect($html, &$error = '') { if (!class_exists('Whoops\Run')) { return false; } if (strpos($html, 'class="Whoops container"') != false) { // temporarily disables libxml warnings libxml_use_internal_errors(true); $dom = new \DOMDocument(); $dom->loadHTML($html); $xpath = new \DOMXpath($dom); $results = $xpath->query("//span[@id='plain-exception']"); libxml_use_internal_errors(false); if (!is_null($results)) { $error = $results[0]->nodeValue; } return true; } return false; }
php
public static function detect($html, &$error = '') { if (!class_exists('Whoops\Run')) { return false; } if (strpos($html, 'class="Whoops container"') != false) { // temporarily disables libxml warnings libxml_use_internal_errors(true); $dom = new \DOMDocument(); $dom->loadHTML($html); $xpath = new \DOMXpath($dom); $results = $xpath->query("//span[@id='plain-exception']"); libxml_use_internal_errors(false); if (!is_null($results)) { $error = $results[0]->nodeValue; } return true; } return false; }
Function detect Takes care of detecting if a Whoops error was passed and if true extracting the error code to return it by reference @access public @param string $html code of the page to be analyzed @param string $error the error code found (if any) @return bool does the page contain an error
https://github.com/tigron/skeleton-error/blob/c0671ad52a4386d95179f1c47bedfdf754ee3611/lib/Skeleton/Error/Detector/Whoops.php#L25-L47
pmdevelopment/tool-bundle
Framework/Model/SendMailFormModel.php
SendMailFormModel.getSwiftMessage
public function getSwiftMessage() { $message = \Swift_Message::newInstance(); if (true === is_array($this->getRecipient())) { $recipient = $this->getRecipient(); } else { $recipient = [ $this->getRecipient(), ]; }; $message ->setSubject($this->getSubject()) ->setFrom( [ $this->getSender(), ] ) ->setTo($recipient) ->setBody($this->getMessage()); if (0 < count($this->getAttachments())) { foreach ($this->getAttachments() as $attachment) { $message->attach($attachment); } } return $message; }
php
public function getSwiftMessage() { $message = \Swift_Message::newInstance(); if (true === is_array($this->getRecipient())) { $recipient = $this->getRecipient(); } else { $recipient = [ $this->getRecipient(), ]; }; $message ->setSubject($this->getSubject()) ->setFrom( [ $this->getSender(), ] ) ->setTo($recipient) ->setBody($this->getMessage()); if (0 < count($this->getAttachments())) { foreach ($this->getAttachments() as $attachment) { $message->attach($attachment); } } return $message; }
Get Swift Message @return Swift_Mime_Message
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Model/SendMailFormModel.php#L161-L190
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/GCM/Response.php
Response.processResponse
public function processResponse() { $response = $this->response; $statusCode = $response->getStatusCode(); $this->checkResponseCode($statusCode); $encodedMessage = $response->getContent(); $message = $this->decodeMessage($encodedMessage); $this->checkMessageStatus($message); $this->checkMessageResult($message, $this->recipients); }
php
public function processResponse() { $response = $this->response; $statusCode = $response->getStatusCode(); $this->checkResponseCode($statusCode); $encodedMessage = $response->getContent(); $message = $this->decodeMessage($encodedMessage); $this->checkMessageStatus($message); $this->checkMessageResult($message, $this->recipients); }
{@inheritdoc}
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/GCM/Response.php#L52-L64
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/GCM/Response.php
Response.checkResponseCode
private function checkResponseCode($responseCode) { switch ($responseCode) { case self::REQUEST_HAS_SUCCEED_CODE: break; case self::MALFORMED_NOTIFICATION_CODE: throw new MalformedNotificationException( "The request could not be parsed as JSON, or it contained invalid fields", self::MALFORMED_NOTIFICATION_CODE ); case self::AUTHENTICATION_ERROR_CODE: throw new DispatchMessageException( "There was an error authenticating the sender account.", self::AUTHENTICATION_ERROR_CODE ); default: throw new RuntimeException( "Unknown error occurred while sending notification." ); } }
php
private function checkResponseCode($responseCode) { switch ($responseCode) { case self::REQUEST_HAS_SUCCEED_CODE: break; case self::MALFORMED_NOTIFICATION_CODE: throw new MalformedNotificationException( "The request could not be parsed as JSON, or it contained invalid fields", self::MALFORMED_NOTIFICATION_CODE ); case self::AUTHENTICATION_ERROR_CODE: throw new DispatchMessageException( "There was an error authenticating the sender account.", self::AUTHENTICATION_ERROR_CODE ); default: throw new RuntimeException( "Unknown error occurred while sending notification." ); } }
Checks if response has succeed code or request was rejected @param int $responseCode @throws MalformedNotificationException @throws DispatchMessageException @throws RuntimeException
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/GCM/Response.php#L89-L112
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/GCM/Response.php
Response.checkMessageStatus
private function checkMessageStatus($message) { if (!$message || $message->success == 0 || $message->failure > 0) { throw new DispatchMessageException( sprintf("%d messages could not be processed", $message->failure) ); } }
php
private function checkMessageStatus($message) { if (!$message || $message->success == 0 || $message->failure > 0) { throw new DispatchMessageException( sprintf("%d messages could not be processed", $message->failure) ); } }
Checks message status @param \stdClass $message
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/GCM/Response.php#L119-L126
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/GCM/Response.php
Response.checkMessageResult
private function checkMessageResult($message, \ArrayIterator $recipients) { $hasDeviceError = false; $recipientCount = $recipients->count(); for ($i = 0; $i <= $recipientCount; $i++) { if (isset($message->results[$i]['registration_id'])) { $hasDeviceError = true; $recipients->offsetGet($i)->setIdentifierToReplaceTo($message->results[$i]['registration_id']); } if (isset($message->results[$i]['error'])) { $hasDeviceError = true; $error = $message->results[$i]['error']; $this->processError($error, $recipients->offsetGet($i)); } } if ($hasDeviceError) { throw new InvalidRecipientException("Device identifier error status", $recipients); } }
php
private function checkMessageResult($message, \ArrayIterator $recipients) { $hasDeviceError = false; $recipientCount = $recipients->count(); for ($i = 0; $i <= $recipientCount; $i++) { if (isset($message->results[$i]['registration_id'])) { $hasDeviceError = true; $recipients->offsetGet($i)->setIdentifierToReplaceTo($message->results[$i]['registration_id']); } if (isset($message->results[$i]['error'])) { $hasDeviceError = true; $error = $message->results[$i]['error']; $this->processError($error, $recipients->offsetGet($i)); } } if ($hasDeviceError) { throw new InvalidRecipientException("Device identifier error status", $recipients); } }
Check message result @param \stdClass $message @param \ArrayIterator $recipients
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/GCM/Response.php#L134-L156
diasbruno/stc
lib/stc/Config.php
Config.load
public function load($data_folder = '') { $loader = new DataLoader(); $this->data = $loader->load($data_folder, '/config.json'); if (!$this->validator->validate($this->data)) { throw new \Exception('Config.json fail.'); } }
php
public function load($data_folder = '') { $loader = new DataLoader(); $this->data = $loader->load($data_folder, '/config.json'); if (!$this->validator->validate($this->data)) { throw new \Exception('Config.json fail.'); } }
Load files from a given directory. @param $data_folder string | The folder name. @return array
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/Config.php#L39-L46
diasbruno/stc
lib/stc/Config.php
Config.getOptional
public function getOptional($key, $defaultValue = null) { if (array_key_exists($key, $this->data)) { return $this->data[$key]; } return $defaultValue; }
php
public function getOptional($key, $defaultValue = null) { if (array_key_exists($key, $this->data)) { return $this->data[$key]; } return $defaultValue; }
Use this method for optional values. @param $key string | The key name. @return object
https://github.com/diasbruno/stc/blob/43f62c3b28167bff76274f954e235413a9e9c707/lib/stc/Config.php#L82-L88
bruno-barros/w.eloquent-framework
src/weloquent/Providers/OptimizeServiceProvider.php
OptimizeServiceProvider.registerOptimizeCommand
protected function registerOptimizeCommand() { $this->app->bindShared('command.optimize', function($app) { return new \Weloquent\Core\Console\OptimizeCommand($app['composer']); }); }
php
protected function registerOptimizeCommand() { $this->app->bindShared('command.optimize', function($app) { return new \Weloquent\Core\Console\OptimizeCommand($app['composer']); }); }
Register the optimize command. @return void
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Providers/OptimizeServiceProvider.php#L35-L41
asaritech/ukey1-php-sdk
src/Ukey1/Endpoints/Authentication/SystemScopes.php
SystemScopes.execute
public function execute() { if ($this->executed) { return; } $request = new Request(Request::GET); $request->setHost($this->app->getHost()) ->setEndpoint(self::ENDPOINT) ->setCredentials($this->app->getAppId(), $this->app->getSecretKey()); if ($this->accessToken) { $request->setAccessToken($this->accessToken); } $result = $request->send(); $data = $result->getData(); if (!(isset($data["permissions"]))) { throw new EndpointException("Invalid result structure: " . $result->getBody()); } $this->scopes = $data["permissions"]; $this->executed = true; if (isset($data["rejected-permissions"])) { $this->rejected = $data["rejected-permissions"]; } }
php
public function execute() { if ($this->executed) { return; } $request = new Request(Request::GET); $request->setHost($this->app->getHost()) ->setEndpoint(self::ENDPOINT) ->setCredentials($this->app->getAppId(), $this->app->getSecretKey()); if ($this->accessToken) { $request->setAccessToken($this->accessToken); } $result = $request->send(); $data = $result->getData(); if (!(isset($data["permissions"]))) { throw new EndpointException("Invalid result structure: " . $result->getBody()); } $this->scopes = $data["permissions"]; $this->executed = true; if (isset($data["rejected-permissions"])) { $this->rejected = $data["rejected-permissions"]; } }
Executes an API request @throws \Ukey1\Exceptions\EndpointException
https://github.com/asaritech/ukey1-php-sdk/blob/a4a306b9c71db8644dfd85e0e231f2b2b21bdd3a/src/Ukey1/Endpoints/Authentication/SystemScopes.php#L85-L113
PhoxPHP/Glider
src/Events/EventManager.php
EventManager.listenTo
public static function listenTo(String $eventId, $callback) { if (!in_array(gettype($callback), ['array', 'object', 'closure'])) { return false; } EventManager::$listeners[$eventId][] = $callback; }
php
public static function listenTo(String $eventId, $callback) { if (!in_array(gettype($callback), ['array', 'object', 'closure'])) { return false; } EventManager::$listeners[$eventId][] = $callback; }
Creates a new listener. Two parameters are required. The eventId that will be used to track the current event and the callback which can be either an array or a closure. @param $eventId <String> @param $callback <Mixed> @access public @static @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Events/EventManager.php#L75-L82
PhoxPHP/Glider
src/Events/EventManager.php
EventManager.dispatchEvent
public function dispatchEvent(String $eventId, $subscriber=null) { if (isset(EventManager::$listeners[$eventId])) { foreach(EventManager::$listeners[$eventId] as $listener) { call_user_func_array($listener, [$subscriber]); } } }
php
public function dispatchEvent(String $eventId, $subscriber=null) { if (isset(EventManager::$listeners[$eventId])) { foreach(EventManager::$listeners[$eventId] as $listener) { call_user_func_array($listener, [$subscriber]); } } }
Dispatches an event with the @param $eventId only if it exists. @param $eventId <String> @param $subscriber <Kit\Glider\Events\Contract\Subscriber> @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Events/EventManager.php#L92-L99
PhoxPHP/Glider
src/Events/EventManager.php
EventManager.attachSubscriber
public function attachSubscriber(Subscriber $subscriber) { $listeners = $subscriber->getRegisteredEvents(); foreach($listeners as $id => $listener) { EventManager::listenTo($id, array($subscriber, $listener)); } }
php
public function attachSubscriber(Subscriber $subscriber) { $listeners = $subscriber->getRegisteredEvents(); foreach($listeners as $id => $listener) { EventManager::listenTo($id, array($subscriber, $listener)); } }
This method attaches an event through it's subscribe object. List of events are loaded from the subscriber and added to the listeners. @param $subscriber <Kit\Glider\Events\Contract\Subcriber> @access public @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Events/EventManager.php#L109-L115
eloquent/endec
src/Endec.php
Endec.registerFilters
public static function registerFilters(Isolator $isolator = null) { $isolator = Isolator::get($isolator); $isolator->stream_filter_register( 'endec.base16-encode', 'Eloquent\Endec\Base16\Base16EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base16-decode', 'Eloquent\Endec\Base16\Base16DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32-encode', 'Eloquent\Endec\Base32\Base32EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32-decode', 'Eloquent\Endec\Base32\Base32DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32hex-encode', 'Eloquent\Endec\Base32\Base32HexEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32hex-decode', 'Eloquent\Endec\Base32\Base32HexDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64-encode', 'Eloquent\Endec\Base64\Base64EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64-decode', 'Eloquent\Endec\Base64\Base64DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64mime-encode', 'Eloquent\Endec\Base64\Base64MimeEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64mime-decode', 'Eloquent\Endec\Base64\Base64MimeDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64url-encode', 'Eloquent\Endec\Base64\Base64UrlEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64url-decode', 'Eloquent\Endec\Base64\Base64UrlDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.uri-encode', 'Eloquent\Endec\Uri\UriEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.uri-decode', 'Eloquent\Endec\Uri\UriDecodeNativeStreamFilter' ); }
php
public static function registerFilters(Isolator $isolator = null) { $isolator = Isolator::get($isolator); $isolator->stream_filter_register( 'endec.base16-encode', 'Eloquent\Endec\Base16\Base16EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base16-decode', 'Eloquent\Endec\Base16\Base16DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32-encode', 'Eloquent\Endec\Base32\Base32EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32-decode', 'Eloquent\Endec\Base32\Base32DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32hex-encode', 'Eloquent\Endec\Base32\Base32HexEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base32hex-decode', 'Eloquent\Endec\Base32\Base32HexDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64-encode', 'Eloquent\Endec\Base64\Base64EncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64-decode', 'Eloquent\Endec\Base64\Base64DecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64mime-encode', 'Eloquent\Endec\Base64\Base64MimeEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64mime-decode', 'Eloquent\Endec\Base64\Base64MimeDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64url-encode', 'Eloquent\Endec\Base64\Base64UrlEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.base64url-decode', 'Eloquent\Endec\Base64\Base64UrlDecodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.uri-encode', 'Eloquent\Endec\Uri\UriEncodeNativeStreamFilter' ); $isolator->stream_filter_register( 'endec.uri-decode', 'Eloquent\Endec\Uri\UriDecodeNativeStreamFilter' ); }
Register Endec's native stream filters. @param Isolator|null $isolator The isolator to use.
https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Endec.php#L26-L86
kmfk/slowdb
src/Collection.php
Collection.all
public function all() { $results = []; foreach ($this->index->getKeys() as $key) { $result = $this->get($key); $results[key($result)] = current($result); } return $results; }
php
public function all() { $results = []; foreach ($this->index->getKeys() as $key) { $result = $this->get($key); $results[key($result)] = current($result); } return $results; }
Returns all Key/Value pairs in the Colleciton @return array
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L65-L74
kmfk/slowdb
src/Collection.php
Collection.get
public function get($key) { $position = $this->getPosition($key); if (false !== $position) { return [$key => $this->file->read($position)]; } return false; }
php
public function get($key) { $position = $this->getPosition($key); if (false !== $position) { return [$key => $this->file->read($position)]; } return false; }
Retrieves the value based on the key @param mixed $key The key to fetch data for @return array
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L83-L91
kmfk/slowdb
src/Collection.php
Collection.count
public function count($match = null, $exact = false) { if (!is_null($match)) { $keys = $this->index->getKeys(); if ($exact) { $match = "^{$match}$"; } $matches = array_filter($keys, function($key) use ($match) { return preg_match("/{$match}/i", $key); }); return sizeof($matches); } return $this->index->count(); }
php
public function count($match = null, $exact = false) { if (!is_null($match)) { $keys = $this->index->getKeys(); if ($exact) { $match = "^{$match}$"; } $matches = array_filter($keys, function($key) use ($match) { return preg_match("/{$match}/i", $key); }); return sizeof($matches); } return $this->index->count(); }
Returns a count of Key/Value pairs in the Collection Optionally you can pass a an case-insensitive Expression to filter the count by @param string $match An expression to filter on @param boolean $exact Whether to do an exact match @return integer
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L104-L121
kmfk/slowdb
src/Collection.php
Collection.query
public function query($match) { $keys = $this->index->getKeys(); $matches = array_filter($keys, function($key) use ($match) { return preg_match("/{$match}/i", $key); }); $results = []; foreach ($matches as $match) { $result = $this->get($match); $results[key($result)] = current($result); } return $results; }
php
public function query($match) { $keys = $this->index->getKeys(); $matches = array_filter($keys, function($key) use ($match) { return preg_match("/{$match}/i", $key); }); $results = []; foreach ($matches as $match) { $result = $this->get($match); $results[key($result)] = current($result); } return $results; }
Queries for Keys matching a case insensitive expression @param string $match The expression to match against @return array
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L130-L144
kmfk/slowdb
src/Collection.php
Collection.set
public function set($key, $value) { $position = $this->getPosition($key); if (false !== $position) { $this->file->update($position, $key, $value); $this->rebuildIndex(); } else { $pos = $this->file->insert($key, $value); $this->index->set($key, $pos); } return true; }
php
public function set($key, $value) { $position = $this->getPosition($key); if (false !== $position) { $this->file->update($position, $key, $value); $this->rebuildIndex(); } else { $pos = $this->file->insert($key, $value); $this->index->set($key, $pos); } return true; }
Sets the Key/Value pair in the database @param mixed $key The key to store @param mixed $value The value to store @return bool
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L154-L166
kmfk/slowdb
src/Collection.php
Collection.remove
public function remove($key) { $position = $this->getPosition($key); if (false !== $position) { $this->file->remove($position); $this->rebuildIndex(); return true; } return false; }
php
public function remove($key) { $position = $this->getPosition($key); if (false !== $position) { $this->file->remove($position); $this->rebuildIndex(); return true; } return false; }
Remove a Value based on its Key @param mixed $key The key to remove @return bool
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L175-L186
kmfk/slowdb
src/Collection.php
Collection.drop
public function drop() { $filepath = $this->file->getFilePath(); unset($this->file); if (!file_exists($filepath)) { unlink($filepath); } return true; }
php
public function drop() { $filepath = $this->file->getFilePath(); unset($this->file); if (!file_exists($filepath)) { unlink($filepath); } return true; }
Removes the Collection database file @return bool
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L206-L217
kmfk/slowdb
src/Collection.php
Collection.getPosition
private function getPosition($key) { if ($this->index->containsKey($key)) { return $this->index->get($key); } return false; }
php
private function getPosition($key) { if ($this->index->containsKey($key)) { return $this->index->get($key); } return false; }
Get a Key/Value position by Key, if it exists - returns false if the key does not exist @param mixed $key The key to search the index for @return integer|bool
https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/Collection.php#L227-L234
wdbo/webdocbook
src/WebDocBook/FrontController.php
FrontController.boot
protected function boot() { try { Kernel::boot(); // Kernel::debug(); // the actual manifest if (true===file_exists(Kernel::getPath('app_manifest_filepath'))) { $manifest_data = FilesystemHelper::parseJson(Kernel::getPath('app_manifest_filepath')); if ($manifest_data) { Kernel::setConfig($manifest_data, 'manifest'); } else { throw new \Exception( sprintf('Can not parse app manifest "%s" JSON content!', Kernel::getPath('app_manifest_filepath', true)) ); } } else { throw new \Exception( sprintf('App manifest "%s" not found or is empty!', Kernel::getPath('app_manifest_filepath', true)) ); } } catch (\Exception $e) { // hard die for startup errors header('Content-Type: text/plain'); echo PHP_EOL.'[WebDocBook startup error] : '.PHP_EOL; echo PHP_EOL."\t".$e->getMessage().PHP_EOL; echo PHP_EOL.'-------------------------'.PHP_EOL; echo 'For more info, see the documentation online at <http://webdocbook.com/>.'.PHP_EOL; exit(1); } }
php
protected function boot() { try { Kernel::boot(); // Kernel::debug(); // the actual manifest if (true===file_exists(Kernel::getPath('app_manifest_filepath'))) { $manifest_data = FilesystemHelper::parseJson(Kernel::getPath('app_manifest_filepath')); if ($manifest_data) { Kernel::setConfig($manifest_data, 'manifest'); } else { throw new \Exception( sprintf('Can not parse app manifest "%s" JSON content!', Kernel::getPath('app_manifest_filepath', true)) ); } } else { throw new \Exception( sprintf('App manifest "%s" not found or is empty!', Kernel::getPath('app_manifest_filepath', true)) ); } } catch (\Exception $e) { // hard die for startup errors header('Content-Type: text/plain'); echo PHP_EOL.'[WebDocBook startup error] : '.PHP_EOL; echo PHP_EOL."\t".$e->getMessage().PHP_EOL; echo PHP_EOL.'-------------------------'.PHP_EOL; echo 'For more info, see the documentation online at <http://webdocbook.com/>.'.PHP_EOL; exit(1); } }
This must boot the system If an error occurred, a message is written "as is" on screen and the run stops here. @return void @see \WebDocBook\Kernel::boot()
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/FrontController.php#L94-L125
wdbo/webdocbook
src/WebDocBook/FrontController.php
FrontController.init
protected function init() { // WebDocBook booting $this->boot(); // the logger $this->logger = new Logger(array( 'directory' => Kernel::getPath('log'), 'logfile' => Kernel::getConfig('app:logfile', 'history'), 'error_logfile' => Kernel::getConfig('app:error_logfile', 'errors'), 'duplicate_errors' => false, )); // user configuration $internal_config = Kernel::getConfig('userconf', array()); $user_config_file = Kernel::getPath('user_config_filepath'); if (true===file_exists($user_config_file)) { $user_config = FilesystemHelper::parseIni($user_config_file); if (!empty($user_config)) { Kernel::setConfig($user_config, 'user_config'); } else { throw new Exception( sprintf('Can not read you configuration file "%s"!', Kernel::getPath('user_config_filepath', true)) ); } } else { Kernel::setConfig($internal_config, 'user_config'); } // creating the application default headers $charset = Kernel::getConfig('html:charset', 'utf-8'); $content_type = Kernel::getConfig('html:content-type', 'text/html'); $app_name = Kernel::getConfig('title', null, 'manifest'); $app_version = Kernel::getConfig('version', null, 'manifest'); $app_website = Kernel::getConfig('homepage', null, 'manifest'); $this->response->addHeader('Content-type', $content_type.'; charset: '.$charset); // expose app ? $expose_wdb = Kernel::getConfig('app:expose_webdocbook', true); if (true===$expose_wdb || 'true'===$expose_wdb || '1'===$expose_wdb) { $this->response->addHeader('Composed-by', $app_name.' '.$app_version.' ('.$app_website.')'); } // the template builder $this->setTemplateBuilder(new TemplateBuilder); // some PHP configs @date_default_timezone_set( Kernel::getConfig('user_config:timezone', 'Europe/London') ); // the internationalization $langs = Kernel::getConfig('languages:langs', array('en'=>'English')); $i18n_loader_opts = array( 'language_directory' => Kernel::getPath('i18n'), 'language_strings_db_directory' => Kernel::getPath('user_config'), 'language_strings_db_filename' => basename(Kernel::get('app_i18n_filepath')), 'force_rebuild' => true, 'available_languages' => array_combine(array_keys($langs), array_keys($langs)), ); if (Kernel::isDevMode()) { $i18n_loader_opts['show_untranslated'] = true; } $translator = I18n::getInstance(new I18n_Loader($i18n_loader_opts)); // language $def_ln = Kernel::getConfig('languages:default', 'auto'); if (!empty($def_ln) && $def_ln==='auto') { $translator->setDefaultFromHttp(); $def_ln = Kernel::getConfig('languages:fallback_language', 'en'); } $trans_ln = $translator->getLanguage(); if (empty($trans_ln)) { $translator->setLanguage($def_ln); } $this->getTemplateBuilder() ->getTwigEngine() ->addExtension(new I18n_Twig_Extension($translator)); }
php
protected function init() { // WebDocBook booting $this->boot(); // the logger $this->logger = new Logger(array( 'directory' => Kernel::getPath('log'), 'logfile' => Kernel::getConfig('app:logfile', 'history'), 'error_logfile' => Kernel::getConfig('app:error_logfile', 'errors'), 'duplicate_errors' => false, )); // user configuration $internal_config = Kernel::getConfig('userconf', array()); $user_config_file = Kernel::getPath('user_config_filepath'); if (true===file_exists($user_config_file)) { $user_config = FilesystemHelper::parseIni($user_config_file); if (!empty($user_config)) { Kernel::setConfig($user_config, 'user_config'); } else { throw new Exception( sprintf('Can not read you configuration file "%s"!', Kernel::getPath('user_config_filepath', true)) ); } } else { Kernel::setConfig($internal_config, 'user_config'); } // creating the application default headers $charset = Kernel::getConfig('html:charset', 'utf-8'); $content_type = Kernel::getConfig('html:content-type', 'text/html'); $app_name = Kernel::getConfig('title', null, 'manifest'); $app_version = Kernel::getConfig('version', null, 'manifest'); $app_website = Kernel::getConfig('homepage', null, 'manifest'); $this->response->addHeader('Content-type', $content_type.'; charset: '.$charset); // expose app ? $expose_wdb = Kernel::getConfig('app:expose_webdocbook', true); if (true===$expose_wdb || 'true'===$expose_wdb || '1'===$expose_wdb) { $this->response->addHeader('Composed-by', $app_name.' '.$app_version.' ('.$app_website.')'); } // the template builder $this->setTemplateBuilder(new TemplateBuilder); // some PHP configs @date_default_timezone_set( Kernel::getConfig('user_config:timezone', 'Europe/London') ); // the internationalization $langs = Kernel::getConfig('languages:langs', array('en'=>'English')); $i18n_loader_opts = array( 'language_directory' => Kernel::getPath('i18n'), 'language_strings_db_directory' => Kernel::getPath('user_config'), 'language_strings_db_filename' => basename(Kernel::get('app_i18n_filepath')), 'force_rebuild' => true, 'available_languages' => array_combine(array_keys($langs), array_keys($langs)), ); if (Kernel::isDevMode()) { $i18n_loader_opts['show_untranslated'] = true; } $translator = I18n::getInstance(new I18n_Loader($i18n_loader_opts)); // language $def_ln = Kernel::getConfig('languages:default', 'auto'); if (!empty($def_ln) && $def_ln==='auto') { $translator->setDefaultFromHttp(); $def_ln = Kernel::getConfig('languages:fallback_language', 'en'); } $trans_ln = $translator->getLanguage(); if (empty($trans_ln)) { $translator->setLanguage($def_ln); } $this->getTemplateBuilder() ->getTwigEngine() ->addExtension(new I18n_Twig_Extension($translator)); }
Initialize environment If an error occurred here, an error page may be displayable @throws \WebDocBook\Exception\Exception
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/FrontController.php#L134-L212
wdbo/webdocbook
src/WebDocBook/FrontController.php
FrontController.distribute
public function distribute($return = false) { $this->processSessionValues(); try { $routing = $this->request ->parseWDBRequest() ->getWDBRouting(); } catch (NotFoundException $e) { throw $e; } $this->processQueryArguments(); $input_file = $this->getInputFile(); if (empty($input_file)) { $input_path = $this->getInputPath(); if (!empty($input_path)) { $input_file = Kernel::getPath('web').trim($input_path, '/'); } } $result = null; if (!empty($routing)) { $ctrl_cls = $routing['controller_classname']; /* @var \WebDocBook\Abstracts\AbstractController $ctrl_obj */ $ctrl_obj = new $ctrl_cls(); $this->setController($ctrl_obj); $result = Helper::fetchArguments( $this->getController(), $routing['action'], array('path'=>$input_file) ); } if (empty($result) || !is_array($result) || (count($result)!=2 && count($result)!=3)) { $str = gettype($result); if (is_array($result)) { $str .= ' length '.count($result); } throw new RuntimeException( sprintf('A controller action must return a two or three entries array like [ template file , content (, params) ]! Received %s from class "%s::%s()".', $str, $routing['controller_classname'], $routing['action']) ); } else { $template = $result[0]; $content = $result[1]; $params = isset($result[2]) ? $result[2] : array(); } // debug if so if (!empty($_GET) && isset($_GET['debug'])) { Kernel::debug($this); } $this->display($content, $template, $params, true); }
php
public function distribute($return = false) { $this->processSessionValues(); try { $routing = $this->request ->parseWDBRequest() ->getWDBRouting(); } catch (NotFoundException $e) { throw $e; } $this->processQueryArguments(); $input_file = $this->getInputFile(); if (empty($input_file)) { $input_path = $this->getInputPath(); if (!empty($input_path)) { $input_file = Kernel::getPath('web').trim($input_path, '/'); } } $result = null; if (!empty($routing)) { $ctrl_cls = $routing['controller_classname']; /* @var \WebDocBook\Abstracts\AbstractController $ctrl_obj */ $ctrl_obj = new $ctrl_cls(); $this->setController($ctrl_obj); $result = Helper::fetchArguments( $this->getController(), $routing['action'], array('path'=>$input_file) ); } if (empty($result) || !is_array($result) || (count($result)!=2 && count($result)!=3)) { $str = gettype($result); if (is_array($result)) { $str .= ' length '.count($result); } throw new RuntimeException( sprintf('A controller action must return a two or three entries array like [ template file , content (, params) ]! Received %s from class "%s::%s()".', $str, $routing['controller_classname'], $routing['action']) ); } else { $template = $result[0]; $content = $result[1]; $params = isset($result[2]) ? $result[2] : array(); } // debug if so if (!empty($_GET) && isset($_GET['debug'])) { Kernel::debug($this); } $this->display($content, $template, $params, true); }
This will distribute the request and return the response @param bool $return @throws \WebDocBook\Exception\NotFoundException @throws \WebDocBook\Exception\RuntimeException if the controller action does not return a valid array @return void
https://github.com/wdbo/webdocbook/blob/7d4e806f674b6222c9a3e85bfed34e72bc9d584e/src/WebDocBook/FrontController.php#L238-L290
stonedz/pff2
src/modules/encryption/Encryption.php
Encryption.encrypt
public function encrypt($plaintext, $key = null) { if(null !== $key) { $this->_key = md5($key); } $td = mcrypt_module_open($this->_cypher, '', self::MODE, ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); mcrypt_generic_init($td, $this->_key, $iv); $crypttext = mcrypt_generic($td, $plaintext); mcrypt_generic_deinit($td); return base64_encode($iv . $crypttext); }
php
public function encrypt($plaintext, $key = null) { if(null !== $key) { $this->_key = md5($key); } $td = mcrypt_module_open($this->_cypher, '', self::MODE, ''); $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); mcrypt_generic_init($td, $this->_key, $iv); $crypttext = mcrypt_generic($td, $plaintext); mcrypt_generic_deinit($td); return base64_encode($iv . $crypttext); }
Encrypts a text @param string $plaintext the text to encrypt @param null|string $key User specified @return string
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/encryption/Encryption.php#L50-L61
stonedz/pff2
src/modules/encryption/Encryption.php
Encryption.decrypt
public function decrypt($crypttext, $key = null) { if(null !== $key) { $this->_key = md5($key); } $crypttext = base64_decode($crypttext); $plaintext = ''; $td = mcrypt_module_open($this->_cypher, '', self::MODE, ''); $ivsize = mcrypt_enc_get_iv_size($td); $iv = substr($crypttext, 0, $ivsize); $crypttext = substr($crypttext, $ivsize); if ($iv) { mcrypt_generic_init($td, $this->_key, $iv); $plaintext = mdecrypt_generic($td, $crypttext); } return trim($plaintext); }
php
public function decrypt($crypttext, $key = null) { if(null !== $key) { $this->_key = md5($key); } $crypttext = base64_decode($crypttext); $plaintext = ''; $td = mcrypt_module_open($this->_cypher, '', self::MODE, ''); $ivsize = mcrypt_enc_get_iv_size($td); $iv = substr($crypttext, 0, $ivsize); $crypttext = substr($crypttext, $ivsize); if ($iv) { mcrypt_generic_init($td, $this->_key, $iv); $plaintext = mdecrypt_generic($td, $crypttext); } return trim($plaintext); }
Decrypt a previously encrypted text @param string $crypttext @param null|string $key User specified key @return string
https://github.com/stonedz/pff2/blob/ec3b087d4d4732816f61ac487f0cb25511e0da88/src/modules/encryption/Encryption.php#L70-L86
Napp/aclcore
src/AclServiceProvider.php
AclServiceProvider.registerBladeDirectives
protected function registerBladeDirectives() { $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { $bladeCompiler->directive('hasrole', function ($role) { return "<?php if(has_role({$role})): ?>"; }); $bladeCompiler->directive('endhasrole', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('may', function ($permission) { return "<?php if(may({$permission})): ?>"; }); $bladeCompiler->directive('endmay', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('maynot', function ($permission) { return "<?php if(maynot({$permission})): ?>"; }); $bladeCompiler->directive('endmaynot', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('mayall', function ($permissions) { return "<?php if(mayall({$permissions})): ?>"; }); $bladeCompiler->directive('endmayall', function () { return '<?php endif; ?>'; }); }); }
php
protected function registerBladeDirectives() { $this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) { $bladeCompiler->directive('hasrole', function ($role) { return "<?php if(has_role({$role})): ?>"; }); $bladeCompiler->directive('endhasrole', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('may', function ($permission) { return "<?php if(may({$permission})): ?>"; }); $bladeCompiler->directive('endmay', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('maynot', function ($permission) { return "<?php if(maynot({$permission})): ?>"; }); $bladeCompiler->directive('endmaynot', function () { return '<?php endif; ?>'; }); $bladeCompiler->directive('mayall', function ($permissions) { return "<?php if(mayall({$permissions})): ?>"; }); $bladeCompiler->directive('endmayall', function () { return '<?php endif; ?>'; }); }); }
Register Blade directives. @return void
https://github.com/Napp/aclcore/blob/9f2f48fe0af4c50ed7cbbafe653761da42e39596/src/AclServiceProvider.php#L39-L70
devsdmf/annotations
src/Devsdmf/Annotations/DocParser.php
DocParser.setReflector
public function setReflector(\Reflector $reflector, $adapterDiscover = true) { if ($adapterDiscover) { $adapter = __NAMESPACE__ . '\\Adapter\\' . get_class($reflector) . 'Adapter'; if (class_exists($adapter)) { $this->setAdapter(new $adapter()); } else { throw new AdapterNotFoundException(sprintf('Adapter for "$s" objects was not found.',get_class($reflector))); } } $this->reflector = $reflector; return $this; }
php
public function setReflector(\Reflector $reflector, $adapterDiscover = true) { if ($adapterDiscover) { $adapter = __NAMESPACE__ . '\\Adapter\\' . get_class($reflector) . 'Adapter'; if (class_exists($adapter)) { $this->setAdapter(new $adapter()); } else { throw new AdapterNotFoundException(sprintf('Adapter for "$s" objects was not found.',get_class($reflector))); } } $this->reflector = $reflector; return $this; }
{@inheritdoc}
https://github.com/devsdmf/annotations/blob/e543ff84db3ecedf56a149c1be0fdd36dbb9e62f/src/Devsdmf/Annotations/DocParser.php#L44-L57
devsdmf/annotations
src/Devsdmf/Annotations/DocParser.php
DocParser.parse
public function parse($input = null, $delimiter = ' ') { if (is_null($input) && !is_null($this->reflector) && !is_null($this->adapter)) { $input = $this->adapter->getDocBlock($this->reflector); } $data = array(); preg_match_all('#@(.*?)\n#s', $input, $matches); $matches = $matches[0]; foreach ($matches as $annotation) { $annotation = trim($annotation); $annotation = explode($delimiter,$annotation); $key = str_replace('@','',$annotation[0]); unset($annotation[0]); $value = implode($delimiter,$annotation); if (isset($data[$key])) { if (is_array($data[$key])) { $data[$key][] = $value; } else { $old_value = $data[$key]; $data[$key] = array($old_value,$value); } } else { $data[$key] = $value; } } return $data; }
php
public function parse($input = null, $delimiter = ' ') { if (is_null($input) && !is_null($this->reflector) && !is_null($this->adapter)) { $input = $this->adapter->getDocBlock($this->reflector); } $data = array(); preg_match_all('#@(.*?)\n#s', $input, $matches); $matches = $matches[0]; foreach ($matches as $annotation) { $annotation = trim($annotation); $annotation = explode($delimiter,$annotation); $key = str_replace('@','',$annotation[0]); unset($annotation[0]); $value = implode($delimiter,$annotation); if (isset($data[$key])) { if (is_array($data[$key])) { $data[$key][] = $value; } else { $old_value = $data[$key]; $data[$key] = array($old_value,$value); } } else { $data[$key] = $value; } } return $data; }
{@inheritdoc}
https://github.com/devsdmf/annotations/blob/e543ff84db3ecedf56a149c1be0fdd36dbb9e62f/src/Devsdmf/Annotations/DocParser.php#L87-L119
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php
ServiceClientFactory.getServiceURL
public function getServiceURL($serviceName, $isFeedback = false) { $serviceName = NotificationServices::validateServiceName($serviceName); $serviceType = $isFeedback ? self::FEEDBACK_SERVICE : self::PUSH_SERVICE; $environment = $this->getEnvironment(); $serviceConfig = $this->getServiceConfig(); if (empty($serviceConfig[$serviceName][$serviceType][static::ENVIRONMENT_DEVELOPMENT])) { $environment = static::ENVIRONMENT_PRODUCTION; } if (empty($serviceConfig[$serviceName][$serviceType][$environment])) { throw new DomainException("Service url is not defined"); } return $serviceConfig[$serviceName][$serviceType][$environment]; }
php
public function getServiceURL($serviceName, $isFeedback = false) { $serviceName = NotificationServices::validateServiceName($serviceName); $serviceType = $isFeedback ? self::FEEDBACK_SERVICE : self::PUSH_SERVICE; $environment = $this->getEnvironment(); $serviceConfig = $this->getServiceConfig(); if (empty($serviceConfig[$serviceName][$serviceType][static::ENVIRONMENT_DEVELOPMENT])) { $environment = static::ENVIRONMENT_PRODUCTION; } if (empty($serviceConfig[$serviceName][$serviceType][$environment])) { throw new DomainException("Service url is not defined"); } return $serviceConfig[$serviceName][$serviceType][$environment]; }
Gets notification service url by service name @param string $serviceName @param bool $isFeedback @return array
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php#L148-L165
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php
ServiceClientFactory.createServiceClient
public function createServiceClient($serviceName, $isFeedback = false) { $serviceUrl = $this->getServiceURL($serviceName, $isFeedback); $clientClass = sprintf( 'Zbox\UnifiedPush\NotificationService\%s\%s', $serviceName, $isFeedback ? 'ServiceFeedbackClient' : 'ServiceClient' ); $credentials = $this->credentialsFactory->getCredentialsByService($serviceName); $clientConnection = new $clientClass($serviceUrl, $credentials); return $clientConnection; }
php
public function createServiceClient($serviceName, $isFeedback = false) { $serviceUrl = $this->getServiceURL($serviceName, $isFeedback); $clientClass = sprintf( 'Zbox\UnifiedPush\NotificationService\%s\%s', $serviceName, $isFeedback ? 'ServiceFeedbackClient' : 'ServiceClient' ); $credentials = $this->credentialsFactory->getCredentialsByService($serviceName); $clientConnection = new $clientClass($serviceUrl, $credentials); return $clientConnection; }
Creates client server connection by service name and sender credentials @param string $serviceName @param bool $isFeedback @return ServiceClientInterface
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php#L174-L188
zbox/UnifiedPush
src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php
ServiceClientFactory.loadServicesConfig
public function loadServicesConfig() { $configPath = $this->serviceConfigPath; if (!file_exists($configPath)) { throw new InvalidArgumentException( sprintf( "Service config file '%s' doesn`t exists", $configPath ) ); } $config = json_decode(file_get_contents($configPath), true); if (!is_array($config)) { throw new RuntimeException('Empty credentials config'); } $this->serviceConfig = $config; return $this; }
php
public function loadServicesConfig() { $configPath = $this->serviceConfigPath; if (!file_exists($configPath)) { throw new InvalidArgumentException( sprintf( "Service config file '%s' doesn`t exists", $configPath ) ); } $config = json_decode(file_get_contents($configPath), true); if (!is_array($config)) { throw new RuntimeException('Empty credentials config'); } $this->serviceConfig = $config; return $this; }
Load notification services connection data @return $this
https://github.com/zbox/UnifiedPush/blob/47da2d0577b18ac709cd947c68541014001e1866/src/Zbox/UnifiedPush/NotificationService/ServiceClientFactory.php#L195-L217
newestindustry/ginger-rest
src/Ginger/Format.php
Format.getFormatByAcceptHeader
public static function getFormatByAcceptHeader($header) { if(isset(self::$mimeMapper[$header])) { return self::$mimeMapper[$header]; } else { return self::$format; } }
php
public static function getFormatByAcceptHeader($header) { if(isset(self::$mimeMapper[$header])) { return self::$mimeMapper[$header]; } else { return self::$format; } }
getFormatByAcceptHeader function. @access public @static @param mixed $header @return void
https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/Format.php#L89-L96
hermajan/dobine
src/Connections/Environment.php
Environment.load
public static function load(string $filename) { if(class_exists(Dotenv::class)) { $dotenv = new Dotenv($filename); $dotenv->load(); } }
php
public static function load(string $filename) { if(class_exists(Dotenv::class)) { $dotenv = new Dotenv($filename); $dotenv->load(); } }
Loads environment variables. @param string $filename Path to the .env file.
https://github.com/hermajan/dobine/blob/0f18727923cfe06abbbfcd1d39b897633586ad05/src/Connections/Environment.php#L15-L20
hermajan/dobine
src/Connections/Environment.php
Environment.choose
public static function choose($environment = null) { if (!isset($environment)) { if(isset($_ENV["APP_ENV"])) { switch($_ENV["APP_ENV"]) { case "dev": case "development": default: $environment = Environment::DEVELOPMENT; break; case "stage": $environment = Environment::STAGE; break; case "prod": case "production": $environment = Environment::PRODUCTION; break; } } else { switch($_SERVER["SERVER_NAME"]) { case "localhost": $environment = Environment::DEVELOPMENT; break; default: $environment = Environment::PRODUCTION; break; } } } else { $environment = Environment::DEVELOPMENT; } return $environment; }
php
public static function choose($environment = null) { if (!isset($environment)) { if(isset($_ENV["APP_ENV"])) { switch($_ENV["APP_ENV"]) { case "dev": case "development": default: $environment = Environment::DEVELOPMENT; break; case "stage": $environment = Environment::STAGE; break; case "prod": case "production": $environment = Environment::PRODUCTION; break; } } else { switch($_SERVER["SERVER_NAME"]) { case "localhost": $environment = Environment::DEVELOPMENT; break; default: $environment = Environment::PRODUCTION; break; } } } else { $environment = Environment::DEVELOPMENT; } return $environment; }
Chooses environment. @param null|string $environment @return string
https://github.com/hermajan/dobine/blob/0f18727923cfe06abbbfcd1d39b897633586ad05/src/Connections/Environment.php#L27-L51
villermen/runescape-lookup-commons
src/ActivityFeed/ActivityFeed.php
ActivityFeed.getItemsAfter
public function getItemsAfter(ActivityFeedItem $targetItem): array { $newerItems = []; foreach($this->getItems() as $item) { if ($item->equals($targetItem)) { break; } $newerItems[] = $item; } return $newerItems; }
php
public function getItemsAfter(ActivityFeedItem $targetItem): array { $newerItems = []; foreach($this->getItems() as $item) { if ($item->equals($targetItem)) { break; } $newerItems[] = $item; } return $newerItems; }
Returns all feed items in this feed that occur after the given item. @param ActivityFeedItem $targetItem @return ActivityFeedItem[]
https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/ActivityFeed/ActivityFeed.php#L32-L45
villermen/runescape-lookup-commons
src/ActivityFeed/ActivityFeed.php
ActivityFeed.merge
public function merge(ActivityFeed $newerFeed): ActivityFeed { if (count($this->getItems()) > 0) { $prepend = $newerFeed->getItemsAfter($this->getItems()[0]); } else { $prepend = $newerFeed->getItems(); } return new ActivityFeed(array_merge($prepend, $this->getItems())); }
php
public function merge(ActivityFeed $newerFeed): ActivityFeed { if (count($this->getItems()) > 0) { $prepend = $newerFeed->getItemsAfter($this->getItems()[0]); } else { $prepend = $newerFeed->getItems(); } return new ActivityFeed(array_merge($prepend, $this->getItems())); }
Merges this ActivityFeed with a newer feed. Returns a new feed with all new items from the newerFeed prepended to it. @param ActivityFeed $newerFeed @return ActivityFeed
https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/ActivityFeed/ActivityFeed.php#L54-L63
kpicaza/GenBundle
Formatter/FieldFormatter.php
FieldFormatter.formatMappingsWithRelations
public function formatMappingsWithRelations($mappings, $associationMappings) { $formattedMappings = $this->formatMappings($mappings); return $this->formatRelationMappings($formattedMappings, $associationMappings); }
php
public function formatMappingsWithRelations($mappings, $associationMappings) { $formattedMappings = $this->formatMappings($mappings); return $this->formatRelationMappings($formattedMappings, $associationMappings); }
@param $mappings @param $associationMappings @return mixed
https://github.com/kpicaza/GenBundle/blob/bdc37d101718caca146b39e4358f5eb403b534db/Formatter/FieldFormatter.php#L18-L23
kpicaza/GenBundle
Formatter/FieldFormatter.php
FieldFormatter.formatMappings
public function formatMappings($mappings) { $types = $this->getTypes(); foreach ($mappings as $key => $mapping) { $mappings[$key] = $types[$mappings[$key]['type']]; } return $mappings; }
php
public function formatMappings($mappings) { $types = $this->getTypes(); foreach ($mappings as $key => $mapping) { $mappings[$key] = $types[$mappings[$key]['type']]; } return $mappings; }
@param $mappings @return mixed
https://github.com/kpicaza/GenBundle/blob/bdc37d101718caca146b39e4358f5eb403b534db/Formatter/FieldFormatter.php#L30-L39
kpicaza/GenBundle
Formatter/FieldFormatter.php
FieldFormatter.formatRelationMappings
protected function formatRelationMappings($mappings, $associationMappings) { $types = $this->getTypes(); foreach ($associationMappings as $fieldName => $relation) { if ($relation['type'] !== ClassMetadataInfo::ONE_TO_MANY) { $mappings[sprintf('%s_%s', $fieldName, 'id')] = $types['string']; } } return $mappings; }
php
protected function formatRelationMappings($mappings, $associationMappings) { $types = $this->getTypes(); foreach ($associationMappings as $fieldName => $relation) { if ($relation['type'] !== ClassMetadataInfo::ONE_TO_MANY) { $mappings[sprintf('%s_%s', $fieldName, 'id')] = $types['string']; } } return $mappings; }
@param $mappings @param $associationMappings @return mixed
https://github.com/kpicaza/GenBundle/blob/bdc37d101718caca146b39e4358f5eb403b534db/Formatter/FieldFormatter.php#L47-L58
apishka/easy-extend
source/Broker.php
Broker.getRouter
public function getRouter(string $router): RouterAbstract { if (!array_key_exists($router, $this->_routers)) $this->_routers[$router] = $this->getItem($router); return $this->_routers[$router]; }
php
public function getRouter(string $router): RouterAbstract { if (!array_key_exists($router, $this->_routers)) $this->_routers[$router] = $this->getItem($router); return $this->_routers[$router]; }
Get router instance @param string $router @return RouterAbstract
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Broker.php#L60-L66
apishka/easy-extend
source/Broker.php
Broker.isCorrectItem
protected function isCorrectItem(\ReflectionClass $reflector): bool { if ($reflector->isInstance($this)) return false; if (!$reflector->isSubclassOf(RouterAbstract::class)) return false; return true; }
php
protected function isCorrectItem(\ReflectionClass $reflector): bool { if ($reflector->isInstance($this)) return false; if (!$reflector->isSubclassOf(RouterAbstract::class)) return false; return true; }
Is correct item @param \ReflectionClass $reflector @return bool
https://github.com/apishka/easy-extend/blob/5e5c63c2509377abc3db6956e353623683703e09/source/Broker.php#L97-L106
fxpio/fxp-gluon
Form/Extension/DateExtension.php
DateExtension.buildView
public function buildView(FormView $view, FormInterface $form, array $options) { if (\in_array($options['widget'], ['text', 'choice'])) { BlockUtil::addAttributeClass($view, 'date-'.$options['widget'].'-wrapper'); if ($options['text_block']) { BlockUtil::addAttributeClass($view, 'date-'.$options['widget'].'-block'); } } }
php
public function buildView(FormView $view, FormInterface $form, array $options) { if (\in_array($options['widget'], ['text', 'choice'])) { BlockUtil::addAttributeClass($view, 'date-'.$options['widget'].'-wrapper'); if ($options['text_block']) { BlockUtil::addAttributeClass($view, 'date-'.$options['widget'].'-block'); } } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Form/Extension/DateExtension.php#L31-L40
fxpio/fxp-gluon
Form/Extension/DateExtension.php
DateExtension.finishView
public function finishView(FormView $view, FormInterface $form, array $options) { if ('text' === $options['widget']) { $date = new \DateTime('now - 23 years'); BlockUtil::addAttribute($view->children['year'], 'placeholder', $date->format('Y')); BlockUtil::addAttribute($view->children['month'], 'placeholder', 5); BlockUtil::addAttribute($view->children['day'], 'placeholder', 23); $view->children['year']->vars['translation_domain'] = false; $view->children['month']->vars['translation_domain'] = false; $view->children['day']->vars['translation_domain'] = false; $view->children['year']->vars['attr'] = array_merge( $view->children['year']->vars['attr'], $options['text_attr'] ); $view->children['month']->vars['attr'] = array_merge( $view->children['month']->vars['attr'], $options['text_attr'] ); $view->children['day']->vars['attr'] = array_merge( $view->children['day']->vars['attr'], $options['text_attr'] ); } if (isset($view->vars['date_pattern'])) { $view->vars['date_pattern'] = str_replace('/', '<span>/</span>', $view->vars['date_pattern']); $view->vars['date_pattern'] = str_replace('-', '<span>-</span>', $view->vars['date_pattern']); } }
php
public function finishView(FormView $view, FormInterface $form, array $options) { if ('text' === $options['widget']) { $date = new \DateTime('now - 23 years'); BlockUtil::addAttribute($view->children['year'], 'placeholder', $date->format('Y')); BlockUtil::addAttribute($view->children['month'], 'placeholder', 5); BlockUtil::addAttribute($view->children['day'], 'placeholder', 23); $view->children['year']->vars['translation_domain'] = false; $view->children['month']->vars['translation_domain'] = false; $view->children['day']->vars['translation_domain'] = false; $view->children['year']->vars['attr'] = array_merge( $view->children['year']->vars['attr'], $options['text_attr'] ); $view->children['month']->vars['attr'] = array_merge( $view->children['month']->vars['attr'], $options['text_attr'] ); $view->children['day']->vars['attr'] = array_merge( $view->children['day']->vars['attr'], $options['text_attr'] ); } if (isset($view->vars['date_pattern'])) { $view->vars['date_pattern'] = str_replace('/', '<span>/</span>', $view->vars['date_pattern']); $view->vars['date_pattern'] = str_replace('-', '<span>-</span>', $view->vars['date_pattern']); } }
{@inheritdoc}
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Form/Extension/DateExtension.php#L45-L76
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.generalServiceManager
public static function generalServiceManager(Iterable $serviceConfig = NULL, $selfRefNames= []) { if(!static::$serviceManager) { if(is_null($serviceConfig)) throw new ServiceException(sprintf("First call of %s must pass a service configuration", __METHOD__), 13); /** @var ServiceManager $man */ $man = static::$serviceManager = new static($serviceConfig); $man->selfReferenceNames = array_merge($man->selfReferenceNames, $selfRefNames); if($n = self::getGlobalVariableName()) $GLOBALS[$n] = $man; } return static::$serviceManager; }
php
public static function generalServiceManager(Iterable $serviceConfig = NULL, $selfRefNames= []) { if(!static::$serviceManager) { if(is_null($serviceConfig)) throw new ServiceException(sprintf("First call of %s must pass a service configuration", __METHOD__), 13); /** @var ServiceManager $man */ $man = static::$serviceManager = new static($serviceConfig); $man->selfReferenceNames = array_merge($man->selfReferenceNames, $selfRefNames); if($n = self::getGlobalVariableName()) $GLOBALS[$n] = $man; } return static::$serviceManager; }
Returns the service manager. The first call of this method should pass a service config info. @param iterable|NULL $serviceConfig @return ServiceManager
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L72-L85
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.get
public function get($serviceName) { $container = $this->serviceData[$serviceName] ?? NULL; if($container) { return $container->getInstance(); } if(in_array($serviceName, $this->getSelfReferenceNames())) return $this; $e = new UnknownServiceException("Service $serviceName is not registered", E_USER_ERROR); $e->setServiceName($serviceName); throw $e; }
php
public function get($serviceName) { $container = $this->serviceData[$serviceName] ?? NULL; if($container) { return $container->getInstance(); } if(in_array($serviceName, $this->getSelfReferenceNames())) return $this; $e = new UnknownServiceException("Service $serviceName is not registered", E_USER_ERROR); $e->setServiceName($serviceName); throw $e; }
Returns the instance of a requested service This method call fails if the service does not exist or something else went wrong during creating the service instance. @param string $serviceName @return object|null @throws UnknownServiceException
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L187-L199
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.set
public function set(string $serviceName, $object) { if(isset($this->serviceData[$serviceName]) || in_array($serviceName, $this->getSelfReferenceNames())) { if($this->replaceExistingServices()) { trigger_error("Service $serviceName is already registered", E_USER_NOTICE); } else { $e = new ServiceException("Service $serviceName is already registered"); $e->setServiceName($serviceName); throw $e; } } if(is_callable($object)) { $object = new CallbackContainer($object); } elseif (is_array($object)) { $object = new ConfiguredServiceContainer($serviceName, $object, $this); } elseif(!is_object($object)) { throw new ServiceException("Service Manager only allows objects to be service instances!"); } elseif(!($object instanceof ContainerInterface)) { $object = new StaticContainer($object); } $this->serviceData[$serviceName] = $object; }
php
public function set(string $serviceName, $object) { if(isset($this->serviceData[$serviceName]) || in_array($serviceName, $this->getSelfReferenceNames())) { if($this->replaceExistingServices()) { trigger_error("Service $serviceName is already registered", E_USER_NOTICE); } else { $e = new ServiceException("Service $serviceName is already registered"); $e->setServiceName($serviceName); throw $e; } } if(is_callable($object)) { $object = new CallbackContainer($object); } elseif (is_array($object)) { $object = new ConfiguredServiceContainer($serviceName, $object, $this); } elseif(!is_object($object)) { throw new ServiceException("Service Manager only allows objects to be service instances!"); } elseif(!($object instanceof ContainerInterface)) { $object = new StaticContainer($object); } $this->serviceData[$serviceName] = $object; }
Sets a service Accepted are: - Objects that implement ContainerInterface, their getInstance method call will be the service instance - A callback (note! Objects implementing __invoke are also callbacks!) to obtain the service instance - An array to load configured service - Any other object directly as service If replaceExistingServices() returns false, this method call fails with an already registered service. @param string $serviceName @param object|callable|ContainerInterface $object @throws ServiceException @see ServiceManager::replaceExistingServices() @see ServiceManager::__get()
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L231-L254
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.serviceExists
public function serviceExists(string $serviceName): bool { return isset($this->serviceData[$serviceName]) || in_array($serviceName, $this->getSelfReferenceNames()) ? true : false; }
php
public function serviceExists(string $serviceName): bool { return isset($this->serviceData[$serviceName]) || in_array($serviceName, $this->getSelfReferenceNames()) ? true : false; }
Looks, if a service with the given name is available @param string $serviceName @return bool
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L261-L263
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.isServiceLoaded
public function isServiceLoaded(string $serviceName): bool { if($this->serviceExists($serviceName)) { if(in_array($serviceName, $this->getSelfReferenceNames())) return true; /** @var ContainerInterface $container */ $container = $this->serviceData[$serviceName]; return $container->isInstanceLoaded(); } return false; }
php
public function isServiceLoaded(string $serviceName): bool { if($this->serviceExists($serviceName)) { if(in_array($serviceName, $this->getSelfReferenceNames())) return true; /** @var ContainerInterface $container */ $container = $this->serviceData[$serviceName]; return $container->isInstanceLoaded(); } return false; }
Looks, if a service with the given name is available and already is loaded. @param string $serviceName @return bool @see ServiceManager::serviceExists()
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L271-L281
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.setParameter
public function setParameter(string $paramName, $paramValue = NULL) { if($paramName) { if(is_null($paramValue) && isset($this->parameters[$paramName])) unset($this->parameters[$paramName]); else $this->parameters[$paramName] = $paramValue; } }
php
public function setParameter(string $paramName, $paramValue = NULL) { if($paramName) { if(is_null($paramValue) && isset($this->parameters[$paramName])) unset($this->parameters[$paramName]); else $this->parameters[$paramName] = $paramValue; } }
Parameters can be dynamic markers in the configuration that are resolved right before the service instance is required. @example Config [ AbstractFileConfiguration::SERVICE_CLASS => MySQL::class, AbstractFileConfiguration::SERVICE_INIT_ARGUMENTS => [ 'host' => 'localhost', 'dbname' => '%dataBaseName%' ] ] This configuration is valid and the %dataBaseName% parameter placeholder gets replaced by the parameter entry on service instance initialisation. @param string $paramName @param null $paramValue
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L315-L322
tasoftch/php-service-manager
src/ServiceManager.php
ServiceManager.getParameter
public function getParameter(string $name, bool &$contained = NULL) { if(isset($this->parameters[$name])) { $contained = true; return $this->parameters[$name]; } $contained = false; return NULL; }
php
public function getParameter(string $name, bool &$contained = NULL) { if(isset($this->parameters[$name])) { $contained = true; return $this->parameters[$name]; } $contained = false; return NULL; }
Returns the requested parameter value. If not set, the $contained argument is set to false, otherwise true @param string $name @param bool $contained @return mixed|null
https://github.com/tasoftch/php-service-manager/blob/5f627d81457356f6c087398cd1e8f8e4f9d14822/src/ServiceManager.php#L331-L338