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
|
---|---|---|---|---|---|---|---|
schpill/thin | src/Queuespl.php | Queuespl.remove | public function remove($datum)
{
$found = false;
foreach ($this->items as $key => $item) {
if ($item['data'] === $datum) {
$found = true;
break;
}
}
if ($found) {
unset($this->items[$key]);
$this->queue = null;
if (!$this->isEmpty()) {
$queue = $this->getQueue();
foreach ($this->items as $item) {
$queue->insert($item['data'], $item['priority']);
}
}
return true;
}
return false;
} | php | public function remove($datum)
{
$found = false;
foreach ($this->items as $key => $item) {
if ($item['data'] === $datum) {
$found = true;
break;
}
}
if ($found) {
unset($this->items[$key]);
$this->queue = null;
if (!$this->isEmpty()) {
$queue = $this->getQueue();
foreach ($this->items as $item) {
$queue->insert($item['data'], $item['priority']);
}
}
return true;
}
return false;
} | Remove an item from the queue
This is different than {@link extract()}; its purpose is to dequeue an
item.
This operation is potentially expensive, as it requires
re-initialization and re-population of the inner queue.
Note: this removes the first item matching the provided item found. If
the same item has been added multiple times, it will not remove other
instances.
@param mixed $datum
@return bool False if the item was not found, true otherwise. | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Queuespl.php#L84-L109 |
schpill/thin | src/Queuespl.php | Queuespl.contains | public function contains($datum)
{
foreach ($this->items as $item) {
if ($item['data'] === $datum) {
return true;
}
}
return false;
} | php | public function contains($datum)
{
foreach ($this->items as $item) {
if ($item['data'] === $datum) {
return true;
}
}
return false;
} | Does the queue contain the given datum?
@param mixed $datum
@return bool | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Queuespl.php#L249-L258 |
schpill/thin | src/Queuespl.php | Queuespl.getQueue | protected function getQueue()
{
if (null === $this->queue) {
$this->queue = new $this->queueClass();
if (!$this->queue instanceof SplPriorityQueue) {
throw new Exception(sprintf(
'Queue expects an internal queue of type SplPriorityQueue; received "%s"',
get_class($this->queue)
));
}
}
return $this->queue;
} | php | protected function getQueue()
{
if (null === $this->queue) {
$this->queue = new $this->queueClass();
if (!$this->queue instanceof SplPriorityQueue) {
throw new Exception(sprintf(
'Queue expects an internal queue of type SplPriorityQueue; received "%s"',
get_class($this->queue)
));
}
}
return $this->queue;
} | Get the inner priority queue instance
@throws Exception\DomainException
@return SplQueue | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Queuespl.php#L283-L297 |
oliwierptak/Everon1 | src/Everon/RequestValidator.php | RequestValidator.validate | public function validate(Config\Interfaces\ItemRouter $RouteItem, Interfaces\Request $Request)
{
$method = $RouteItem->getMethod();
if ($method !== null && strcasecmp($method, $Request->getMethod()) !== 0) {
throw new Exception\RequestValidator('Invalid request method: "%s", expected: "%s" for url: "%s"', [$Request->getMethod(), $method, $RouteItem->getName()]);
}
$this->errors = null;
$parsed_query_parameters = $this->validateQuery($RouteItem, $Request->getPath(), $Request->getQueryCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getQueryRegex(),
$parsed_query_parameters,
true //so 404 can be thrown
);
$parsed_get_parameters = $this->validateGet($RouteItem, $Request->getGetCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getGetRegex(),
$parsed_get_parameters,
false
);
$parsed_post_parameters = $this->validatePost($RouteItem, $Request->getPostCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getPostRegex(),
$parsed_post_parameters,
false
);
return [$parsed_query_parameters, $parsed_get_parameters, $parsed_post_parameters];
} | php | public function validate(Config\Interfaces\ItemRouter $RouteItem, Interfaces\Request $Request)
{
$method = $RouteItem->getMethod();
if ($method !== null && strcasecmp($method, $Request->getMethod()) !== 0) {
throw new Exception\RequestValidator('Invalid request method: "%s", expected: "%s" for url: "%s"', [$Request->getMethod(), $method, $RouteItem->getName()]);
}
$this->errors = null;
$parsed_query_parameters = $this->validateQuery($RouteItem, $Request->getPath(), $Request->getQueryCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getQueryRegex(),
$parsed_query_parameters,
true //so 404 can be thrown
);
$parsed_get_parameters = $this->validateGet($RouteItem, $Request->getGetCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getGetRegex(),
$parsed_get_parameters,
false
);
$parsed_post_parameters = $this->validatePost($RouteItem, $Request->getPostCollection()->toArray());
$this->validateRoute(
$RouteItem->getName(),
(array) $RouteItem->getPostRegex(),
$parsed_post_parameters,
false
);
return [$parsed_query_parameters, $parsed_get_parameters, $parsed_post_parameters];
} | Validates $_GET, $_POST and $QUERY_STRING.
Returns array of validated query, get and post, or throws an exception
@param Config\Interfaces\ItemRouter $RouteItem
@param Interfaces\Request $Request
@return array
@throws Exception\RequestValidator | https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/RequestValidator.php#L29-L63 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Bundle/Form/Type/Component/MenuType.php | MenuType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add($builder
->create('tree', HiddenType::class, array(
'attr' => array(
'class' => 'synapse-tree-menu',
'data-labels' => json_encode(array(
'link' => array(
'name' => 'Name',
'url' => 'Url',
),
)),
),
))
->addModelTransformer($this)
)
;
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add($builder
->create('tree', HiddenType::class, array(
'attr' => array(
'class' => 'synapse-tree-menu',
'data-labels' => json_encode(array(
'link' => array(
'name' => 'Name',
'url' => 'Url',
),
)),
),
))
->addModelTransformer($this)
)
;
} | Menu component form prototype definition.
@see FormInterface::buildForm() | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Bundle/Form/Type/Component/MenuType.php#L55-L73 |
iron-bound-designs/wp-notifications | src/Strategy/iThemes_Exchange.php | iThemes_Exchange.send | public function send( \WP_User $recipient, $message, $subject, array $template_parts ) {
$message = str_replace( array_keys( $template_parts ), array_values( $template_parts ), $message );
$subject = str_replace( array_keys( $template_parts ), array_values( $template_parts ), $subject );
do_action( 'it_exchange_send_email_notification', $recipient->ID, $subject, $message );
return true;
} | php | public function send( \WP_User $recipient, $message, $subject, array $template_parts ) {
$message = str_replace( array_keys( $template_parts ), array_values( $template_parts ), $message );
$subject = str_replace( array_keys( $template_parts ), array_values( $template_parts ), $subject );
do_action( 'it_exchange_send_email_notification', $recipient->ID, $subject, $message );
return true;
} | Send the notification.
@since 1.0
@param \WP_User $recipient
@param string $message May contain HTML. Template parts aren't replaced.
@param string $subject
@param array $template_parts Array of template parts to their values.
@return bool
@throws \Exception | https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Strategy/iThemes_Exchange.php#L34-L41 |
alaa-almaliki/property-setter-config | src/PropertySetterConfig.php | PropertySetterConfig.setObjectProperties | static public function setObjectProperties($object, array $config = [])
{
foreach (static::createSetterMethods($config) as $method => $value) {
if (method_exists($object, $method)) {
call_user_func_array([$object, $method], [$value]);
}
}
} | php | static public function setObjectProperties($object, array $config = [])
{
foreach (static::createSetterMethods($config) as $method => $value) {
if (method_exists($object, $method)) {
call_user_func_array([$object, $method], [$value]);
}
}
} | Sets object properties by a given array
@param $object
@param array $config | https://github.com/alaa-almaliki/property-setter-config/blob/0dd77d0a206d927990b708e0e935284d8a5d4116/src/PropertySetterConfig.php#L16-L23 |
allprogrammic/redis-client | src/Client.php | Client.setReadTimeout | public function setReadTimeout($timeout)
{
if ($timeout < -1) {
throw new Exception('Timeout values less than -1 are not accepted.');
}
$this->readTimeout = $timeout;
if ($this->connected) {
if ($this->standalone) {
$timeout = $timeout <= 0 ? 315360000 : $timeout; // Ten-year timeout
stream_set_blocking($this->redis, true);
stream_set_timeout($this->redis, (int) floor($timeout), ($timeout - floor($timeout)) * 1000000);
} elseif (defined('Redis::OPT_READ_TIMEOUT')) {
// supported in phpredis 2.2.3
// a timeout value of -1 means reads will not timeout
$timeout = $timeout == 0 ? -1 : $timeout;
$this->redis->setOption(Redis::OPT_READ_TIMEOUT, $timeout);
}
}
return $this;
} | php | public function setReadTimeout($timeout)
{
if ($timeout < -1) {
throw new Exception('Timeout values less than -1 are not accepted.');
}
$this->readTimeout = $timeout;
if ($this->connected) {
if ($this->standalone) {
$timeout = $timeout <= 0 ? 315360000 : $timeout; // Ten-year timeout
stream_set_blocking($this->redis, true);
stream_set_timeout($this->redis, (int) floor($timeout), ($timeout - floor($timeout)) * 1000000);
} elseif (defined('Redis::OPT_READ_TIMEOUT')) {
// supported in phpredis 2.2.3
// a timeout value of -1 means reads will not timeout
$timeout = $timeout == 0 ? -1 : $timeout;
$this->redis->setOption(Redis::OPT_READ_TIMEOUT, $timeout);
}
}
return $this;
} | Set the read timeout for the connection. Use 0 to disable timeouts entirely (or use a very long timeout
if not supported).
@param int $timeout 0 (or -1) for no timeout, otherwise number of seconds
@throws Exception
@return Client | https://github.com/allprogrammic/redis-client/blob/5bbd5ca4cef79cb5d61bb0854d5860a03c38a85d/src/Client.php#L482-L501 |
allprogrammic/redis-client | src/Client.php | Client.renameCommand | public function renameCommand($command, $alias = null)
{
if (! $this->standalone) {
$this->forceStandalone();
}
if ($alias === null) {
$this->renamedCommands = $command;
} else {
if (! $this->renamedCommands) {
$this->renamedCommands = [];
}
$this->renamedCommands[$command] = $alias;
}
return $this;
} | php | public function renameCommand($command, $alias = null)
{
if (! $this->standalone) {
$this->forceStandalone();
}
if ($alias === null) {
$this->renamedCommands = $command;
} else {
if (! $this->renamedCommands) {
$this->renamedCommands = [];
}
$this->renamedCommands[$command] = $alias;
}
return $this;
} | Enabled command renaming and provide mapping method. Supported methods are:
1. renameCommand('foo') // Salted md5 hash for all commands -> md5('foo'.$command)
2. renameCommand(function($command){ return 'my'.$command; }); // Callable
3. renameCommand('get', 'foo') // Single command -> alias
4. renameCommand(['get' => 'foo', 'set' => 'bar']) // Full map of [command -> alias]
@param string|callable|array $command
@param string|null $alias
@return $this | https://github.com/allprogrammic/redis-client/blob/5bbd5ca4cef79cb5d61bb0854d5860a03c38a85d/src/Client.php#L532-L546 |
allprogrammic/redis-client | src/Client.php | Client.prepareCommand | private static function prepareCommand($args)
{
return sprintf('*%d%s%s%s', count($args), self::CRLF, implode(array_map(array('self', 'map'), $args), self::CRLF), self::CRLF);
} | php | private static function prepareCommand($args)
{
return sprintf('*%d%s%s%s', count($args), self::CRLF, implode(array_map(array('self', 'map'), $args), self::CRLF), self::CRLF);
} | Build the Redis unified protocol command
@param array $args
@return string | https://github.com/allprogrammic/redis-client/blob/5bbd5ca4cef79cb5d61bb0854d5860a03c38a85d/src/Client.php#L1267-L1270 |
allprogrammic/redis-client | src/Client.php | Client.flattenArguments | private static function flattenArguments(array $arguments, &$out = [])
{
foreach ($arguments as $key => $arg) {
if (!is_int($key)) {
$out[] = $key;
}
if (is_array($arg)) {
self::flattenArguments($arg, $out);
} else {
$out[] = $arg;
}
}
return $out;
} | php | private static function flattenArguments(array $arguments, &$out = [])
{
foreach ($arguments as $key => $arg) {
if (!is_int($key)) {
$out[] = $key;
}
if (is_array($arg)) {
self::flattenArguments($arg, $out);
} else {
$out[] = $arg;
}
}
return $out;
} | Flatten arguments
If an argument is an array, the key is inserted as argument followed by the array values
array('zrangebyscore', '-inf', 123, array('limit' => array('0', '1')))
becomes
array('zrangebyscore', '-inf', 123, 'limit', '0', '1')
@param array $arguments
@param array $out
@return array | https://github.com/allprogrammic/redis-client/blob/5bbd5ca4cef79cb5d61bb0854d5860a03c38a85d/src/Client.php#L1290-L1305 |
wigedev/farm | src/Validator/Validator/Date.php | Date.checkValidity | protected function checkValidity($value) : bool
{
if ('' === $value) {
return true;
}
$date = date_create($value);
if (false === $date) {
return false;
}
return true;
} | php | protected function checkValidity($value) : bool
{
if ('' === $value) {
return true;
}
$date = date_create($value);
if (false === $date) {
return false;
}
return true;
} | This is the function that does the actual checking. This should allow either matches to the regex or empty
values.
@param $value
@return bool | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/Validator/Validator/Date.php#L25-L35 |
IftekherSunny/Planet-Framework | src/Sun/Validation/Form/Request.php | Request.validate | public function validate()
{
foreach($this->rules() as $key => $value) {
$this->rules[$key] = [$this->input($key), $value];
}
$validate = $this->validator->validate($this->rules);
if ($validate->fails()) {
if($this->isAjax()) {
return $this->response->json(['errors' => $validate->errors()->all()], 403);
}
return $this->redirect->backWith('errors', $validate->errors()->all());
}
} | php | public function validate()
{
foreach($this->rules() as $key => $value) {
$this->rules[$key] = [$this->input($key), $value];
}
$validate = $this->validator->validate($this->rules);
if ($validate->fails()) {
if($this->isAjax()) {
return $this->response->json(['errors' => $validate->errors()->all()], 403);
}
return $this->redirect->backWith('errors', $validate->errors()->all());
}
} | Validate requested form.
@return string | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Validation/Form/Request.php#L56-L71 |
kiwi-suite/core42 | src/Navigation/Filter/AbstractFilter.php | AbstractFilter.accept | public function accept()
{
$accepted = (bool) $this->isAccepted();
if ($accepted === false && $this->current() instanceof PageInterface) {
$parent = $this->current()->getParent();
if (!empty($parent)) {
$parent->removePage($this->current());
}
}
return $accepted;
} | php | public function accept()
{
$accepted = (bool) $this->isAccepted();
if ($accepted === false && $this->current() instanceof PageInterface) {
$parent = $this->current()->getParent();
if (!empty($parent)) {
$parent->removePage($this->current());
}
}
return $accepted;
} | Check whether the current element of the iterator is acceptable
@see http://php.net/manual/en/filteriterator.accept.php
@return bool true if the current element is acceptable, otherwise false
@since 5.1.0 | https://github.com/kiwi-suite/core42/blob/b1b6c4a0e32b7024fb8c281a7f42590acaeefb45/src/Navigation/Filter/AbstractFilter.php#L25-L36 |
Phpillip/phpillip | src/Provider/InformatorServiceProvider.php | InformatorServiceProvider.register | public function register(Application $app)
{
$app['informator'] = $app->share(function ($app) {
return new $app['informator_class']($app['url_generator']);
});
$app->before([$app['informator'], 'beforeRequest']);
} | php | public function register(Application $app)
{
$app['informator'] = $app->share(function ($app) {
return new $app['informator_class']($app['url_generator']);
});
$app->before([$app['informator'], 'beforeRequest']);
} | {@inheritdoc} | https://github.com/Phpillip/phpillip/blob/c37afaafb536361e7e0b564659f1cd5b80b98be9/src/Provider/InformatorServiceProvider.php#L17-L24 |
Boolive/Core | template/Template.php | Template.getEngine | static function getEngine($template)
{
foreach (self::$engines as $pattern => $engine){
if (fnmatch($pattern, $template)){
if (is_string($engine)){
self::$engines[$pattern] = new $engine();
}
return self::$engines[$pattern];
}
}
return null;
} | php | static function getEngine($template)
{
foreach (self::$engines as $pattern => $engine){
if (fnmatch($pattern, $template)){
if (is_string($engine)){
self::$engines[$pattern] = new $engine();
}
return self::$engines[$pattern];
}
}
return null;
} | Возвращает шаблонизатор для указанного файла шаблона
@param string $template
@return | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/template/Template.php#L32-L43 |
Boolive/Core | template/Template.php | Template.render | static function render($template, $v = [])
{
if ($engine = self::getEngine($template)){
return $engine->render($template, $v);
}else{
throw new Error(array('Template engine for template "%s" not found ', $template));
}
} | php | static function render($template, $v = [])
{
if ($engine = self::getEngine($template)){
return $engine->render($template, $v);
}else{
throw new Error(array('Template engine for template "%s" not found ', $template));
}
} | Создание текста из шаблона
В шаблон вставляются переданные значения
@param string $template
@param array $v
@throws Error
@return string | https://github.com/Boolive/Core/blob/ead9668f1a6adf41656131eb608a99db6855138d/template/Template.php#L53-L60 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.procesarParametros | public static function procesarParametros(
$cadena,
$formato = 'application/x-www-form-urlencoded',
$porDefecto = []
) {
$resultado = $porDefecto;
if ('application/x-www-form-urlencoded' == $formato) {
$resultado = [];
// Excluimos contenido que no sea usable
if (strpos($cadena, '?') !== false) {
$cadena = parse_url($cadena, PHP_URL_QUERY);
}
// Separamos los parametros
$pares = explode('&', $cadena);
foreach ($pares as $par) {
$temp = explode('=', $par, 2);
$nombre = urldecode($temp[0]);
$temp2 = strpos($nombre, '[]');
if ($temp2 !== false) {
$nombre = substr($nombre, 0, $temp2);
}
$valor = (isset($temp[1])) ? urldecode($temp[1]) : '';
// Si el nombre ya existe pegamos el valor como matriz
if (isset($resultado[$nombre])) {
# Pegamos varios valores en una matriz
if (is_array($resultado[$nombre])) {
$resultado[$nombre][] = $valor;
} else {
$resultado[$nombre] = [$resultado[$nombre], $valor];
}
// de lo contrario, sólo pegamos el valor simple
} else {
$resultado[$nombre] = $valor;
}
}
}
if ('application/json' == $formato) {
$resultado = json_decode($cadena, true);
}
return $resultado;
} | php | public static function procesarParametros(
$cadena,
$formato = 'application/x-www-form-urlencoded',
$porDefecto = []
) {
$resultado = $porDefecto;
if ('application/x-www-form-urlencoded' == $formato) {
$resultado = [];
// Excluimos contenido que no sea usable
if (strpos($cadena, '?') !== false) {
$cadena = parse_url($cadena, PHP_URL_QUERY);
}
// Separamos los parametros
$pares = explode('&', $cadena);
foreach ($pares as $par) {
$temp = explode('=', $par, 2);
$nombre = urldecode($temp[0]);
$temp2 = strpos($nombre, '[]');
if ($temp2 !== false) {
$nombre = substr($nombre, 0, $temp2);
}
$valor = (isset($temp[1])) ? urldecode($temp[1]) : '';
// Si el nombre ya existe pegamos el valor como matriz
if (isset($resultado[$nombre])) {
# Pegamos varios valores en una matriz
if (is_array($resultado[$nombre])) {
$resultado[$nombre][] = $valor;
} else {
$resultado[$nombre] = [$resultado[$nombre], $valor];
}
// de lo contrario, sólo pegamos el valor simple
} else {
$resultado[$nombre] = $valor;
}
}
}
if ('application/json' == $formato) {
$resultado = json_decode($cadena, true);
}
return $resultado;
} | Procesa y devuelve los parámetros de la cadena según el formato.
@param string $cadena
@param string $formato
@param array $porDefecto
@return array | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L34-L82 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.prepararArchivos | public static function prepararArchivos(array $archivos, $inicio = true)
{
$final = [];
foreach ($archivos as $nombre => $archivo) {
// Definimos sub nombre
$subNombre = $nombre;
if ($inicio) {
$subNombre = $archivo['name'];
}
$final[$nombre] = $archivo;
if (is_array($subNombre)) {
foreach (array_keys($subNombre) as $llave) {
$final[$nombre][$llave] = array(
'name' => $archivo['name'][$llave],
'type' => $archivo['type'][$llave],
'tmp_name' => $archivo['tmp_name'][$llave],
'error' => $archivo['error'][$llave],
'size' => $archivo['size'][$llave],
);
$final[$nombre] = self::prepararArchivos($final[$nombre], false);
}
}
}
return $final;
} | php | public static function prepararArchivos(array $archivos, $inicio = true)
{
$final = [];
foreach ($archivos as $nombre => $archivo) {
// Definimos sub nombre
$subNombre = $nombre;
if ($inicio) {
$subNombre = $archivo['name'];
}
$final[$nombre] = $archivo;
if (is_array($subNombre)) {
foreach (array_keys($subNombre) as $llave) {
$final[$nombre][$llave] = array(
'name' => $archivo['name'][$llave],
'type' => $archivo['type'][$llave],
'tmp_name' => $archivo['tmp_name'][$llave],
'error' => $archivo['error'][$llave],
'size' => $archivo['size'][$llave],
);
$final[$nombre] = self::prepararArchivos($final[$nombre], false);
}
}
}
return $final;
} | Prepara el formato en que se presenta los archivos subidos.
@link http://php.net/manual/es/reserved.variables.files.php#106608
@param array $archivos
@param bool $inicio
@return array | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L94-L120 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.crearDesdeGlobales | public static function crearDesdeGlobales()
{
// Preparamos Metodo
if (isset($_SERVER['REQUEST_METHOD'])) {
$metodo = $_SERVER['REQUEST_METHOD'];
} else {
$metodo = 'GET';
}
// Preparamos URL
$url = '';
if (!empty($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] !== 'off') {
$url .= 'https';
} else {
$url .= 'http';
}
} else {
if ($_SERVER['SERVER_PORT'] == 443) {
$url .= 'https';
} else {
$url .= 'http';
}
}
$url .= '://';
if (isset($_SERVER['HTTP_HOST'])) {
$url .= $_SERVER['HTTP_HOST'];
} else {
$url .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
}
$url .= $_SERVER['REQUEST_URI'];
// Preparamos cabeceras
$cabeceras = [];
foreach ($_SERVER as $nombre => $valor) {
if (substr($nombre, 0, 5) == 'HTTP_') {
$nombre = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($nombre, 5)))));
$cabeceras[$nombre] = $valor;
} else if ($nombre == 'CONTENT_MD5') {
$cabeceras['Content-Md5'] = $valor;
} else if ($nombre == 'CONTENT_TYPE') {
$cabeceras['Content-Type'] = $valor;
} else if ($nombre == 'CONTENT_LENGTH') {
$cabeceras['Content-Length'] = $valor;
}
}
if (!isset($cabeceras['Authorization'])) {
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
$cabeceras['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
} elseif (isset($_SERVER['PHP_AUTH_USER'])) {
$temp = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$cabeceras['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $temp);
} elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
$cabeceras['Authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
}
}
// Preparamos parámetros según método
$parametros = [];
if ($metodo != 'GET') {
$parametros = self::procesarParametros(file_get_contents('php://input'), $cabeceras['Content-Type'], $_POST);
}
// Preparamos galletas
$galletas = [];
if (!empty($_COOKIE)) {
$galletas = $_COOKIE;
}
// Preparamos archivos
$archivos = [];
if (!empty($_FILES)) {
$archivos = self::prepararArchivos($_FILES);
}
// Iniciamos instancia de petición con los datos ya preparados
$peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);
// Preparamos IP del cliente
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$peticion->cliente_ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
$peticion->cliente_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$peticion->cliente_ip = $_SERVER['REMOTE_ADDR'];
}
// Retornamos instancia iniciada
return $peticion;
} | php | public static function crearDesdeGlobales()
{
// Preparamos Metodo
if (isset($_SERVER['REQUEST_METHOD'])) {
$metodo = $_SERVER['REQUEST_METHOD'];
} else {
$metodo = 'GET';
}
// Preparamos URL
$url = '';
if (!empty($_SERVER['HTTPS'])) {
if ($_SERVER['HTTPS'] !== 'off') {
$url .= 'https';
} else {
$url .= 'http';
}
} else {
if ($_SERVER['SERVER_PORT'] == 443) {
$url .= 'https';
} else {
$url .= 'http';
}
}
$url .= '://';
if (isset($_SERVER['HTTP_HOST'])) {
$url .= $_SERVER['HTTP_HOST'];
} else {
$url .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
}
$url .= $_SERVER['REQUEST_URI'];
// Preparamos cabeceras
$cabeceras = [];
foreach ($_SERVER as $nombre => $valor) {
if (substr($nombre, 0, 5) == 'HTTP_') {
$nombre = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($nombre, 5)))));
$cabeceras[$nombre] = $valor;
} else if ($nombre == 'CONTENT_MD5') {
$cabeceras['Content-Md5'] = $valor;
} else if ($nombre == 'CONTENT_TYPE') {
$cabeceras['Content-Type'] = $valor;
} else if ($nombre == 'CONTENT_LENGTH') {
$cabeceras['Content-Length'] = $valor;
}
}
if (!isset($cabeceras['Authorization'])) {
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
$cabeceras['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
} elseif (isset($_SERVER['PHP_AUTH_USER'])) {
$temp = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$cabeceras['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $temp);
} elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) {
$cabeceras['Authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
}
}
// Preparamos parámetros según método
$parametros = [];
if ($metodo != 'GET') {
$parametros = self::procesarParametros(file_get_contents('php://input'), $cabeceras['Content-Type'], $_POST);
}
// Preparamos galletas
$galletas = [];
if (!empty($_COOKIE)) {
$galletas = $_COOKIE;
}
// Preparamos archivos
$archivos = [];
if (!empty($_FILES)) {
$archivos = self::prepararArchivos($_FILES);
}
// Iniciamos instancia de petición con los datos ya preparados
$peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);
// Preparamos IP del cliente
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$peticion->cliente_ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
$peticion->cliente_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$peticion->cliente_ip = $_SERVER['REMOTE_ADDR'];
}
// Retornamos instancia iniciada
return $peticion;
} | Crea una instancia de petición usando como base las variables globales de PHP.
@return self | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L127-L218 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.crearDesdeSwoole | public static function crearDesdeSwoole(\swoole_http_request $req)
{
// Preparamos Metodo
$metodo = $req->server['request_method'];
// Preparamos URL
$url = 'http';
if (!empty($req->server['https']) && $req->server['https'] !== 'off') {
$url .= 's';
} elseif ($req->server['server_port'] == 443) {
$url .= 's';
}
$url .= '://' . $req->header['host'];
$url .= $req->server['request_uri'];
if (isset($req->server['query_string'])) {
$url .= '?' . $req->server['query_string'];
}
// Preparamos parámetros según método
$parametros = [];
if (!empty($req->post)) {
$parametros = $req->post;
}
if ($metodo != 'GET' && isset($req->header['content-type'])) {
$parametros = self::procesarParametros($req->rawContent(), $req->header['content-type'], $parametros);
}
// Preparamos cabeceras
$cabeceras = [];
foreach($req->header as $nombre => $valor) {
$nombre = str_replace(' ', '-', ucwords(str_replace('-', ' ', $nombre)));
if (isset($cabeceras[$nombre])) {
if (is_array($cabeceras[$nombre])) {
$cabeceras[$nombre][] = $valor;
} else {
$cabeceras[$nombre] = [$cabeceras[$nombre], $valor];
}
} else {
$cabeceras[$nombre] = $valor;
}
}
// Preparamos galletas
$galletas = [];
if (!empty($req->cookie)) {
$galletas = $req->cookie;
}
// Preparamos arhivos
$archivos = [];
if (!empty($req->files)) {
$archivos = $req->files;
}
// Iniciamos instancia de petición con los datos ya preparados
$peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);
// Preparamos IP del cliente
$peticion->cliente_ip = $req->server['remote_addr'];
if (isset($req->server['x-client-ip'])) {
$peticion->cliente_ip = $req->server['x-client-ip'];
} elseif (isset($req->server['x-real-ip'])) {
$peticion->cliente_ip = $req->server['x-real-ip'];
} elseif (isset($_SERVER['x-forwarded-for'])) {
$peticion->cliente_ip = trim(explode(',', $_SERVER['x-forwarded-for'])[0]);
}
// Retornamos instancia iniciada
return $peticion;
} | php | public static function crearDesdeSwoole(\swoole_http_request $req)
{
// Preparamos Metodo
$metodo = $req->server['request_method'];
// Preparamos URL
$url = 'http';
if (!empty($req->server['https']) && $req->server['https'] !== 'off') {
$url .= 's';
} elseif ($req->server['server_port'] == 443) {
$url .= 's';
}
$url .= '://' . $req->header['host'];
$url .= $req->server['request_uri'];
if (isset($req->server['query_string'])) {
$url .= '?' . $req->server['query_string'];
}
// Preparamos parámetros según método
$parametros = [];
if (!empty($req->post)) {
$parametros = $req->post;
}
if ($metodo != 'GET' && isset($req->header['content-type'])) {
$parametros = self::procesarParametros($req->rawContent(), $req->header['content-type'], $parametros);
}
// Preparamos cabeceras
$cabeceras = [];
foreach($req->header as $nombre => $valor) {
$nombre = str_replace(' ', '-', ucwords(str_replace('-', ' ', $nombre)));
if (isset($cabeceras[$nombre])) {
if (is_array($cabeceras[$nombre])) {
$cabeceras[$nombre][] = $valor;
} else {
$cabeceras[$nombre] = [$cabeceras[$nombre], $valor];
}
} else {
$cabeceras[$nombre] = $valor;
}
}
// Preparamos galletas
$galletas = [];
if (!empty($req->cookie)) {
$galletas = $req->cookie;
}
// Preparamos arhivos
$archivos = [];
if (!empty($req->files)) {
$archivos = $req->files;
}
// Iniciamos instancia de petición con los datos ya preparados
$peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);
// Preparamos IP del cliente
$peticion->cliente_ip = $req->server['remote_addr'];
if (isset($req->server['x-client-ip'])) {
$peticion->cliente_ip = $req->server['x-client-ip'];
} elseif (isset($req->server['x-real-ip'])) {
$peticion->cliente_ip = $req->server['x-real-ip'];
} elseif (isset($_SERVER['x-forwarded-for'])) {
$peticion->cliente_ip = trim(explode(',', $_SERVER['x-forwarded-for'])[0]);
}
// Retornamos instancia iniciada
return $peticion;
} | Crea una isntancia de petición usando como base la petición de Swoole.
@param \swoole_http_request $req
@return self | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L227-L298 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.obtenerCabecera | public function obtenerCabecera($nombre, $porDefecto = null)
{
return isset($this->cabeceras[$nombre]) ? $this->cabeceras[$nombre] : $porDefecto;
} | php | public function obtenerCabecera($nombre, $porDefecto = null)
{
return isset($this->cabeceras[$nombre]) ? $this->cabeceras[$nombre] : $porDefecto;
} | Obtiene cabecera solicitada dentro de la petición, en caso de exitir.
@param string $nombre
@param mixed $porDefecto
@return mixed | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L394-L397 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.filtrarVar | public function filtrarVar($valor, $filtro)
{
if ($filtro == 'email') {
$dotString = '(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/-]|(?<!\\.|\\A)\\.(?!\\.|@))';
$quotedString = '(?:\\\\\\\\|\\\\"|\\\\?[A-Za-z0-9!#$%&*+=?^_`{|}~()<>[\\]:;@,. \'\\/-])';
$ipv4Part = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
$ipv6Part = '(?:[A-fa-f0-9]{1,4})';
$fqdnPart = '(?:[A-Za-z](?:[A-Za-z0-9-]{0,61}?[A-Za-z0-9])?)';
$ipv4 = "(?:(?:{$ipv4Part}\\.){3}{$ipv4Part})";
$ipv6 = '(?:' .
"(?:(?:{$ipv6Part}:){7}(?:{$ipv6Part}|:))" . '|' .
"(?:(?:{$ipv6Part}:){6}(?::{$ipv6Part}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){5}(?:(?::{$ipv6Part}){1,2}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){4}(?:(?::{$ipv6Part}){1,3}|(?::{$ipv6Part})?:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){3}(?:(?::{$ipv6Part}){1,4}|(?::{$ipv6Part}){0,2}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){2}(?:(?::{$ipv6Part}){1,5}|(?::{$ipv6Part}){0,3}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){1}(?:(?::{$ipv6Part}){1,6}|(?::{$ipv6Part}){0,4}:{$ipv4}|:))" . '|' .
"(?::(?:(?::{$ipv6Part}){1,7}|(?::{$ipv6Part}){0,5}:{$ipv4}|:))" .
')';
$fqdn = "(?:(?:{$fqdnPart}\\.)+?{$fqdnPart})";
$local = "({$dotString}++|(\"){$quotedString}++\")";
$domain = "({$fqdn}|\\[{$ipv4}]|\\[{$ipv6}]|\\[{$fqdn}])";
$pattern = "/\\A{$local}@{$domain}\\z/";
return preg_match($pattern, $valor, $matches) &&
(
!empty($matches[2]) && !isset($matches[1][66]) && !isset($matches[0][256]) ||
!isset($matches[1][64]) && !isset($matches[0][254])
);
}
if ($filtro == 'entero') {
return filter_var($valor, FILTER_VALIDATE_INT);
}
if ($filtro == 'flotante') {
return filter_var($valor, FILTER_VALIDATE_FLOAT);
}
if ($filtro == 'ip') {
return filter_var($valor, FILTER_VALIDATE_IP);
}
if ($filtro == 'url') {
return filter_var($valor, FILTER_VALIDATE_URL);
}
if ($filtro == 'booleano') {
return filter_var($valor, FILTER_VALIDATE_BOOLEAN);
}
if ($filtro == 'texto_limpio') {
return trim(filter_var($valor, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW));
}
return $valor;
} | php | public function filtrarVar($valor, $filtro)
{
if ($filtro == 'email') {
$dotString = '(?:[A-Za-z0-9!#$%&*+=?^_`{|}~\'\\/-]|(?<!\\.|\\A)\\.(?!\\.|@))';
$quotedString = '(?:\\\\\\\\|\\\\"|\\\\?[A-Za-z0-9!#$%&*+=?^_`{|}~()<>[\\]:;@,. \'\\/-])';
$ipv4Part = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
$ipv6Part = '(?:[A-fa-f0-9]{1,4})';
$fqdnPart = '(?:[A-Za-z](?:[A-Za-z0-9-]{0,61}?[A-Za-z0-9])?)';
$ipv4 = "(?:(?:{$ipv4Part}\\.){3}{$ipv4Part})";
$ipv6 = '(?:' .
"(?:(?:{$ipv6Part}:){7}(?:{$ipv6Part}|:))" . '|' .
"(?:(?:{$ipv6Part}:){6}(?::{$ipv6Part}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){5}(?:(?::{$ipv6Part}){1,2}|:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){4}(?:(?::{$ipv6Part}){1,3}|(?::{$ipv6Part})?:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){3}(?:(?::{$ipv6Part}){1,4}|(?::{$ipv6Part}){0,2}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){2}(?:(?::{$ipv6Part}){1,5}|(?::{$ipv6Part}){0,3}:{$ipv4}|:))" . '|' .
"(?:(?:{$ipv6Part}:){1}(?:(?::{$ipv6Part}){1,6}|(?::{$ipv6Part}){0,4}:{$ipv4}|:))" . '|' .
"(?::(?:(?::{$ipv6Part}){1,7}|(?::{$ipv6Part}){0,5}:{$ipv4}|:))" .
')';
$fqdn = "(?:(?:{$fqdnPart}\\.)+?{$fqdnPart})";
$local = "({$dotString}++|(\"){$quotedString}++\")";
$domain = "({$fqdn}|\\[{$ipv4}]|\\[{$ipv6}]|\\[{$fqdn}])";
$pattern = "/\\A{$local}@{$domain}\\z/";
return preg_match($pattern, $valor, $matches) &&
(
!empty($matches[2]) && !isset($matches[1][66]) && !isset($matches[0][256]) ||
!isset($matches[1][64]) && !isset($matches[0][254])
);
}
if ($filtro == 'entero') {
return filter_var($valor, FILTER_VALIDATE_INT);
}
if ($filtro == 'flotante') {
return filter_var($valor, FILTER_VALIDATE_FLOAT);
}
if ($filtro == 'ip') {
return filter_var($valor, FILTER_VALIDATE_IP);
}
if ($filtro == 'url') {
return filter_var($valor, FILTER_VALIDATE_URL);
}
if ($filtro == 'booleano') {
return filter_var($valor, FILTER_VALIDATE_BOOLEAN);
}
if ($filtro == 'texto_limpio') {
return trim(filter_var($valor, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW));
}
return $valor;
} | Valida y sanea un valor según el filtro aplicado.
@param mixed $valor
@param string $filtro
@return mixed | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L445-L500 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.obtenerGet | public function obtenerGet($nombre, $porDefecto = null, $filtro = null)
{
if (isset($this->parametrosGet[$nombre])) {
if (isset($filtro) && !$this->filtrarVar($this->parametrosGet[$nombre], $filtro)) {
return false;
}
return $this->parametrosGet[$nombre];
}
return $porDefecto;
} | php | public function obtenerGet($nombre, $porDefecto = null, $filtro = null)
{
if (isset($this->parametrosGet[$nombre])) {
if (isset($filtro) && !$this->filtrarVar($this->parametrosGet[$nombre], $filtro)) {
return false;
}
return $this->parametrosGet[$nombre];
}
return $porDefecto;
} | Devuelve el valor del parámetro GET llamado.
Si el parámetro GET no existe, se devolverá el segundo parámetro de este método.
@param string $nombre Nombre del parámetro
@param mixed $porDefecto El valor del parámetro por defecto
@param string $filtro Aplica un filtro al valor obtenido
@see obtenerParam
@return bool|mixed El valor del parámetro o falso en caso de fallar el filtro | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L513-L524 |
armazon/armazon | src/Armazon/Http/Peticion.php | Peticion.obtenerParam | public function obtenerParam($nombre, $porDefecto = null, $filtro = null)
{
if (isset($this->parametros[$nombre])) {
if (isset($filtro) && !$this->filtrarVar($this->parametros[$nombre], $filtro)) {
return false;
}
return $this->parametros[$nombre];
}
return $porDefecto;
} | php | public function obtenerParam($nombre, $porDefecto = null, $filtro = null)
{
if (isset($this->parametros[$nombre])) {
if (isset($filtro) && !$this->filtrarVar($this->parametros[$nombre], $filtro)) {
return false;
}
return $this->parametros[$nombre];
}
return $porDefecto;
} | Devuelve el valor del parámetro llamado.
Si el parámetro POST no existe, se devolverá el segundo parámetro de este método.
@param string $nombre Nombre del parámetro
@param mixed $porDefecto El valor del parámetro por defecto
@param string $filtro Aplica un filtro al valor obtenido
@see obtenerGet
@return mixed El valor del parámetro o falso en caso de fallar el filtro | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Http/Peticion.php#L537-L548 |
phore/phore-system | src/PhoreProc.php | PhoreProc.watch | public function watch(int $channel, callable $callback = null) : self
{
$this->listener[$channel] = $callback;
return $this;
} | php | public function watch(int $channel, callable $callback = null) : self
{
$this->listener[$channel] = $callback;
return $this;
} | Register a callback on channel if output occures. After feof() this callback
will be called with null as data
<example>
phore_exec("ls -l")->watch(1, function($data, $len, PhoreProc $proc) {})->wait();
</example>
@param int $channel
@param callable|null $callback
@return PhoreProc | https://github.com/phore/phore-system/blob/564f41ea790d4fb564d65f1533a4aeb9f05dabf0/src/PhoreProc.php#L47-L51 |
phore/phore-system | src/PhoreProc.php | PhoreProc.exec | public function exec() : self
{
$descSpec = [
0 => ["pipe", "r"]
];
foreach ($this->listener as $chanId => $listener) {
$descSpec[$chanId] = ["pipe", "w"];
}
$this->proc = proc_open($this->cmd, $descSpec, $pipes);
if ($this->proc === false)
throw new \Exception("Unable to proc_open()");
//print_r (proc_get_status($this->proc));
foreach ($this->listener as $chanId => $listener) {
stream_set_blocking($pipes[$chanId], 0);
}
$this->pipes = $pipes;
return $this;
} | php | public function exec() : self
{
$descSpec = [
0 => ["pipe", "r"]
];
foreach ($this->listener as $chanId => $listener) {
$descSpec[$chanId] = ["pipe", "w"];
}
$this->proc = proc_open($this->cmd, $descSpec, $pipes);
if ($this->proc === false)
throw new \Exception("Unable to proc_open()");
//print_r (proc_get_status($this->proc));
foreach ($this->listener as $chanId => $listener) {
stream_set_blocking($pipes[$chanId], 0);
}
$this->pipes = $pipes;
return $this;
} | Execute the process.
This method will not wait unitl the process exists. So you have to call wait() afterwards!
@return PhoreProc
@throws \Exception | https://github.com/phore/phore-system/blob/564f41ea790d4fb564d65f1533a4aeb9f05dabf0/src/PhoreProc.php#L72-L93 |
phore/phore-system | src/PhoreProc.php | PhoreProc.wait | public function wait(bool $throwExceptionOnError=true) : PhoreProcResult
{
if ($this->proc === null)
$this->exec();
$buf = null;
if ($buf === null) {
$buf = [];
foreach ($this->listener as $chanId => $listener) {
$buf[$chanId] = "";
}
}
while(true) {
$allPipesClosed = true;
$noData = true;
foreach ($buf as $chanId => &$buffer) {
if ( ! feof($this->pipes[$chanId])) {
$allPipesClosed = false;
$dataRead = fread($this->pipes[$chanId], 1024 * 32);
$dataReadLen = strlen($dataRead);
if ($dataReadLen > 0) {
$noData = false;
if ($this->listener[$chanId] !== null) {
($this->listener[$chanId])($dataRead, $dataReadLen, $this);
} else {
$buffer .= $dataRead;
}
}
}
}
if ($allPipesClosed) {
break;
}
if ($noData) {
usleep(500);
}
}
foreach ($this->listener as $chanId => $listener) {
if ($listener === null)
continue;
$listener(null, null, $this);
fclose($this->pipes[$chanId]);
}
fclose($this->pipes[0]);
$exitStatus = proc_close($this->proc);
$errmsg = "";
if (isset ($buf[2]))
$errmsg = $buf[2];
if ($exitStatus !== 0) {
throw new PhoreExecException("Command '$this->cmd' returned with exit-code $exitStatus: $errmsg", $exitStatus);
}
return new PhoreProcResult($exitStatus, $buf);
} | php | public function wait(bool $throwExceptionOnError=true) : PhoreProcResult
{
if ($this->proc === null)
$this->exec();
$buf = null;
if ($buf === null) {
$buf = [];
foreach ($this->listener as $chanId => $listener) {
$buf[$chanId] = "";
}
}
while(true) {
$allPipesClosed = true;
$noData = true;
foreach ($buf as $chanId => &$buffer) {
if ( ! feof($this->pipes[$chanId])) {
$allPipesClosed = false;
$dataRead = fread($this->pipes[$chanId], 1024 * 32);
$dataReadLen = strlen($dataRead);
if ($dataReadLen > 0) {
$noData = false;
if ($this->listener[$chanId] !== null) {
($this->listener[$chanId])($dataRead, $dataReadLen, $this);
} else {
$buffer .= $dataRead;
}
}
}
}
if ($allPipesClosed) {
break;
}
if ($noData) {
usleep(500);
}
}
foreach ($this->listener as $chanId => $listener) {
if ($listener === null)
continue;
$listener(null, null, $this);
fclose($this->pipes[$chanId]);
}
fclose($this->pipes[0]);
$exitStatus = proc_close($this->proc);
$errmsg = "";
if (isset ($buf[2]))
$errmsg = $buf[2];
if ($exitStatus !== 0) {
throw new PhoreExecException("Command '$this->cmd' returned with exit-code $exitStatus: $errmsg", $exitStatus);
}
return new PhoreProcResult($exitStatus, $buf);
} | Wait for the process to exit.
This will call exec() if not done before.
@param bool $throwExceptionOnError
@return PhoreProcResult
@throws PhoreExecException | https://github.com/phore/phore-system/blob/564f41ea790d4fb564d65f1533a4aeb9f05dabf0/src/PhoreProc.php#L105-L162 |
old-town/workflow-zf2 | src/Options/ManagerOptions.php | ManagerOptions.getConfiguration | public function getConfiguration()
{
if (null === $this->configuration) {
$errMsg = 'no attribute \'configuration\'';
throw new Exception\InvalidConfigurationNameException($errMsg);
}
return $this->configuration;
} | php | public function getConfiguration()
{
if (null === $this->configuration) {
$errMsg = 'no attribute \'configuration\'';
throw new Exception\InvalidConfigurationNameException($errMsg);
}
return $this->configuration;
} | Возвращает имя конфигурации для данного менеджера workflow
@return string
@throws Exception\InvalidConfigurationNameException | https://github.com/old-town/workflow-zf2/blob/b63910bd0f4c05855e19cfa29e3376eee7c16c77/src/Options/ManagerOptions.php#L47-L54 |
IftekherSunny/Planet-Framework | src/Sun/Support/Alien.php | Alien.execute | protected static function execute()
{
try {
$instance = static::getInstance();
$reflectionMethod = new ReflectionMethod($instance, static::$method);
return $reflectionMethod->invokeArgs($instance, static::$arguments);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
} | php | protected static function execute()
{
try {
$instance = static::getInstance();
$reflectionMethod = new ReflectionMethod($instance, static::$method);
return $reflectionMethod->invokeArgs($instance, static::$arguments);
} catch (Exception $e) {
throw new Exception($e->getMessage());
}
} | Execute method of the registered alien
@return mixed
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Alien.php#L46-L57 |
IftekherSunny/Planet-Framework | src/Sun/Support/Alien.php | Alien.shouldReceive | public static function shouldReceive()
{
if(!isset(static::$mocked[static::registerAlien()])) {
static::$mocked[static::registerAlien()] = Mockery::mock(static::registerAlien());
}
return call_user_func_array([static::$mocked[static::registerAlien()], 'shouldReceive'], func_get_args());
} | php | public static function shouldReceive()
{
if(!isset(static::$mocked[static::registerAlien()])) {
static::$mocked[static::registerAlien()] = Mockery::mock(static::registerAlien());
}
return call_user_func_array([static::$mocked[static::registerAlien()], 'shouldReceive'], func_get_args());
} | Initiate mock expectation for the registered alien
@return mixed
@throws Exception | https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Alien.php#L84-L91 |
greggilbert/redoubt | src/Greggilbert/Redoubt/RedoubtServiceProvider.php | RedoubtServiceProvider.boot | public function boot()
{
$this->package('greggilbert/redoubt');
$groupModel = $this->app['config']->get('redoubt::group.model', 'Greggilbert\Redoubt\Group\EloquentGroup');
$userModel = $this->app['config']->get('redoubt::user.model', 'Greggilbert\Redoubt\Group\EloquentUser');
$permissionModel = $this->app['config']->get('redoubt::permission.model', 'Greggilbert\Redoubt\Permission\Permission');
$this->app->bind('redoubt.group', $groupModel);
$this->app->bind('redoubt.user', $userModel);
$this->app->bind('redoubt.permissionModel', $permissionModel);
} | php | public function boot()
{
$this->package('greggilbert/redoubt');
$groupModel = $this->app['config']->get('redoubt::group.model', 'Greggilbert\Redoubt\Group\EloquentGroup');
$userModel = $this->app['config']->get('redoubt::user.model', 'Greggilbert\Redoubt\Group\EloquentUser');
$permissionModel = $this->app['config']->get('redoubt::permission.model', 'Greggilbert\Redoubt\Permission\Permission');
$this->app->bind('redoubt.group', $groupModel);
$this->app->bind('redoubt.user', $userModel);
$this->app->bind('redoubt.permissionModel', $permissionModel);
} | Bootstrap the application events.
@return void | https://github.com/greggilbert/redoubt/blob/941a8b8e2140295f76400f865971c62faf91d601/src/Greggilbert/Redoubt/RedoubtServiceProvider.php#L26-L37 |
greggilbert/redoubt | src/Greggilbert/Redoubt/RedoubtServiceProvider.php | RedoubtServiceProvider.register | public function register()
{
$this->registerGroupProvider();
$this->registerPermissionProvider();
$this->registerGroupObjectPermissionProvider();
$this->registerUserObjectPermissionProvider();
$this->registerRedoubt();
} | php | public function register()
{
$this->registerGroupProvider();
$this->registerPermissionProvider();
$this->registerGroupObjectPermissionProvider();
$this->registerUserObjectPermissionProvider();
$this->registerRedoubt();
} | Register the service provider.
@return void | https://github.com/greggilbert/redoubt/blob/941a8b8e2140295f76400f865971c62faf91d601/src/Greggilbert/Redoubt/RedoubtServiceProvider.php#L44-L52 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Repository.php | Repository.fromClass | function fromClass($className)
{
if(!isset($this->metas[$className]))
{
$this->metas[$className] = $this->findMeta($className, $this);
}
return $this->metas[$className];
} | php | function fromClass($className)
{
if(!isset($this->metas[$className]))
{
$this->metas[$className] = $this->findMeta($className, $this);
}
return $this->metas[$className];
} | Get the meta info for the class specified by $className
@param string $className The class name to get meta for.
@return mixed The meta information for the class. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Repository.php#L57-L65 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Repository.php | Repository.findMeta | private function findMeta($className)
{
$class = new \ReflectionClass($className);
//If it's a proxy class, use the parent for meta
if($class->implementsInterface('LRezek\\Arachnid\\Proxy\\Entity'))
{
$class = $class->getParentClass();
}
$node = $this->reader->getClassAnnotation($class, 'LRezek\\Arachnid\\Annotation\\Node');
$relation = $this->reader->getClassAnnotation($class, 'LRezek\\Arachnid\\Annotation\\Relation');
//Throw an error if it has both annotations
if($node && $relation)
{
throw new Exception("Class $className is defined as both a node and relation.");
}
//Handle nodes
if($node)
{
//Save the node to common object
$entity = $node;
//Create the node
$object = new Node($class->getName());
}
//Handle Relations
else if($relation)
{
//Save the relation to a common object
$entity = $relation;
//Create the relation
$object = new Relation($class->getName());
}
//Unknown annotation
else
{
$className = $class->getName();
throw new Exception("Class $className is not declared as a node or relation.");
}
//Set the objects repo class
$object->setRepositoryClass($entity->repositoryClass);
//Load object properties, and validate it
$object->loadProperties($this->reader, $class->getProperties());
$object->validate();
return $object;
} | php | private function findMeta($className)
{
$class = new \ReflectionClass($className);
//If it's a proxy class, use the parent for meta
if($class->implementsInterface('LRezek\\Arachnid\\Proxy\\Entity'))
{
$class = $class->getParentClass();
}
$node = $this->reader->getClassAnnotation($class, 'LRezek\\Arachnid\\Annotation\\Node');
$relation = $this->reader->getClassAnnotation($class, 'LRezek\\Arachnid\\Annotation\\Relation');
//Throw an error if it has both annotations
if($node && $relation)
{
throw new Exception("Class $className is defined as both a node and relation.");
}
//Handle nodes
if($node)
{
//Save the node to common object
$entity = $node;
//Create the node
$object = new Node($class->getName());
}
//Handle Relations
else if($relation)
{
//Save the relation to a common object
$entity = $relation;
//Create the relation
$object = new Relation($class->getName());
}
//Unknown annotation
else
{
$className = $class->getName();
throw new Exception("Class $className is not declared as a node or relation.");
}
//Set the objects repo class
$object->setRepositoryClass($entity->repositoryClass);
//Load object properties, and validate it
$object->loadProperties($this->reader, $class->getProperties());
$object->validate();
return $object;
} | Does the actual annotation parsing to get meta information for a given class.
@param string $className The class name to get meta for.
@return Node|Relation A node/relation meta object.
@throws \LRezek\Arachnid\Exception Thrown if the class is not a node or relation. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Repository.php#L74-L128 |
mojopollo/laravel-helpers | src/Mojopollo/Helpers/StringHelper.php | StringHelper.limitByWords | public static function limitByWords($str, $wordCount = 10)
{
// Reads amount of words in paragraph
$words = preg_split("/[\s]+/", $str, $wordCount + 1);
// limit paragraph to $wordCount value
$words = array_slice($words, 0, $wordCount);
// Return the words back
return join(' ', $words);
} | php | public static function limitByWords($str, $wordCount = 10)
{
// Reads amount of words in paragraph
$words = preg_split("/[\s]+/", $str, $wordCount + 1);
// limit paragraph to $wordCount value
$words = array_slice($words, 0, $wordCount);
// Return the words back
return join(' ', $words);
} | Returns a string limited by the word count specified
logic borrowed from StackOverflow
@see http://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara#answer-10026115
@param string $str paragraph to limit by words
@param integer $wordCount amount to wordCount paragraph to
@return string string with int limitation set | https://github.com/mojopollo/laravel-helpers/blob/0becb5e0f4202a0f489fb5e384c01dacb8f29dc5/src/Mojopollo/Helpers/StringHelper.php#L63-L73 |
Synapse-Cmf/synapse-cmf | src/Synapse/Cmf/Framework/Media/Image/Action/Dal/UploadAction.php | UploadAction.resolve | public function resolve()
{
$this->setFile($this->fileDomain->upload(
$this->sourceFile
));
if (!$this->name) {
$this->setName($this->getFile()->getOriginalName());
}
return parent::resolve();
} | php | public function resolve()
{
$this->setFile($this->fileDomain->upload(
$this->sourceFile
));
if (!$this->name) {
$this->setName($this->getFile()->getOriginalName());
}
return parent::resolve();
} | Image creation method.
@return Image | https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Media/Image/Action/Dal/UploadAction.php#L24-L34 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.process | public function process()
{
$em = $this->getEm();
$cronRegistry = $this->getCronjobs();
$pending = $this->getPending();
$scheduleLifetime = $this->scheduleLifetime * 60; //convert min to sec
$now = new \DateTime;
foreach ($pending as $job) {
$scheduleTime = $job->getScheduleTime();
if ($scheduleTime > $now) {
continue;
}
try {
$errorStatus = Mapper\Cronjob::STATUS_ERROR;
$missedTime = clone $now;
$timestamp = $missedTime->getTimestamp();
$timestamp -= $scheduleLifetime;
$missedTime->setTimestamp($timestamp);
if ($scheduleTime < $missedTime) {
$errorStatus = Mapper\Cronjob::STATUS_MISSED;
throw new Exception\RuntimeException(
'too late for job'
);
}
$code = $job->getCode();
if (!isset($cronRegistry[$code])) {
throw new Exception\RuntimeException(sprintf(
'job "%s" undefined in cron registry',
$code
));
}
if (!$this->tryLockJob($job)) {
//another cron started this job intermittently. skip.
continue;
}
//run job now
$callback = $cronRegistry[$code]['callback'];
$args = $cronRegistry[$code]['args'];
$job->setExecuteTime(new \DateTime);
$em->persist($job);
$em->flush();
call_user_func_array($callback, $args);
$job
->setStatus(Mapper\Cronjob::STATUS_SUCCESS)
->setFinishTime(new \DateTime);
} catch (\Exception $e) {
$job
->setStatus($errorStatus)
->setErrorMsg($e->getMessage())
->setStackTrace($e->getTraceAsString());
}
$em->persist($job);
$em->flush();
}
return $this;
} | php | public function process()
{
$em = $this->getEm();
$cronRegistry = $this->getCronjobs();
$pending = $this->getPending();
$scheduleLifetime = $this->scheduleLifetime * 60; //convert min to sec
$now = new \DateTime;
foreach ($pending as $job) {
$scheduleTime = $job->getScheduleTime();
if ($scheduleTime > $now) {
continue;
}
try {
$errorStatus = Mapper\Cronjob::STATUS_ERROR;
$missedTime = clone $now;
$timestamp = $missedTime->getTimestamp();
$timestamp -= $scheduleLifetime;
$missedTime->setTimestamp($timestamp);
if ($scheduleTime < $missedTime) {
$errorStatus = Mapper\Cronjob::STATUS_MISSED;
throw new Exception\RuntimeException(
'too late for job'
);
}
$code = $job->getCode();
if (!isset($cronRegistry[$code])) {
throw new Exception\RuntimeException(sprintf(
'job "%s" undefined in cron registry',
$code
));
}
if (!$this->tryLockJob($job)) {
//another cron started this job intermittently. skip.
continue;
}
//run job now
$callback = $cronRegistry[$code]['callback'];
$args = $cronRegistry[$code]['args'];
$job->setExecuteTime(new \DateTime);
$em->persist($job);
$em->flush();
call_user_func_array($callback, $args);
$job
->setStatus(Mapper\Cronjob::STATUS_SUCCESS)
->setFinishTime(new \DateTime);
} catch (\Exception $e) {
$job
->setStatus($errorStatus)
->setErrorMsg($e->getMessage())
->setStackTrace($e->getTraceAsString());
}
$em->persist($job);
$em->flush();
}
return $this;
} | run cron jobs
@return self | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L160-L230 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.cleanLog | public function cleanLog()
{
$em = $this->getEm();
$lifetime = array(
Mapper\Cronjob::STATUS_SUCCESS =>
$this->getSuccessLogLifetime() * 60,
Mapper\Cronjob::STATUS_MISSED =>
$this->getFailureLogLifetime() * 60,
Mapper\Cronjob::STATUS_ERROR =>
$this->getFailureLogLifetime() * 60,
);
$history = $em->getRepository('AdfabCore\Entity\Cronjob')
->getHistory();
$now = time();
foreach ($history as $job) {
if ($job->getExecuteTime()
&& $job->getExecuteTime()->getTimestamp()
< $now - $lifetime[$job->getStatus()]) {
$em->remove($job);
}
}
$em->flush();
return $this;
} | php | public function cleanLog()
{
$em = $this->getEm();
$lifetime = array(
Mapper\Cronjob::STATUS_SUCCESS =>
$this->getSuccessLogLifetime() * 60,
Mapper\Cronjob::STATUS_MISSED =>
$this->getFailureLogLifetime() * 60,
Mapper\Cronjob::STATUS_ERROR =>
$this->getFailureLogLifetime() * 60,
);
$history = $em->getRepository('AdfabCore\Entity\Cronjob')
->getHistory();
$now = time();
foreach ($history as $job) {
if ($job->getExecuteTime()
&& $job->getExecuteTime()->getTimestamp()
< $now - $lifetime[$job->getStatus()]) {
$em->remove($job);
}
}
$em->flush();
return $this;
} | delete old cron job logs
@return self | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L333-L360 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.tryLockJob | public function tryLockJob(Entity\Cronjob $job)
{
$em = $this->getEm();
$repo = $em->getRepository('AdfabCore\Entity\Cronjob');
if ($job->getStatus() === Mapper\Cronjob::STATUS_PENDING) {
$job->setStatus(Mapper\Cronjob::STATUS_RUNNING);
$em->persist($job);
$em->flush();
// flush() succeeded if reached here;
// otherwise an Exception would have been thrown
return true;
}
return false;
} | php | public function tryLockJob(Entity\Cronjob $job)
{
$em = $this->getEm();
$repo = $em->getRepository('AdfabCore\Entity\Cronjob');
if ($job->getStatus() === Mapper\Cronjob::STATUS_PENDING) {
$job->setStatus(Mapper\Cronjob::STATUS_RUNNING);
$em->persist($job);
$em->flush();
// flush() succeeded if reached here;
// otherwise an Exception would have been thrown
return true;
}
return false;
} | try to acquire a lock on a cron job
set a job to 'running' only if it is currently 'pending'
@param Entity\Cronjob $job
@return bool | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L380-L395 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.matchTime | public static function matchTime($time, $expr)
{
//ArgValidator::assert($time, array('string', 'numeric'));
//ArgValidator::assert($expr, 'string');
$cronExpr = preg_split('/\s+/', $expr, null, PREG_SPLIT_NO_EMPTY);
if (count($cronExpr) !== 5) {
throw new Exception\InvalidArgumentException(sprintf(
'cron expression should have exactly 5 arguments, "%s" given',
$expr
));
}
if (is_string($time)) $time = strtotime($time);
$date = getdate($time);
return self::matchTimeComponent($cronExpr[0], $date['minutes'])
&& self::matchTimeComponent($cronExpr[1], $date['hours'])
&& self::matchTimeComponent($cronExpr[2], $date['mday'])
&& self::matchTimeComponent($cronExpr[3], $date['mon'])
&& self::matchTimeComponent($cronExpr[4], $date['wday']);
} | php | public static function matchTime($time, $expr)
{
//ArgValidator::assert($time, array('string', 'numeric'));
//ArgValidator::assert($expr, 'string');
$cronExpr = preg_split('/\s+/', $expr, null, PREG_SPLIT_NO_EMPTY);
if (count($cronExpr) !== 5) {
throw new Exception\InvalidArgumentException(sprintf(
'cron expression should have exactly 5 arguments, "%s" given',
$expr
));
}
if (is_string($time)) $time = strtotime($time);
$date = getdate($time);
return self::matchTimeComponent($cronExpr[0], $date['minutes'])
&& self::matchTimeComponent($cronExpr[1], $date['hours'])
&& self::matchTimeComponent($cronExpr[2], $date['mday'])
&& self::matchTimeComponent($cronExpr[3], $date['mon'])
&& self::matchTimeComponent($cronExpr[4], $date['wday']);
} | determine whether a given time falls within the given cron expr
@param string|numeric $time
timestamp or strtotime()-compatible string
@param string $expr
any valid cron expression, in addition supporting:
range: '0-5'
range + interval: '10-59/5'
comma-separated combinations of these: '1,4,7,10-20'
English months: 'january'
English months (abbreviated to three letters): 'jan'
English weekdays: 'monday'
English weekdays (abbreviated to three letters): 'mon'
These text counterparts can be used in all places where their
numerical counterparts are allowed, e.g. 'jan-jun/2'
A full example:
'0-5,10-59/5 * 2-10,15-25 january-june/2 mon-fri' -
every minute between minute 0-5 + every 5th min between 10-59
every hour
every day between day 2-10 and day 15-25
every 2nd month between January-June
Monday-Friday
@throws Exception\InvalidArgumentException on invalid cron expression
@return bool | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L423-L445 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.matchTimeComponent | public static function matchTimeComponent($expr, $num)
{
//ArgValidator::assert($expr, 'string');
//ArgValidator::assert($num, 'numeric');
//handle all match
if ($expr === '*') {
return true;
}
//handle multiple options
if (strpos($expr, ',') !== false) {
$args = explode(',', $expr);
foreach ($args as $arg) {
if (self::matchTimeComponent($arg, $num)) {
return true;
}
}
return false;
}
//handle modulus
if (strpos($expr, '/') !== false) {
$arg = explode('/', $expr);
if (count($arg) !== 2) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting match/modulus, "%s" given',
$expr
));
}
if (!is_numeric($arg[1])) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting numeric modulus, "%s" given',
$expr
));
}
$expr = $arg[0];
$mod = $arg[1];
} else {
$mod = 1;
}
//handle all match by modulus
if ($expr === '*') {
$from = 0;
$to = 60;
}
//handle range
elseif (strpos($expr, '-') !== false) {
$arg = explode('-', $expr);
if (count($arg) !== 2) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting from-to structure, "%s" given',
$expr
));
}
$from = self::exprToNumeric($arg[0]);
$to = self::exprToNumeric($arg[1]);
}
//handle regular token
else {
$from = self::exprToNumeric($expr);
$to = $from;
}
if ($from === false || $to === false) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting numeric or valid string, "%s" given',
$expr
));
}
return ($num >= $from) && ($num <= $to) && ($num % $mod === 0);
} | php | public static function matchTimeComponent($expr, $num)
{
//ArgValidator::assert($expr, 'string');
//ArgValidator::assert($num, 'numeric');
//handle all match
if ($expr === '*') {
return true;
}
//handle multiple options
if (strpos($expr, ',') !== false) {
$args = explode(',', $expr);
foreach ($args as $arg) {
if (self::matchTimeComponent($arg, $num)) {
return true;
}
}
return false;
}
//handle modulus
if (strpos($expr, '/') !== false) {
$arg = explode('/', $expr);
if (count($arg) !== 2) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting match/modulus, "%s" given',
$expr
));
}
if (!is_numeric($arg[1])) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting numeric modulus, "%s" given',
$expr
));
}
$expr = $arg[0];
$mod = $arg[1];
} else {
$mod = 1;
}
//handle all match by modulus
if ($expr === '*') {
$from = 0;
$to = 60;
}
//handle range
elseif (strpos($expr, '-') !== false) {
$arg = explode('-', $expr);
if (count($arg) !== 2) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting from-to structure, "%s" given',
$expr
));
}
$from = self::exprToNumeric($arg[0]);
$to = self::exprToNumeric($arg[1]);
}
//handle regular token
else {
$from = self::exprToNumeric($expr);
$to = $from;
}
if ($from === false || $to === false) {
throw new Exception\InvalidArgumentException(sprintf(
'invalid cron expression component: '
. 'expecting numeric or valid string, "%s" given',
$expr
));
}
return ($num >= $from) && ($num <= $to) && ($num % $mod === 0);
} | match a cron expression component to a given corresponding date/time
In the expression, * * * * *, each component
*[1] *[2] *[3] *[4] *[5]
will correspond to a getdate() component
1. $date['minutes']
2. $date['hours']
3. $date['mday']
4. $date['mon']
5. $date['wday']
@see self::exprToNumeric() for additional valid string values
@param string $expr
@param numeric $num
@throws Exception\InvalidArgumentException on invalid expression
@return bool | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L466-L545 |
gregorybesson/AdfabCore | src/AdfabCore/Service/Cron.php | Cron.exprToNumeric | public static function exprToNumeric($value)
{
//ArgValidator::assert($value, array('string', 'numeric'));
static $data = array(
'jan' => 1,
'feb' => 2,
'mar' => 3,
'apr' => 4,
'may' => 5,
'jun' => 6,
'jul' => 7,
'aug' => 8,
'sep' => 9,
'oct' => 10,
'nov' => 11,
'dec' => 12,
'sun' => 0,
'mon' => 1,
'tue' => 2,
'wed' => 3,
'thu' => 4,
'fri' => 5,
'sat' => 6,
);
if (is_numeric($value)) {
if (in_array((int) $value, $data, true)) {
return $value;
} else {
return false;
}
}
if (is_string($value)) {
$value = strtolower(substr($value, 0, 3));
if (isset($data[$value])) {
return $data[$value];
}
}
return false;
} | php | public static function exprToNumeric($value)
{
//ArgValidator::assert($value, array('string', 'numeric'));
static $data = array(
'jan' => 1,
'feb' => 2,
'mar' => 3,
'apr' => 4,
'may' => 5,
'jun' => 6,
'jul' => 7,
'aug' => 8,
'sep' => 9,
'oct' => 10,
'nov' => 11,
'dec' => 12,
'sun' => 0,
'mon' => 1,
'tue' => 2,
'wed' => 3,
'thu' => 4,
'fri' => 5,
'sat' => 6,
);
if (is_numeric($value)) {
if (in_array((int) $value, $data, true)) {
return $value;
} else {
return false;
}
}
if (is_string($value)) {
$value = strtolower(substr($value, 0, 3));
if (isset($data[$value])) {
return $data[$value];
}
}
return false;
} | parse a string month / weekday expression to its numeric equivalent
@param string|numeric $value
accepts, case insensitive,
- Jan - Dec
- Sun - Sat
- (or their long forms - only the first three letters important)
@return int|false | https://github.com/gregorybesson/AdfabCore/blob/94078662dae092c2782829bd1554e1426acdf671/src/AdfabCore/Service/Cron.php#L557-L600 |
hannesvdvreken/psr7-middlewares | src/Stack.php | Stack.handle | public function handle(RequestInterface $request)
{
$index = 0;
while ($this->canSetNextCore($index)) {
$this->middlewares[$index]->setNextCore($this->middlewares[$index + 1]);
++$index;
}
return $this->middlewares[0]->handle($request);
} | php | public function handle(RequestInterface $request)
{
$index = 0;
while ($this->canSetNextCore($index)) {
$this->middlewares[$index]->setNextCore($this->middlewares[$index + 1]);
++$index;
}
return $this->middlewares[0]->handle($request);
} | @param RequestInterface $request
@return ResponseInterface | https://github.com/hannesvdvreken/psr7-middlewares/blob/972bc8e5e567efa628a91edc6ddc146c8209b209/src/Stack.php#L21-L31 |
hannesvdvreken/psr7-middlewares | src/Stack.php | Stack.create | public static function create(array $middlewares)
{
if (empty($middlewares)) {
throw new StackException('Middlewares array cannot be empty.');
}
$stack = new static();
$stack->middlewares = $middlewares;
return $stack;
} | php | public static function create(array $middlewares)
{
if (empty($middlewares)) {
throw new StackException('Middlewares array cannot be empty.');
}
$stack = new static();
$stack->middlewares = $middlewares;
return $stack;
} | @param Kernel[] $middlewares
@throws StackException
@return static | https://github.com/hannesvdvreken/psr7-middlewares/blob/972bc8e5e567efa628a91edc6ddc146c8209b209/src/Stack.php#L40-L51 |
hannesvdvreken/psr7-middlewares | src/Stack.php | Stack.canSetNextCore | private function canSetNextCore($index)
{
if (count($this->middlewares) <= $index + 1) {
// Prevent index out of bounds error
return false;
}
if ($this->middlewares[$index] instanceof Kernel) {
// As long as the current core is a kernel it can be notified of next core.
return true;
}
return false;
} | php | private function canSetNextCore($index)
{
if (count($this->middlewares) <= $index + 1) {
// Prevent index out of bounds error
return false;
}
if ($this->middlewares[$index] instanceof Kernel) {
// As long as the current core is a kernel it can be notified of next core.
return true;
}
return false;
} | @param int $index
@return bool | https://github.com/hannesvdvreken/psr7-middlewares/blob/972bc8e5e567efa628a91edc6ddc146c8209b209/src/Stack.php#L58-L71 |
sarcoma/email | src/Email/Email.php | Email.getTwigTemplate | public function getTwigTemplate($content = array(), $template = null, $directory = null)
{
if ($template && $directory) {
$loader = new Twig_Loader_Filesystem($directory);
} else {
$loader = new Twig_Loader_Filesystem(__DIR__ . "/../../views");
$template = 'email.twig';
}
$twig = new Twig_Environment($loader);
return $twig->render($template, array(
'email_title' => $this->email_title,
'body_color' => $this->body_color,
'table_color' => $this->table_color,
'content' => $content
));
} | php | public function getTwigTemplate($content = array(), $template = null, $directory = null)
{
if ($template && $directory) {
$loader = new Twig_Loader_Filesystem($directory);
} else {
$loader = new Twig_Loader_Filesystem(__DIR__ . "/../../views");
$template = 'email.twig';
}
$twig = new Twig_Environment($loader);
return $twig->render($template, array(
'email_title' => $this->email_title,
'body_color' => $this->body_color,
'table_color' => $this->table_color,
'content' => $content
));
} | @param array $content
@param null $template
@param null $directory
@uses Twig_Loader_Filesystem()
@uses Twig_Environment()
@return string | https://github.com/sarcoma/email/blob/9c82cc695a6a9240a872adf7c549732c5bcb7860/src/Email/Email.php#L187-L203 |
sarcoma/email | src/Email/Email.php | Email.check_required_fields | public function check_required_fields($array)
{
$errors = array();
foreach ($array as $key => $field_name) {
// check that required fields are set
if (!isset($field_name) || (empty($field_name) && $field_name != '0')) {
$errors[] = $key . " is empty.";
}
}
return $errors;
} | php | public function check_required_fields($array)
{
$errors = array();
foreach ($array as $key => $field_name) {
// check that required fields are set
if (!isset($field_name) || (empty($field_name) && $field_name != '0')) {
$errors[] = $key . " is empty.";
}
}
return $errors;
} | @param array $array
@return array $errors | https://github.com/sarcoma/email/blob/9c82cc695a6a9240a872adf7c549732c5bcb7860/src/Email/Email.php#L210-L221 |
sarcoma/email | src/Email/Email.php | Email.makeStyles | protected function makeStyles($styles = array())
{
$styles = array_merge($this->styles, $styles);
$output = '';
foreach ($styles as $property => $value) {
$output .= $property . ':' . $value . ';';
}
return $output;
} | php | protected function makeStyles($styles = array())
{
$styles = array_merge($this->styles, $styles);
$output = '';
foreach ($styles as $property => $value) {
$output .= $property . ':' . $value . ';';
}
return $output;
} | @param array $styles
@return string | https://github.com/sarcoma/email/blob/9c82cc695a6a9240a872adf7c549732c5bcb7860/src/Email/Email.php#L250-L259 |
sarcoma/email | src/Email/Email.php | Email.modularScale | public function modularScale($scale = 0)
{
$size = $this->base_font_size;
$i = 0;
if ($scale > 0) {
while ($i < $scale) {
$size = round($size * $this->ratio, 2);
$i ++;
}
} elseif ($scale < 0) {
while ($i > $scale) {
$size = round($size / $this->ratio, 2);
$i --;
}
}
return $size . "px";
} | php | public function modularScale($scale = 0)
{
$size = $this->base_font_size;
$i = 0;
if ($scale > 0) {
while ($i < $scale) {
$size = round($size * $this->ratio, 2);
$i ++;
}
} elseif ($scale < 0) {
while ($i > $scale) {
$size = round($size / $this->ratio, 2);
$i --;
}
}
return $size . "px";
} | @param int $scale
@return string | https://github.com/sarcoma/email/blob/9c82cc695a6a9240a872adf7c549732c5bcb7860/src/Email/Email.php#L266-L283 |
schpill/thin | src/Minify/Html.php | Html.process | public function process()
{
if ($this->_isXhtml === null) {
$this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
}
$this->_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
$this->_placeholders = array();
// replace SCRIPTs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/(\\s*)(<script\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/i'
, array($this, '_removeScriptCB')
, $this->_html);
// replace STYLEs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/\\s*(<style\\b[^>]*?>)([\\s\\S]*?)<\\/style>\\s*/i'
, array($this, '_removeStyleCB')
, $this->_html);
// remove HTML comments (not containing IE conditional comments).
$this->_html = preg_replace_callback(
'/<!--([\\s\\S]*?)-->/'
, array($this, '_commentCB')
, $this->_html);
// replace PREs with placeholders
$this->_html = preg_replace_callback('/\\s*(<pre\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i'
, array($this, '_removePreCB')
, $this->_html);
// replace TEXTAREAs with placeholders
$this->_html = preg_replace_callback(
'/\\s*(<textarea\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i'
, array($this, '_removeTextareaCB')
, $this->_html);
// trim each line.
// @todo take into account attribute values that span multiple lines.
$this->_html = preg_replace('/^\\s+|\\s+$/m', '', $this->_html);
// remove ws around block/undisplayed elements
$this->_html = preg_replace('/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body'
. '|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'
. '|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'
. '|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)'
. '|ul)\\b[^>]*>)/i', '$1', $this->_html);
// remove ws outside of all elements
$this->_html = preg_replace_callback(
'/>([^<]+)</'
, array($this, '_outsideTagCB')
, $this->_html);
// use newlines before 1st attribute in open tags (to limit line lengths)
$this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $this->_html);
// fill placeholders
$this->_html = str_replace(
array_keys($this->_placeholders)
, array_values($this->_placeholders)
, $this->_html
);
return $this->_html;
} | php | public function process()
{
if ($this->_isXhtml === null) {
$this->_isXhtml = (false !== strpos($this->_html, '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML'));
}
$this->_replacementHash = 'MINIFYHTML' . md5($_SERVER['REQUEST_TIME']);
$this->_placeholders = array();
// replace SCRIPTs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/(\\s*)(<script\\b[^>]*?>)([\\s\\S]*?)<\\/script>(\\s*)/i'
, array($this, '_removeScriptCB')
, $this->_html);
// replace STYLEs (and minify) with placeholders
$this->_html = preg_replace_callback(
'/\\s*(<style\\b[^>]*?>)([\\s\\S]*?)<\\/style>\\s*/i'
, array($this, '_removeStyleCB')
, $this->_html);
// remove HTML comments (not containing IE conditional comments).
$this->_html = preg_replace_callback(
'/<!--([\\s\\S]*?)-->/'
, array($this, '_commentCB')
, $this->_html);
// replace PREs with placeholders
$this->_html = preg_replace_callback('/\\s*(<pre\\b[^>]*?>[\\s\\S]*?<\\/pre>)\\s*/i'
, array($this, '_removePreCB')
, $this->_html);
// replace TEXTAREAs with placeholders
$this->_html = preg_replace_callback(
'/\\s*(<textarea\\b[^>]*?>[\\s\\S]*?<\\/textarea>)\\s*/i'
, array($this, '_removeTextareaCB')
, $this->_html);
// trim each line.
// @todo take into account attribute values that span multiple lines.
$this->_html = preg_replace('/^\\s+|\\s+$/m', '', $this->_html);
// remove ws around block/undisplayed elements
$this->_html = preg_replace('/\\s+(<\\/?(?:area|base(?:font)?|blockquote|body'
. '|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form'
. '|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta'
. '|ol|opt(?:group|ion)|p|param|t(?:able|body|head|d|h||r|foot|itle)'
. '|ul)\\b[^>]*>)/i', '$1', $this->_html);
// remove ws outside of all elements
$this->_html = preg_replace_callback(
'/>([^<]+)</'
, array($this, '_outsideTagCB')
, $this->_html);
// use newlines before 1st attribute in open tags (to limit line lengths)
$this->_html = preg_replace('/(<[a-z\\-]+)\\s+([^>]+>)/i', "$1\n$2", $this->_html);
// fill placeholders
$this->_html = str_replace(
array_keys($this->_placeholders)
, array_values($this->_placeholders)
, $this->_html
);
return $this->_html;
} | Minify the markeup given in the constructor
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Minify/Html.php#L37-L103 |
xiewulong/yii2-wechat | models/WechatMessageRule.php | WechatMessageRule.keywords | public static function keywords($appid, $content) {
$keyword = WechatMessageKeyword::find()->where("appid = '$appid' and mode = 1 and keyword = '" . addslashes($content) . "'")->orderBy('rand()')->one();
if(!$keyword) {
$keywords = [];
foreach(ArrayHelper::getColumn(WechatMessageKeyword::find()->where("appid = '$appid' and mode = 0")->select('keyword')->asArray()->all(), 'keyword') as $_keyword) {
$keywords[] = addcslashes($_keyword, "\|/<>()[]{}^$?*+.");
}
if($keywords) {
$keywords = implode('|', $keywords);
preg_match_all("/$keywords/i", $content, $matches);
$matches = array_unique($matches[0]);
foreach($matches as $index => $match) {
$matches[$index] = addslashes($match);
}
$keyword = WechatMessageKeyword::find()->where("appid = '$appid' and mode = 0 and keyword in ('" . implode("','", $matches) . "')")->orderBy('rand()')->one();
}
}
$rule = $keyword ? $keyword->rule : static::findOne(['appid' => $appid, 'type' => 'autoreply']);
return $rule ? $rule->messageFormat : [];
} | php | public static function keywords($appid, $content) {
$keyword = WechatMessageKeyword::find()->where("appid = '$appid' and mode = 1 and keyword = '" . addslashes($content) . "'")->orderBy('rand()')->one();
if(!$keyword) {
$keywords = [];
foreach(ArrayHelper::getColumn(WechatMessageKeyword::find()->where("appid = '$appid' and mode = 0")->select('keyword')->asArray()->all(), 'keyword') as $_keyword) {
$keywords[] = addcslashes($_keyword, "\|/<>()[]{}^$?*+.");
}
if($keywords) {
$keywords = implode('|', $keywords);
preg_match_all("/$keywords/i", $content, $matches);
$matches = array_unique($matches[0]);
foreach($matches as $index => $match) {
$matches[$index] = addslashes($match);
}
$keyword = WechatMessageKeyword::find()->where("appid = '$appid' and mode = 0 and keyword in ('" . implode("','", $matches) . "')")->orderBy('rand()')->one();
}
}
$rule = $keyword ? $keyword->rule : static::findOne(['appid' => $appid, 'type' => 'autoreply']);
return $rule ? $rule->messageFormat : [];
} | 获取
@method keywords
@since 0.0.1
@param {string} $appid AppID
@param {string} $content 文本消息内容
@return {array}
@example static::keywords($appid, $content); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatMessageRule.php#L32-L53 |
xiewulong/yii2-wechat | models/WechatMessageRule.php | WechatMessageRule.getMessageFormat | public function getMessageFormat() {
$message = ['msg_type' => $this->msg_type];
switch($this->msg_type) {
case 'text':
$message['content'] = $this->content;
break;
case 'video':
$message['title'] = $this->title;
$message['description'] = $this->description;
case 'image':
case 'voice':
$message['media_id'] = $this->materialMedia->media_id;
$message['media_url'] = $this->materialMedia->material->url;
break;
case 'music':
$message['title'] = $this->title;
$message['description'] = $this->description;
$message['music_url'] = $this->music_url;
$message['hq_music_url'] = $this->hq_music_url;
$message['thumb_media_id'] = $this->thumbMaterialMedia->media_id;
$message['thumb_media_url'] = $this->thumbMaterialMedia->material->url;
break;
case 'news':
$pic_urls = $this->newsMedia->thumbUrlList;
$urls = $this->newsMedia->urlList;
$articles = [];
foreach($this->newsMedia->news->items as $index => $item) {
if(!isset($pic_urls[$index]) || !isset($urls[$index])) {
break;
}
$articles[] = [
'title' => $item->title,
'description' => $item->digest,
'pic_url' => $pic_urls[$index],
'url' => $urls[$index],
];
}
$message['articles'] = Json::encode($articles);
break;
default:
return [];
break;
}
return $message;
} | php | public function getMessageFormat() {
$message = ['msg_type' => $this->msg_type];
switch($this->msg_type) {
case 'text':
$message['content'] = $this->content;
break;
case 'video':
$message['title'] = $this->title;
$message['description'] = $this->description;
case 'image':
case 'voice':
$message['media_id'] = $this->materialMedia->media_id;
$message['media_url'] = $this->materialMedia->material->url;
break;
case 'music':
$message['title'] = $this->title;
$message['description'] = $this->description;
$message['music_url'] = $this->music_url;
$message['hq_music_url'] = $this->hq_music_url;
$message['thumb_media_id'] = $this->thumbMaterialMedia->media_id;
$message['thumb_media_url'] = $this->thumbMaterialMedia->material->url;
break;
case 'news':
$pic_urls = $this->newsMedia->thumbUrlList;
$urls = $this->newsMedia->urlList;
$articles = [];
foreach($this->newsMedia->news->items as $index => $item) {
if(!isset($pic_urls[$index]) || !isset($urls[$index])) {
break;
}
$articles[] = [
'title' => $item->title,
'description' => $item->digest,
'pic_url' => $pic_urls[$index],
'url' => $urls[$index],
];
}
$message['articles'] = Json::encode($articles);
break;
default:
return [];
break;
}
return $message;
} | 获取回复消息格式
@method getMessageFormat
@since 0.0.1
@return {array}
@example $this->getMessageFormat(); | https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/models/WechatMessageRule.php#L76-L121 |
rstoetter/ctextparser-php | src/cTextParser.class.php | cTextParser.SkipWhitespacesLine | protected function SkipWhitespacesLine( ) {
// skip all following whitespaces BUT NOT "\n"
$fertig = false;
$ret = false;
$str = '';
if ( $this->m_scriptpos == -1 ) $this->GetChar( );
while ( $this->IsWhitespaceLine( $this->ActChar( ) ) && ( !$this->EOT( )) ) {
$ret = true;
$this->GetChar();
}
assert( ! $this->IsWhitespaceLine( $this->ActChar( ) ) );
return $ret;
// echo "\nskipped whites";
} | php | protected function SkipWhitespacesLine( ) {
// skip all following whitespaces BUT NOT "\n"
$fertig = false;
$ret = false;
$str = '';
if ( $this->m_scriptpos == -1 ) $this->GetChar( );
while ( $this->IsWhitespaceLine( $this->ActChar( ) ) && ( !$this->EOT( )) ) {
$ret = true;
$this->GetChar();
}
assert( ! $this->IsWhitespaceLine( $this->ActChar( ) ) );
return $ret;
// echo "\nskipped whites";
} | function SkipWhitespaces() | https://github.com/rstoetter/ctextparser-php/blob/63c471d062ac7f5d54ee9d392fabc06bb7c75c38/src/cTextParser.class.php#L296-L317 |
chenshenchao/palex | main/crypt/RSAPrivateKey.php | RsaPrivateKey.encrypt | public function encrypt($data) {
if (is_array($data)) return array_map([$this, __FUNCTION__], $data);
openssl_private_encrypt($data, $result, $this->key);
return base64_encode($result);
} | php | public function encrypt($data) {
if (is_array($data)) return array_map([$this, __FUNCTION__], $data);
openssl_private_encrypt($data, $result, $this->key);
return base64_encode($result);
} | encrypt by key.
@param string|array $data: encrypt data reference. | https://github.com/chenshenchao/palex/blob/9d809a876c4a996d3bd38634c4fc2f0a93301838/main/crypt/RSAPrivateKey.php#L56-L60 |
hametuha/pattern | app/Hametuha/Pattern/Command.php | Command.sql | public function sql( $args ) {
list( $table_name ) = $args;
$rows = Model::$list;
if ( ! isset( $rows[ $table_name ] ) ) {
\WP_CLI::error( sprintf( '%s: table is not registered.', $table_name ) );
}
$model = $rows[ $table_name ];
if ( ! class_exists( $model ) ) {
\WP_CLI::error( sprintf( '%s: Model class does not exist.', $model ) );
}
if ( ! $this->is_sub_class_of( $model, Model::class ) ) {
\WP_CLI::error( sprintf( '%s is not sub class of %s.', $model, Model::class ) );
}
/** @var Model $instance */
$instance = $model::get_instance();
\WP_CLI::line( sprintf( '%s: Version %s', $instance->table, $instance->version ) );
$query = $instance->get_tables_schema( $instance->current_version() );
echo "\n" . $query . "\n\n";
\WP_CLI::success( sprintf( '%s letters', number_format_i18n( strlen( $query ) ) ) );
} | php | public function sql( $args ) {
list( $table_name ) = $args;
$rows = Model::$list;
if ( ! isset( $rows[ $table_name ] ) ) {
\WP_CLI::error( sprintf( '%s: table is not registered.', $table_name ) );
}
$model = $rows[ $table_name ];
if ( ! class_exists( $model ) ) {
\WP_CLI::error( sprintf( '%s: Model class does not exist.', $model ) );
}
if ( ! $this->is_sub_class_of( $model, Model::class ) ) {
\WP_CLI::error( sprintf( '%s is not sub class of %s.', $model, Model::class ) );
}
/** @var Model $instance */
$instance = $model::get_instance();
\WP_CLI::line( sprintf( '%s: Version %s', $instance->table, $instance->version ) );
$query = $instance->get_tables_schema( $instance->current_version() );
echo "\n" . $query . "\n\n";
\WP_CLI::success( sprintf( '%s letters', number_format_i18n( strlen( $query ) ) ) );
} | Display table schema SQL
## OPTIONS
<model_class>
: Model class name of Hametuha\Pattern\Model
## EXAMPLES
wp schema wp_custom_table
@synopsis <table_name>
@param array $args | https://github.com/hametuha/pattern/blob/562d18f8e750d1c4e52c537839679807a0e3d055/app/Hametuha/Pattern/Command.php#L31-L50 |
hametuha/pattern | app/Hametuha/Pattern/Command.php | Command.tables | public function tables() {
$table = new \cli\Table();
$rows = Model::$list;
if ( ! $rows ) {
\WP_CLI::error( 'No model is regsitered.' );
}
$table->setHeaders( [ 'Table Name', 'Model Class' ] );
foreach ( $rows as $table_name => $class) {
$table->addRow( [ $table_name, $class ] );
}
$table->display();
} | php | public function tables() {
$table = new \cli\Table();
$rows = Model::$list;
if ( ! $rows ) {
\WP_CLI::error( 'No model is regsitered.' );
}
$table->setHeaders( [ 'Table Name', 'Model Class' ] );
foreach ( $rows as $table_name => $class) {
$table->addRow( [ $table_name, $class ] );
}
$table->display();
} | Get list of tables which generated by Hametuha\Pattern\Model | https://github.com/hametuha/pattern/blob/562d18f8e750d1c4e52c537839679807a0e3d055/app/Hametuha/Pattern/Command.php#L55-L66 |
alphacomm/alpharpc | src/AlphaRPC/Client/ManagerList.php | ManagerList.add | public function add($manager)
{
if (!is_string($manager)) {
throw new \InvalidArgumentException('ManagerList::add requires $manager to be a string.');
}
$this->managerList[$manager] = $manager;
$this->managerStatus[self::FLAG_AVAILABLE][$manager] = $manager;
return $this;
} | php | public function add($manager)
{
if (!is_string($manager)) {
throw new \InvalidArgumentException('ManagerList::add requires $manager to be a string.');
}
$this->managerList[$manager] = $manager;
$this->managerStatus[self::FLAG_AVAILABLE][$manager] = $manager;
return $this;
} | Adds a manager dsn to the list.
@param string $manager
@return ManagerList
@throws \InvalidArgumentException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/ManagerList.php#L71-L81 |
alphacomm/alpharpc | src/AlphaRPC/Client/ManagerList.php | ManagerList.toPrioritizedArray | public function toPrioritizedArray()
{
// Reset the available managers every $this->unavailableCheckAt requests.
if (($this->resetCounter % $this->resetAt) == 0) {
$this->resetAvailableManagers();
}
$this->resetCounter++;
$available =& $this->managerStatus[self::FLAG_AVAILABLE];
$unavailable =& $this->managerStatus[self::FLAG_UNAVAILABLE];
// Shuffle the available managers to distribute load.
shuffle($available);
// Add the unavailable managers at the end.
$managerList = array_merge($available, $unavailable);
return $managerList;
} | php | public function toPrioritizedArray()
{
// Reset the available managers every $this->unavailableCheckAt requests.
if (($this->resetCounter % $this->resetAt) == 0) {
$this->resetAvailableManagers();
}
$this->resetCounter++;
$available =& $this->managerStatus[self::FLAG_AVAILABLE];
$unavailable =& $this->managerStatus[self::FLAG_UNAVAILABLE];
// Shuffle the available managers to distribute load.
shuffle($available);
// Add the unavailable managers at the end.
$managerList = array_merge($available, $unavailable);
return $managerList;
} | Returns an array or manager dsns, sorted by priority.
Available managers get priority over unavailable managers.
Once every x calls all managers will be flagged as available.
This makes sure managers that where unavailable for a period of
time will receive jobs once they get up.
@return array[] | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/ManagerList.php#L106-L124 |
alphacomm/alpharpc | src/AlphaRPC/Client/ManagerList.php | ManagerList.flag | public function flag($manager, $flag)
{
if (!in_array($flag, array(self::FLAG_AVAILABLE, self::FLAG_UNAVAILABLE))) {
throw new \InvalidArgumentException(
'Client::flagManager $flag argument must be one of the FLAG_ constants');
}
if (!isset($this->managerStatus[$flag][$manager])) {
$this->managerStatus[$flag][$manager] = $manager;
}
$removeFlag = ($flag != self::FLAG_AVAILABLE) ? self::FLAG_AVAILABLE : self::FLAG_UNAVAILABLE;
if (isset($this->managerStatus[$removeFlag][$manager])) {
unset($this->managerStatus[$removeFlag][$manager]);
}
} | php | public function flag($manager, $flag)
{
if (!in_array($flag, array(self::FLAG_AVAILABLE, self::FLAG_UNAVAILABLE))) {
throw new \InvalidArgumentException(
'Client::flagManager $flag argument must be one of the FLAG_ constants');
}
if (!isset($this->managerStatus[$flag][$manager])) {
$this->managerStatus[$flag][$manager] = $manager;
}
$removeFlag = ($flag != self::FLAG_AVAILABLE) ? self::FLAG_AVAILABLE : self::FLAG_UNAVAILABLE;
if (isset($this->managerStatus[$removeFlag][$manager])) {
unset($this->managerStatus[$removeFlag][$manager]);
}
} | Flags a manager as (un)available, changing its priority.
@param string $manager
@param string $flag
@throws \InvalidArgumentException | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/ManagerList.php#L135-L150 |
alphacomm/alpharpc | src/AlphaRPC/Client/ManagerList.php | ManagerList.resetAvailableManagers | protected function resetAvailableManagers()
{
$this->managerStatus[self::FLAG_AVAILABLE] = $this->managerList;
$this->managerStatus[self::FLAG_UNAVAILABLE] = array();
} | php | protected function resetAvailableManagers()
{
$this->managerStatus[self::FLAG_AVAILABLE] = $this->managerList;
$this->managerStatus[self::FLAG_UNAVAILABLE] = array();
} | Makes all managers available. | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Client/ManagerList.php#L156-L160 |
RadialCorp/magento-core | src/app/code/community/Radial/Core/Helper/Api/Validator.php | Radial_Core_Helper_Api_Validator.returnClientErrorResponse | public function returnClientErrorResponse(Zend_Http_Response $response)
{
$status = $response->getStatus();
switch ($status) {
case 401:
$message = self::INVALID_API_KEY;
break;
case 403:
$message = self::INVALID_STORE_ID;
break;
case 408:
$message = self::NETWORK_TIMEOUT;
break;
default:
$message = self::UNKNOWN_FAILURE;
break;
}
return array(
'message' => Mage::helper('radial_core')->__($message), 'success' => false
);
} | php | public function returnClientErrorResponse(Zend_Http_Response $response)
{
$status = $response->getStatus();
switch ($status) {
case 401:
$message = self::INVALID_API_KEY;
break;
case 403:
$message = self::INVALID_STORE_ID;
break;
case 408:
$message = self::NETWORK_TIMEOUT;
break;
default:
$message = self::UNKNOWN_FAILURE;
break;
}
return array(
'message' => Mage::helper('radial_core')->__($message), 'success' => false
);
} | Return the response data for client errors - 4XX range errors.
@param Zend_Http_Response $response
@return array | https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Core/Helper/Api/Validator.php#L58-L78 |
x2ts/x2ts | src/cache/CCache.php | CCache.get | public function get($key) {
$file = $this->key2file($key);
if (is_file($file)) {
/** @noinspection PhpIncludeInspection */
$r = require $file;
if (!empty($r) && $key === $r['key'] && (0 === $r['expiration'] || time() <= $r['expiration'])) {
X::logger()->trace("CCache hit $key");
return $r['data'];
}
}
X::logger()->trace("CCache miss $key");
return false;
} | php | public function get($key) {
$file = $this->key2file($key);
if (is_file($file)) {
/** @noinspection PhpIncludeInspection */
$r = require $file;
if (!empty($r) && $key === $r['key'] && (0 === $r['expiration'] || time() <= $r['expiration'])) {
X::logger()->trace("CCache hit $key");
return $r['data'];
}
}
X::logger()->trace("CCache miss $key");
return false;
} | @param string $key
@return mixed | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/cache/CCache.php#L40-L52 |
x2ts/x2ts | src/cache/CCache.php | CCache.set | public function set($key, $value, $duration) {
X::logger()->trace("CCache set $key expire in $duration");
$file = $this->key2file($key);
$content = array(
'key' => $key,
'expiration' => $duration > 0 ? time() + $duration : 0,
'data' => $value,
);
$phpCode = '<?php return ' . Toolkit::compile($content) . ';';
if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
}
file_put_contents($file, $phpCode, LOCK_EX);
} | php | public function set($key, $value, $duration) {
X::logger()->trace("CCache set $key expire in $duration");
$file = $this->key2file($key);
$content = array(
'key' => $key,
'expiration' => $duration > 0 ? time() + $duration : 0,
'data' => $value,
);
$phpCode = '<?php return ' . Toolkit::compile($content) . ';';
if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
}
file_put_contents($file, $phpCode, LOCK_EX);
} | @param string $key
@param mixed $value
@param int $duration
@return void
@throws \x2ts\UncompilableException | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/cache/CCache.php#L62-L75 |
x2ts/x2ts | src/cache/CCache.php | CCache.remove | public function remove($key) {
X::logger()->trace("CCache remove $key");
$file = $this->key2file($key);
if (is_file($file)) {
unlink($file);
return true;
}
return false;
} | php | public function remove($key) {
X::logger()->trace("CCache remove $key");
$file = $this->key2file($key);
if (is_file($file)) {
unlink($file);
return true;
}
return false;
} | @param string $key
@return boolean | https://github.com/x2ts/x2ts/blob/65e43952ab940ab05696a34d31a1c3ab91545090/src/cache/CCache.php#L82-L90 |
chadicus/coding-standard | Chadicus/Sniffs/Commenting/ClassCommentSniff.php | Chadicus_Sniffs_Commenting_ClassCommentSniff.process | public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$find = PHP_CodeSniffer_Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true);
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT
) {
//Don't require the class doc block.
return;
}
// Try and determine if this is a file comment instead of a class comment.
// We assume that if this is the first comment after the open PHP tag, then
// it is most likely a file comment instead of a class comment.
if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
$start = ($tokens[$commentEnd]['comment_opener'] - 1);
} else {
$start = $phpcsFile->findPrevious(T_COMMENT, ($commentEnd - 1), null, true);
}
$prev = $phpcsFile->findPrevious(T_WHITESPACE, $start, null, true);
if ($tokens[$prev]['code'] === T_OPEN_TAG) {
$prevOpen = $phpcsFile->findPrevious(T_OPEN_TAG, ($prev - 1));
if ($prevOpen === false) {
// This is a comment directly after the first open tag,
// so probably a file comment.
$phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing');
return;
}
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle');
return;
}
if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) {
$error = 'There must be no blank lines after the class comment';
$phpcsFile->addError($error, $commentEnd, 'SpacingAfter');
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
if ($tokens[$prev]['line'] !== ($tokens[$commentStart]['line'] - 2)) {
$error = 'There must be exactly one blank line before the class comment';
$phpcsFile->addError($error, $commentStart, 'SpacingBefore');
}
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if (in_array($tokens[$tag]['content'], $this->disallowedTags)) {
$error = '%s tag is not allowed in class comment';
$data = array($tokens[$tag]['content']);
$phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data);
}
}
} | php | public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$find = PHP_CodeSniffer_Tokens::$methodPrefixes;
$find[] = T_WHITESPACE;
$commentEnd = $phpcsFile->findPrevious($find, ($stackPtr - 1), null, true);
if ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT
) {
//Don't require the class doc block.
return;
}
// Try and determine if this is a file comment instead of a class comment.
// We assume that if this is the first comment after the open PHP tag, then
// it is most likely a file comment instead of a class comment.
if ($tokens[$commentEnd]['code'] === T_DOC_COMMENT_CLOSE_TAG) {
$start = ($tokens[$commentEnd]['comment_opener'] - 1);
} else {
$start = $phpcsFile->findPrevious(T_COMMENT, ($commentEnd - 1), null, true);
}
$prev = $phpcsFile->findPrevious(T_WHITESPACE, $start, null, true);
if ($tokens[$prev]['code'] === T_OPEN_TAG) {
$prevOpen = $phpcsFile->findPrevious(T_OPEN_TAG, ($prev - 1));
if ($prevOpen === false) {
// This is a comment directly after the first open tag,
// so probably a file comment.
$phpcsFile->addError('Missing class doc comment', $stackPtr, 'Missing');
return;
}
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$phpcsFile->addError('You must use "/**" style comments for a class comment', $stackPtr, 'WrongStyle');
return;
}
if ($tokens[$commentEnd]['line'] !== ($tokens[$stackPtr]['line'] - 1)) {
$error = 'There must be no blank lines after the class comment';
$phpcsFile->addError($error, $commentEnd, 'SpacingAfter');
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
if ($tokens[$prev]['line'] !== ($tokens[$commentStart]['line'] - 2)) {
$error = 'There must be exactly one blank line before the class comment';
$phpcsFile->addError($error, $commentStart, 'SpacingBefore');
}
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if (in_array($tokens[$tag]['content'], $this->disallowedTags)) {
$error = '%s tag is not allowed in class comment';
$data = array($tokens[$tag]['content']);
$phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data);
}
}
} | Processes this test, when one of its tokens is encountered.
@param PHP_CodeSniffer_File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@return void | https://github.com/chadicus/coding-standard/blob/e877151eed0c300e4e33e00308470e3873aa04ea/Chadicus/Sniffs/Commenting/ClassCommentSniff.php#L38-L95 |
heliopsis/ezforms-bundle | Heliopsis/eZFormsBundle/Provider/Handler/ContentTypeIdentifierMap.php | ContentTypeIdentifierMap.getHandler | public function getHandler( Location $location )
{
$locationContentTypeId = $location->contentInfo->contentTypeId;
/** @var ContentType $locationContentType */
$locationContentType = $this->contentTypeService->loadContentType( $locationContentTypeId );
return array_key_exists( $locationContentType->identifier, $this->map ) ?
$this->map[$locationContentType->identifier] :
new NullHandler();
} | php | public function getHandler( Location $location )
{
$locationContentTypeId = $location->contentInfo->contentTypeId;
/** @var ContentType $locationContentType */
$locationContentType = $this->contentTypeService->loadContentType( $locationContentTypeId );
return array_key_exists( $locationContentType->identifier, $this->map ) ?
$this->map[$locationContentType->identifier] :
new NullHandler();
} | Returns form handler to use at $location
@param \eZ\Publish\API\Repository\Values\Content\Location $location
@return \Heliopsis\eZFormsBundle\FormHandler\FormHandlerInterface | https://github.com/heliopsis/ezforms-bundle/blob/ed87feeb76fcdcd4a4e355d4bc60b83077ba90b4/Heliopsis/eZFormsBundle/Provider/Handler/ContentTypeIdentifierMap.php#L57-L67 |
gordonbanderson/weboftalent-gridrows | code/GridRowsExtension.php | GridRowsExtension.SplitDataListIntoGridRows | public function SplitDataListIntoGridRows($itemsInGridMethod, $numberOfCols)
{
$methodFound = false;
$itemsInGrid = null;
// Check first the controller and then the model for the method to call
if ($this->owner->hasMethod($itemsInGridMethod)) {
$itemsInGrid = $this->owner->$itemsInGridMethod();
$methodFound = true;
}
if (!$methodFound && method_exists($this->owner->model, $itemsInGridMethod)) {
$itemsInGrid = $this->owner->model->$itemsInGridMethod();
$methodFound = true;
}
if ($itemsInGrid == null) {
$message = 'Method not found. A grid cannot be formed from the '
. 'method ' . $itemsInGridMethod;
throw new \InvalidArgumentException($message);
}
return $this->createGridLayout($itemsInGrid, $numberOfCols);
} | php | public function SplitDataListIntoGridRows($itemsInGridMethod, $numberOfCols)
{
$methodFound = false;
$itemsInGrid = null;
// Check first the controller and then the model for the method to call
if ($this->owner->hasMethod($itemsInGridMethod)) {
$itemsInGrid = $this->owner->$itemsInGridMethod();
$methodFound = true;
}
if (!$methodFound && method_exists($this->owner->model, $itemsInGridMethod)) {
$itemsInGrid = $this->owner->model->$itemsInGridMethod();
$methodFound = true;
}
if ($itemsInGrid == null) {
$message = 'Method not found. A grid cannot be formed from the '
. 'method ' . $itemsInGridMethod;
throw new \InvalidArgumentException($message);
}
return $this->createGridLayout($itemsInGrid, $numberOfCols);
} | /*
If you are laying out using some form of grid, e.g. HTML table (ugh) or
bootstraps span classes it is useful to have the DataList split by row.
Here the DataList is generated from a method accessible to the current
controller
See README.md for a worked example
Note, this method should have been called SplitDataListMethodIntoGridRows | https://github.com/gordonbanderson/weboftalent-gridrows/blob/27a5248afbe462114015089fb9cf09957b88387f/code/GridRowsExtension.php#L25-L48 |
gordonbanderson/weboftalent-gridrows | code/GridRowsExtension.php | GridRowsExtension.SplitClassNameDataListIntoGridRows | public function SplitClassNameDataListIntoGridRows(
$className,
$numberOfCols,
$limit = 10,
$sort = 'LastEdited DESC'
) {
$clazz = Injector::inst()->create($className);
$itemsInGrid = $clazz->get()->limit($limit)->sort($sort);
return $this->createGridLayout($itemsInGrid, $numberOfCols);
} | php | public function SplitClassNameDataListIntoGridRows(
$className,
$numberOfCols,
$limit = 10,
$sort = 'LastEdited DESC'
) {
$clazz = Injector::inst()->create($className);
$itemsInGrid = $clazz->get()->limit($limit)->sort($sort);
return $this->createGridLayout($itemsInGrid, $numberOfCols);
} | /*
If you are laying out using some form of grid, e.g. HTML table (ugh) or
bootstraps span classes it is useful to have the DataList split by row.
This is what this method does.
See USAGE.md for a worked example | https://github.com/gordonbanderson/weboftalent-gridrows/blob/27a5248afbe462114015089fb9cf09957b88387f/code/GridRowsExtension.php#L58-L67 |
gordonbanderson/weboftalent-gridrows | code/GridRowsExtension.php | GridRowsExtension.createGridLayout | public function createGridLayout($itemsInGrid, $numberOfCols)
{
$position = 1;
$columns = new ArrayList();
$result = new ArrayList();
foreach ($itemsInGrid as $key => $item) {
$columns->push($item);
if (($position) >= $numberOfCols) {
$position = 1;
$row = new ArrayList();
$row->Columns = $columns;
$result->push($row);
$columns = new ArrayList();
} else {
$position = $position + 1;
}
}
if ($columns->Count() > 0) {
$row = new ArrayList();
$row->Columns = $columns;
$result->push($row);
}
return $result;
} | php | public function createGridLayout($itemsInGrid, $numberOfCols)
{
$position = 1;
$columns = new ArrayList();
$result = new ArrayList();
foreach ($itemsInGrid as $key => $item) {
$columns->push($item);
if (($position) >= $numberOfCols) {
$position = 1;
$row = new ArrayList();
$row->Columns = $columns;
$result->push($row);
$columns = new ArrayList();
} else {
$position = $position + 1;
}
}
if ($columns->Count() > 0) {
$row = new ArrayList();
$row->Columns = $columns;
$result->push($row);
}
return $result;
} | /*
The actual method that splits the DataList into an ArrayList of rows that
contain an ArrayList of Columns | https://github.com/gordonbanderson/weboftalent-gridrows/blob/27a5248afbe462114015089fb9cf09957b88387f/code/GridRowsExtension.php#L73-L96 |
faganchalabizada/portmanat-laravel | src/PortmanatServiceProvider.php | PortmanatServiceProvider.boot | public function boot()
{
$this->loadRoutesFrom(__DIR__ . '/Routes/routes.php');
$this->publishes([
__DIR__ . '/Config/portmanat.php' => config_path('portmanat.php'),
]);
$this->publishes([
__DIR__ . '/Controller/PortmanatController.php' => app_path('Http/Controllers/PortmanatController.php'),
]);
} | php | public function boot()
{
$this->loadRoutesFrom(__DIR__ . '/Routes/routes.php');
$this->publishes([
__DIR__ . '/Config/portmanat.php' => config_path('portmanat.php'),
]);
$this->publishes([
__DIR__ . '/Controller/PortmanatController.php' => app_path('Http/Controllers/PortmanatController.php'),
]);
} | Bootstrap the application services.
@return void | https://github.com/faganchalabizada/portmanat-laravel/blob/7876fc4958508f719dd879299eabd02b8756791a/src/PortmanatServiceProvider.php#L14-L23 |
liufee/cms-core | backend/models/form/ResetPasswordForm.php | ResetPasswordForm.resetPassword | public function resetPassword()
{
$user = $this->_user;
$user->setPassword($this->password);
$user->removePasswordResetToken();
Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_UPDATE);
return $user->save(false);
} | php | public function resetPassword()
{
$user = $this->_user;
$user->setPassword($this->password);
$user->removePasswordResetToken();
Event::off(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_UPDATE);
return $user->save(false);
} | Resets password.
@return boolean if password was reset. | https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/models/form/ResetPasswordForm.php#L64-L72 |
schpill/thin | src/Env.php | Env.load | public static function load($path, $file = '.env')
{
if (!is_string($file)) {
$file = '.env';
}
$filePath = rtrim($path, '/') . '/' . $file;
if (!is_readable($filePath) || !is_file($filePath)) {
throw new \InvalidArgumentException(
sprintf(
"Dotenv: Environment file %s not found or not readable. " .
"Create file with your environment settings at %s",
$file,
$filePath
)
);
}
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
foreach ($lines as $line) {
// Disregard comments
if (strpos(trim($line), '#') === 0) {
continue;
}
// Only use non-empty lines that look like setters
if (strpos($line, '=') !== false) {
static::setEnvironmentVariable($line);
}
}
} | php | public static function load($path, $file = '.env')
{
if (!is_string($file)) {
$file = '.env';
}
$filePath = rtrim($path, '/') . '/' . $file;
if (!is_readable($filePath) || !is_file($filePath)) {
throw new \InvalidArgumentException(
sprintf(
"Dotenv: Environment file %s not found or not readable. " .
"Create file with your environment settings at %s",
$file,
$filePath
)
);
}
// Read file into an array of lines with auto-detected line endings
$autodetect = ini_get('auto_detect_line_endings');
ini_set('auto_detect_line_endings', '1');
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
ini_set('auto_detect_line_endings', $autodetect);
foreach ($lines as $line) {
// Disregard comments
if (strpos(trim($line), '#') === 0) {
continue;
}
// Only use non-empty lines that look like setters
if (strpos($line, '=') !== false) {
static::setEnvironmentVariable($line);
}
}
} | Load `.env` file in given directory | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Env.php#L15-L53 |
schpill/thin | src/Env.php | Env.setEnvironmentVariable | public static function setEnvironmentVariable($name, $value = null)
{
list($name, $value) = static::normaliseEnvironmentVariable($name, $value);
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if (true === static::$immutable && false === is_null(static::findEnvironmentVariable($name))) {
return;
}
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
} | php | public static function setEnvironmentVariable($name, $value = null)
{
list($name, $value) = static::normaliseEnvironmentVariable($name, $value);
// Don't overwrite existing environment variables if we're immutable
// Ruby's dotenv does this with `ENV[key] ||= value`.
if (true === static::$immutable && false === is_null(static::findEnvironmentVariable($name))) {
return;
}
putenv("$name=$value");
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
} | Set a variable using:
- putenv
- $_ENV
- $_SERVER
The environment variable value is stripped of single and double quotes.
@param $name
@param null $value | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Env.php#L66-L80 |
schpill/thin | src/Env.php | Env.required | public static function required($environmentVariables, array $allowedValues = array())
{
$environmentVariables = (array) $environmentVariables;
$missingEnvironmentVariables = [];
foreach ($environmentVariables as $environmentVariable) {
$value = static::findEnvironmentVariable($environmentVariable);
if (is_null($value)) {
$missingEnvironmentVariables[] = $environmentVariable;
} elseif ($allowedValues) {
if (!Arrays::in($value, $allowedValues)) {
// may differentiate in the future, but for now this does the job
$missingEnvironmentVariables[] = $environmentVariable;
}
}
}
if ($missingEnvironmentVariables) {
throw new \RuntimeException(
sprintf(
"Required environment variable missing, or value not allowed: '%s'",
implode("', '", $missingEnvironmentVariables)
)
);
}
return true;
} | php | public static function required($environmentVariables, array $allowedValues = array())
{
$environmentVariables = (array) $environmentVariables;
$missingEnvironmentVariables = [];
foreach ($environmentVariables as $environmentVariable) {
$value = static::findEnvironmentVariable($environmentVariable);
if (is_null($value)) {
$missingEnvironmentVariables[] = $environmentVariable;
} elseif ($allowedValues) {
if (!Arrays::in($value, $allowedValues)) {
// may differentiate in the future, but for now this does the job
$missingEnvironmentVariables[] = $environmentVariable;
}
}
}
if ($missingEnvironmentVariables) {
throw new \RuntimeException(
sprintf(
"Required environment variable missing, or value not allowed: '%s'",
implode("', '", $missingEnvironmentVariables)
)
);
}
return true;
} | Require specified ENV vars to be present, or throw Exception.
You can also pass through an set of allowed values for the environment variable.
@throws \RuntimeException
@param mixed $environmentVariables the name of the environment variable or an array of names
@param string[] $allowedValues
@return true (or throws exception on error) | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Env.php#L91-L119 |
schpill/thin | src/Env.php | Env.sanitiseVariableValue | protected static function sanitiseVariableValue($value)
{
$value = trim($value);
if (!$value) {
return '';
}
if (strpbrk($value[0], '"\'') !== false) { // value starts with a quote
$quote = $value[0];
$regexPattern = sprintf('/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx',
$quote
);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\$quote", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = $parts[0];
}
return trim($value);
} | php | protected static function sanitiseVariableValue($value)
{
$value = trim($value);
if (!$value) {
return '';
}
if (strpbrk($value[0], '"\'') !== false) { // value starts with a quote
$quote = $value[0];
$regexPattern = sprintf('/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx',
$quote
);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\$quote", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = $parts[0];
}
return trim($value);
} | Strips quotes from the environment variable value.
@param $value
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Env.php#L165-L200 |
schpill/thin | src/Env.php | Env.resolveNestedVariables | protected static function resolveNestedVariables($value)
{
if (strpos($value, '$') !== false) {
$value = preg_replace_callback(
'/{\$([a-zA-Z0-9_]+)}/',
function ($matchedPatterns) {
$nestedVariable = Dotenv::findEnvironmentVariable($matchedPatterns[1]);
if (is_null($nestedVariable)) {
return $matchedPatterns[0];
} else {
return $nestedVariable;
}
},
$value
);
}
return $value;
} | php | protected static function resolveNestedVariables($value)
{
if (strpos($value, '$') !== false) {
$value = preg_replace_callback(
'/{\$([a-zA-Z0-9_]+)}/',
function ($matchedPatterns) {
$nestedVariable = Dotenv::findEnvironmentVariable($matchedPatterns[1]);
if (is_null($nestedVariable)) {
return $matchedPatterns[0];
} else {
return $nestedVariable;
}
},
$value
);
}
return $value;
} | Look for {$varname} patterns in the variable value and replace with an existing
environment variable.
@param $value
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Env.php#L220-L238 |
daijulong/sms | src/Agents/Content.php | Content.send | public function send(string $to, Sms $sms, array $params = []): bool
{
$content = $sms->content($this->agent_name);
if (!$content) {
throw new SmsException('The agent : ' . $this->agent_name . ' not supported by SMS');
}
$full_content = $this->getFullContent($content, $params);
$this->result->setStatus(true)->setContent($full_content)->setParams($params);
return true;
} | php | public function send(string $to, Sms $sms, array $params = []): bool
{
$content = $sms->content($this->agent_name);
if (!$content) {
throw new SmsException('The agent : ' . $this->agent_name . ' not supported by SMS');
}
$full_content = $this->getFullContent($content, $params);
$this->result->setStatus(true)->setContent($full_content)->setParams($params);
return true;
} | 发送短信
@param string $to
@param Sms $sms
@param array $params
@return bool
@throws SmsException | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/Agents/Content.php#L29-L38 |
daijulong/sms | src/Agents/Content.php | Content.getFullContent | private function getFullContent(string $content, array $params = [])
{
return str_replace(array_map(function ($key) {
return '${' . $key . '}';
}, array_keys($params)), array_values($params), $content);
} | php | private function getFullContent(string $content, array $params = [])
{
return str_replace(array_map(function ($key) {
return '${' . $key . '}';
}, array_keys($params)), array_values($params), $content);
} | 取得完整短信内容
替换短信中的变量
@param string $content
@param array $params
@return string | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/Agents/Content.php#L49-L54 |
schpill/thin | src/Pluralizer.php | Pluralizer.singular | public function singular($value)
{
// First we'll check the cache of inflected values. We cache each word that
// is inflected so we don't have to spin through the regular expressions
// each time we need to inflect a given value for the developer.
if (isset($this->singular[$value])) {
return $this->singular[$value];
}
// English words may be automatically inflected using regular expressions.
// If the word is English, we'll just pass off the word to the automatic
// inflection method and return the result, which is cached.
$irregular = $this->config['irregular'];
$result = $this->auto($value, $this->config['singular'], $irregular);
return $this->singular[$value] = $result ?: $value;
} | php | public function singular($value)
{
// First we'll check the cache of inflected values. We cache each word that
// is inflected so we don't have to spin through the regular expressions
// each time we need to inflect a given value for the developer.
if (isset($this->singular[$value])) {
return $this->singular[$value];
}
// English words may be automatically inflected using regular expressions.
// If the word is English, we'll just pass off the word to the automatic
// inflection method and return the result, which is cached.
$irregular = $this->config['irregular'];
$result = $this->auto($value, $this->config['singular'], $irregular);
return $this->singular[$value] = $result ?: $value;
} | Get the singular form of the given word.
@param string $value
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Pluralizer.php#L42-L59 |
schpill/thin | src/Pluralizer.php | Pluralizer.plural | public function plural($value, $count = 2)
{
if ((int) $count == 1) return $value;
// First we'll check the cache of inflected values. We cache each word that
// is inflected so we don't have to spin through the regular expressions
// each time we need to inflect a given value for the developer.
if (isset($this->plural[$value])) {
return $this->plural[$value];
}
// English words may be automatically inflected using regular expressions.
// If the word is English, we'll just pass off the word to the automatic
// inflection method and return the result, which is cached.
$irregular = array_flip($this->config['irregular']);
$result = $this->auto($value, $this->config['plural'], $irregular);
return $this->plural[$value] = $result;
} | php | public function plural($value, $count = 2)
{
if ((int) $count == 1) return $value;
// First we'll check the cache of inflected values. We cache each word that
// is inflected so we don't have to spin through the regular expressions
// each time we need to inflect a given value for the developer.
if (isset($this->plural[$value])) {
return $this->plural[$value];
}
// English words may be automatically inflected using regular expressions.
// If the word is English, we'll just pass off the word to the automatic
// inflection method and return the result, which is cached.
$irregular = array_flip($this->config['irregular']);
$result = $this->auto($value, $this->config['plural'], $irregular);
return $this->plural[$value] = $result;
} | Get the plural form of the given word.
@param string $value
@param int $count
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Pluralizer.php#L68-L87 |
schpill/thin | src/Pluralizer.php | Pluralizer.auto | protected function auto($value, $source, $irregular)
{
// If the word hasn't been cached, we'll check the list of words that
// that are "uncountable". This should be a quick look up since we
// can just hit the array directly for the value.
if (Arrays::inArray(Inflector::lower($value), $this->config['uncountable'])) {
return $value;
}
// Next, we will check the "irregular" patterns, which contain words
// like "children" and "teeth" which can not be inflected using the
// typically used regular expression matching approach.
foreach ($irregular as $irregular => $pattern) {
if (preg_match($pattern = '/'.$pattern.'$/i', $value)) {
return preg_replace($pattern, $irregular, $value);
}
}
// Finally we'll spin through the array of regular expressions and
// and look for matches for the word. If we find a match we will
// cache and return the inflected value for quick look up.
foreach ($source as $pattern => $inflected) {
if (preg_match($pattern, $value)) {
return preg_replace($pattern, $inflected, $value);
}
}
} | php | protected function auto($value, $source, $irregular)
{
// If the word hasn't been cached, we'll check the list of words that
// that are "uncountable". This should be a quick look up since we
// can just hit the array directly for the value.
if (Arrays::inArray(Inflector::lower($value), $this->config['uncountable'])) {
return $value;
}
// Next, we will check the "irregular" patterns, which contain words
// like "children" and "teeth" which can not be inflected using the
// typically used regular expression matching approach.
foreach ($irregular as $irregular => $pattern) {
if (preg_match($pattern = '/'.$pattern.'$/i', $value)) {
return preg_replace($pattern, $irregular, $value);
}
}
// Finally we'll spin through the array of regular expressions and
// and look for matches for the word. If we find a match we will
// cache and return the inflected value for quick look up.
foreach ($source as $pattern => $inflected) {
if (preg_match($pattern, $value)) {
return preg_replace($pattern, $inflected, $value);
}
}
} | Perform auto inflection on an English word.
@param string $value
@param array $source
@param array $irregular
@return string | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Pluralizer.php#L97-L123 |
ScreamingDev/phpsemver | lib/PHPSemVer/Trigger/Functions/BodyChanged.php | BodyChanged.handle | public function handle($old, $new)
{
if ( ! $this->canHandle($old) || ! $this->canHandle($new)) {
return null;
}
if ($this->equals($old, $new)) {
return false;
}
$this->lastException = new FailedConstraint(
sprintf(
'%s() body changed',
$new->name
)
);
return true;
} | php | public function handle($old, $new)
{
if ( ! $this->canHandle($old) || ! $this->canHandle($new)) {
return null;
}
if ($this->equals($old, $new)) {
return false;
}
$this->lastException = new FailedConstraint(
sprintf(
'%s() body changed',
$new->name
)
);
return true;
} | Check if body of function has changed.
@param Function_ $old
@param Function_ $new
@return bool | https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Trigger/Functions/BodyChanged.php#L51-L69 |
ScreamingDev/phpsemver | lib/PHPSemVer/Trigger/Functions/BodyChanged.php | BodyChanged.equals | protected function equals($old, $new)
{
if (is_array($old)) {
// compare arrays
if (array_keys($old) != array_keys($new)) {
return false;
}
foreach (array_keys($old) as $key) {
if ( ! $this->equals($old[$key], $new[$key])) {
return false;
}
}
return true;
}
if ( ! is_object($old) ) {
// compare non-array scalars
return ($old == $new);
}
if (get_class($old) != get_class($new)) {
// compare object by class name
return false;
}
// compare each sub-node
foreach ($old->getSubNodeNames() as $property) {
if ( ! $this->equals($old->$property, $new->$property)) {
return false;
}
}
return true;
} | php | protected function equals($old, $new)
{
if (is_array($old)) {
// compare arrays
if (array_keys($old) != array_keys($new)) {
return false;
}
foreach (array_keys($old) as $key) {
if ( ! $this->equals($old[$key], $new[$key])) {
return false;
}
}
return true;
}
if ( ! is_object($old) ) {
// compare non-array scalars
return ($old == $new);
}
if (get_class($old) != get_class($new)) {
// compare object by class name
return false;
}
// compare each sub-node
foreach ($old->getSubNodeNames() as $property) {
if ( ! $this->equals($old->$property, $new->$property)) {
return false;
}
}
return true;
} | Check if two Node trees are equal.
@param Node $old
@param Node $new
@return bool | https://github.com/ScreamingDev/phpsemver/blob/11a4bc508f71dee73d4f5fee2e9d39e7984d3e15/lib/PHPSemVer/Trigger/Functions/BodyChanged.php#L84-L119 |
zhengb302/LumengPHP | src/LumengPHP/Kernel/Event/EventManager.php | EventManager.executeListeners | private function executeListeners($eventName) {
$listeners = $this->eventConfig[$eventName];
foreach ($listeners as $listener) {
$return = $this->classInvoker->invoke($listener);
//如果某个事件监听器返回“false”,则停止事件的传播
if ($return === false) {
break;
}
}
} | php | private function executeListeners($eventName) {
$listeners = $this->eventConfig[$eventName];
foreach ($listeners as $listener) {
$return = $this->classInvoker->invoke($listener);
//如果某个事件监听器返回“false”,则停止事件的传播
if ($return === false) {
break;
}
}
} | (逐个)执行事件的监听器
@param string $eventName 事件名称 | https://github.com/zhengb302/LumengPHP/blob/77f41c32a5c6ba71c65956e5c4650707b6168c41/src/LumengPHP/Kernel/Event/EventManager.php#L96-L106 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomLog.php | PHPHtmlDomLog.logError | final public function logError($msg_code,$data = array())
{
self::write(self::compileMessage(self::$error_msg[$msg_code],$data), PEL_ERROR);
} | php | final public function logError($msg_code,$data = array())
{
self::write(self::compileMessage(self::$error_msg[$msg_code],$data), PEL_ERROR);
} | Metodo que permite escribir un log de Error.
@param string $msg_code Cadena de texto con el codigo del mensaje de error.
@param array $data arreglo con los parametros necesarios para escribir el log.
@return void | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomLog.php#L43-L46 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomLog.php | PHPHtmlDomLog.logWarn | final public function logWarn($msg_code,$data = array())
{
self::write(self::compileMessage(self::$warn_msg[$msg_code],$data), PEL_WARNING);
} | php | final public function logWarn($msg_code,$data = array())
{
self::write(self::compileMessage(self::$warn_msg[$msg_code],$data), PEL_WARNING);
} | Metodo que permite escribir un log de Advertencia.
@param string $msg_code Cadena de texto con el codigo del mensaje de advertencia.
@param array $data arreglo con los parametros necesarios para escribir el log.
@return void | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomLog.php#L54-L57 |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomLog.php | PHPHtmlDomLog.logInfo | final public function logInfo($msg_code,$data = array())
{
self::write(self::compileMessage(self::$info_msg[$msg_code],$data), PEL_INFO);
} | php | final public function logInfo($msg_code,$data = array())
{
self::write(self::compileMessage(self::$info_msg[$msg_code],$data), PEL_INFO);
} | Metodo que permite escribir un log de Información.
@param string $msg_code Cadena de texto con el codigo del mensaje de información.
@param array $data arreglo con los parametros necesarios para escribir el log.
@return void | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomLog.php#L65-L68 |
andyburton/Sonic-Framework | src/Resource/User.php | User.Create | public function Create ($exclude = array (), &$db = FALSE)
{
// Check email is unique
if (!$this->uniqueEmail ())
{
// Set message
new \Sonic\Message ('error', 'The email address `' . $this->iget ('email') . '` is already assigned to an account! Please choose another.');
// Return FALSE
return FALSE;
}
// Hash password
$password = $this->iget ('password');
$this->iset ('password', self::_Hash ($password));
// Call parent method
$parent = parent::Create ($exclude, $db);
// Reset password
$this->iset ('password', $password);
// Return
return $parent;
} | php | public function Create ($exclude = array (), &$db = FALSE)
{
// Check email is unique
if (!$this->uniqueEmail ())
{
// Set message
new \Sonic\Message ('error', 'The email address `' . $this->iget ('email') . '` is already assigned to an account! Please choose another.');
// Return FALSE
return FALSE;
}
// Hash password
$password = $this->iget ('password');
$this->iset ('password', self::_Hash ($password));
// Call parent method
$parent = parent::Create ($exclude, $db);
// Reset password
$this->iset ('password', $password);
// Return
return $parent;
} | Create a new user
@param array $exclude Attributes not to set
@param \PDO $db Database connection to use, default to master resource
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L105-L140 |
andyburton/Sonic-Framework | src/Resource/User.php | User.Update | public function Update ($exclude = array (), &$db = FALSE)
{
// Check email is unique
if (!$this->uniqueEmail ())
{
// Set message
new \Sonic\Message ('error', 'The email address `' . $this->iget ('email') . '` is already assigned to an account! Please choose another.');
// Return FALSE
return FALSE;
}
// Hash password
$password = $this->iget ('password');
// If password is not in exclude array
if (!in_array ('password', $exclude))
{
// If no password is set
if (!$this->attributeHasValue ('password'))
{
// Get the existing password hash
$this->readAttribute ('password');
}
// Else password is set
else
{
// Hash password
$this->iset ('password', self::_Hash ($password));
}
}
// Call parent method
$parent = parent::Update ($exclude, $db);
// Reset password
$this->iset ('password', $password);
// Return
return $parent;
} | php | public function Update ($exclude = array (), &$db = FALSE)
{
// Check email is unique
if (!$this->uniqueEmail ())
{
// Set message
new \Sonic\Message ('error', 'The email address `' . $this->iget ('email') . '` is already assigned to an account! Please choose another.');
// Return FALSE
return FALSE;
}
// Hash password
$password = $this->iget ('password');
// If password is not in exclude array
if (!in_array ('password', $exclude))
{
// If no password is set
if (!$this->attributeHasValue ('password'))
{
// Get the existing password hash
$this->readAttribute ('password');
}
// Else password is set
else
{
// Hash password
$this->iset ('password', self::_Hash ($password));
}
}
// Call parent method
$parent = parent::Update ($exclude, $db);
// Reset password
$this->iset ('password', $password);
// Return
return $parent;
} | Update a user
@param array $exclude Attributes not to update
@param \PDO $db Database connection to use, default to master resource
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L150-L213 |
andyburton/Sonic-Framework | src/Resource/User.php | User.Delete | public function Delete ($params = FALSE, &$db = FALSE)
{
// Get database master for write
if ($db === FALSE)
{
$db =& $this->getDbMaster ();
}
// Get objects
$objs = is_array ($params)? self::_getObjects ($params, $db) : [self::_read ($params, $db)];
// Remove each
$db->beginTransaction ();
foreach ($objs as $obj)
{
if (!$obj->Remove ())
{
$db->rollBack ();
return FALSE;
}
}
$db->commit ();
return TRUE;
} | php | public function Delete ($params = FALSE, &$db = FALSE)
{
// Get database master for write
if ($db === FALSE)
{
$db =& $this->getDbMaster ();
}
// Get objects
$objs = is_array ($params)? self::_getObjects ($params, $db) : [self::_read ($params, $db)];
// Remove each
$db->beginTransaction ();
foreach ($objs as $obj)
{
if (!$obj->Remove ())
{
$db->rollBack ();
return FALSE;
}
}
$db->commit ();
return TRUE;
} | Delete an object in the database
@param array|integer $params Primary key value or parameter array
@param \PDO $db Database connection to use, default to master resource
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L223-L253 |
andyburton/Sonic-Framework | src/Resource/User.php | User.session | public function session ()
{
if (!($this->session instanceof Session))
{
$this->session = Session::singleton ($this->sessionID);
}
return $this->session;
} | php | public function session ()
{
if (!($this->session instanceof Session))
{
$this->session = Session::singleton ($this->sessionID);
}
return $this->session;
} | Return user session
@return \Sonic\Resource\Session | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L295-L305 |
andyburton/Sonic-Framework | src/Resource/User.php | User.getSessionData | public function getSessionData ()
{
if (!$this->_sessionData)
{
$this->_sessionData = unserialize ($this->session ()->get (get_called_class ()));
}
return $this->_sessionData;
} | php | public function getSessionData ()
{
if (!$this->_sessionData)
{
$this->_sessionData = unserialize ($this->session ()->get (get_called_class ()));
}
return $this->_sessionData;
} | Set user data from a session
@return array | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L312-L322 |
andyburton/Sonic-Framework | src/Resource/User.php | User.fromSessionData | public function fromSessionData ()
{
$arr = $this->getSessionData ();
if (isset ($arr['id']))
{
$this->iset ('id', $arr['id']);
}
$this->fromArray ($arr, FALSE, FALSE);
$this->loginTimestamp = !Parser::_ak ($arr, 'login_timestamp', FALSE);
$this->lastAction = !Parser::_ak ($arr, 'last_action', FALSE);
} | php | public function fromSessionData ()
{
$arr = $this->getSessionData ();
if (isset ($arr['id']))
{
$this->iset ('id', $arr['id']);
}
$this->fromArray ($arr, FALSE, FALSE);
$this->loginTimestamp = !Parser::_ak ($arr, 'login_timestamp', FALSE);
$this->lastAction = !Parser::_ak ($arr, 'last_action', FALSE);
} | Set user data from a session
@return void | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L330-L345 |
andyburton/Sonic-Framework | src/Resource/User.php | User.setSessionData | public function setSessionData ()
{
$arr = $this->toArray ();
$arr['login_timestamp'] = $this->loginTimestamp;
$arr['last_action'] = $this->lastAction;
$this->session ()->set (get_called_class (), serialize ($arr));
} | php | public function setSessionData ()
{
$arr = $this->toArray ();
$arr['login_timestamp'] = $this->loginTimestamp;
$arr['last_action'] = $this->lastAction;
$this->session ()->set (get_called_class (), serialize ($arr));
} | Set user data in a session
@return void | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L353-L363 |
andyburton/Sonic-Framework | src/Resource/User.php | User.updateLastAction | public function updateLastAction ()
{
$arr = $this->getSessionData ();
$this->lastAction = time ();
$arr['last_action'] = $this->lastAction;
$this->session ()->set (get_called_class (), serialize ($arr));
} | php | public function updateLastAction ()
{
$arr = $this->getSessionData ();
$this->lastAction = time ();
$arr['last_action'] = $this->lastAction;
$this->session ()->set (get_called_class (), serialize ($arr));
} | Update the last action time to the current time
@return void | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L371-L381 |
andyburton/Sonic-Framework | src/Resource/User.php | User.initSession | public function initSession ()
{
// Get session
$session = $this->getSessionData ();
// Check session is valid
if ($this->checkSession ($session) !== TRUE)
{
return $this->Logout ('invalid_session');
}
// Load user from session
$this->fromSessionData ();
// Read user
if (!$this->Read ())
{
return $this->Logout ('user_read_error');
}
// Reset password
$this->reset ('password');
// If the user is not active or the active status has changed
if ($session['active'] != $this->iget ('active') || !$this->iget ('active'))
{
return $this->Logout ('inactive');
}
// Check if the session has timed out
if ($this->session ()->timedOut ($session['last_action']))
{
return $this->Logout ('timeout');
}
// Update action time
$this->updateLastAction ();
// Set login status
$this->loggedIn = TRUE;
// Redirect to originally requested URL
if ($this->session ()->get ('requested_url'))
{
$url = $this->session ()->get ('requested_url');
$this->session ()->set ('requested_url', FALSE);
new Redirect ($url);
}
// return TRUE
return TRUE;
} | php | public function initSession ()
{
// Get session
$session = $this->getSessionData ();
// Check session is valid
if ($this->checkSession ($session) !== TRUE)
{
return $this->Logout ('invalid_session');
}
// Load user from session
$this->fromSessionData ();
// Read user
if (!$this->Read ())
{
return $this->Logout ('user_read_error');
}
// Reset password
$this->reset ('password');
// If the user is not active or the active status has changed
if ($session['active'] != $this->iget ('active') || !$this->iget ('active'))
{
return $this->Logout ('inactive');
}
// Check if the session has timed out
if ($this->session ()->timedOut ($session['last_action']))
{
return $this->Logout ('timeout');
}
// Update action time
$this->updateLastAction ();
// Set login status
$this->loggedIn = TRUE;
// Redirect to originally requested URL
if ($this->session ()->get ('requested_url'))
{
$url = $this->session ()->get ('requested_url');
$this->session ()->set ('requested_url', FALSE);
new Redirect ($url);
}
// return TRUE
return TRUE;
} | Initialise a user session and check it is valid
@return string|boolean Error | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L389-L453 |
andyburton/Sonic-Framework | src/Resource/User.php | User.validSession | public function validSession ()
{
// Get session
$session = $this->getSessionData ();
// Check session is valid
if ($this->checkSession ($session) !== TRUE)
{
$this->loggedIn = FALSE;
return FALSE;
}
// If the user is not active or the active status has changed
if ($session['active'] !== $this->iget ('active') || !$this->iget ('active'))
{
$this->loggedIn = FALSE;
return FALSE;
}
// Check if the session has timed out
if ($this->session ()->timedOut ($session['last_action']))
{
$this->loggedIn = FALSE;
return FALSE;
}
// Set login status
$this->loggedIn = TRUE;
// Return TRUE
return TRUE;
} | php | public function validSession ()
{
// Get session
$session = $this->getSessionData ();
// Check session is valid
if ($this->checkSession ($session) !== TRUE)
{
$this->loggedIn = FALSE;
return FALSE;
}
// If the user is not active or the active status has changed
if ($session['active'] !== $this->iget ('active') || !$this->iget ('active'))
{
$this->loggedIn = FALSE;
return FALSE;
}
// Check if the session has timed out
if ($this->session ()->timedOut ($session['last_action']))
{
$this->loggedIn = FALSE;
return FALSE;
}
// Set login status
$this->loggedIn = TRUE;
// Return TRUE
return TRUE;
} | Whether the user has a valid session
@return boolean | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L461-L500 |
andyburton/Sonic-Framework | src/Resource/User.php | User.checkSession | public function checkSession ($session = FALSE)
{
// If there is no session, get it
if ($session === FALSE)
{
$session = $this->getSessionData ();
}
// No id
if (!Parser::_ak ($session, 'id', FALSE))
{
return 'no_id';
}
// No email
if (!Parser::_ak ($session, 'email', FALSE))
{
return 'no_email';
}
// No login timestamp
if (!Parser::_ak ($session, 'login_timestamp', FALSE))
{
return 'no_login_timestamp';
}
// No last action
if (!Parser::_ak ($session, 'last_action', FALSE))
{
return 'no_last_action';
}
// No active status
if (!Parser::_ak ($session, 'active', FALSE))
{
return 'no_active';
}
// return TRUE
return TRUE;
} | php | public function checkSession ($session = FALSE)
{
// If there is no session, get it
if ($session === FALSE)
{
$session = $this->getSessionData ();
}
// No id
if (!Parser::_ak ($session, 'id', FALSE))
{
return 'no_id';
}
// No email
if (!Parser::_ak ($session, 'email', FALSE))
{
return 'no_email';
}
// No login timestamp
if (!Parser::_ak ($session, 'login_timestamp', FALSE))
{
return 'no_login_timestamp';
}
// No last action
if (!Parser::_ak ($session, 'last_action', FALSE))
{
return 'no_last_action';
}
// No active status
if (!Parser::_ak ($session, 'active', FALSE))
{
return 'no_active';
}
// return TRUE
return TRUE;
} | Check that a session is valid
@param array $session Session data to check
@return string|boolean Error | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L509-L558 |
andyburton/Sonic-Framework | src/Resource/User.php | User.Logout | public function Logout ($reason = FALSE)
{
// Set login status
$this->loggedIn = FALSE;
// Destroy session
$this->session ()->Destroy ();
// Remove session data
$this->_sessionData = FALSE;
// Create a new session
$this->session ()->Create ();
$this->session ()->Refresh ();
// Store requested URL if there is a reason we're logging out
// If no reason then just a logout request, so we dont want to store
// it else we'll create a loop should they try to log back in.
if ($reason !== FALSE)
{
$this->session ()->set ('requested_url', $_SERVER['REQUEST_URI']);
}
// Return
return $reason;
} | php | public function Logout ($reason = FALSE)
{
// Set login status
$this->loggedIn = FALSE;
// Destroy session
$this->session ()->Destroy ();
// Remove session data
$this->_sessionData = FALSE;
// Create a new session
$this->session ()->Create ();
$this->session ()->Refresh ();
// Store requested URL if there is a reason we're logging out
// If no reason then just a logout request, so we dont want to store
// it else we'll create a loop should they try to log back in.
if ($reason !== FALSE)
{
$this->session ()->set ('requested_url', $_SERVER['REQUEST_URI']);
}
// Return
return $reason;
} | Logout the user
return string Reason | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Resource/User.php#L577-L610 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.