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/Injection/Manager.php | InstanceManager.setConfig | public function setConfig($aliasOrClass, array $configuration, $append = false)
{
$key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass;
if (!isset($this->configurations[$key]) || !$append) {
$this->configurations[$key] = $this->configurationTemplate;
}
// Ignore anything but 'parameters' and 'injections'
$configuration = [
'parameters' => isset($configuration['parameters']) ? $configuration['parameters'] : [],
'injections' => isset($configuration['injections']) ? $configuration['injections'] : [],
'shared' => isset($configuration['shared']) ? $configuration['shared'] : true
];
$this->configurations[$key] = array_replace_recursive($this->configurations[$key], $configuration);
} | php | public function setConfig($aliasOrClass, array $configuration, $append = false)
{
$key = ($this->hasAlias($aliasOrClass)) ? 'alias:' . $this->getBaseAlias($aliasOrClass) : $aliasOrClass;
if (!isset($this->configurations[$key]) || !$append) {
$this->configurations[$key] = $this->configurationTemplate;
}
// Ignore anything but 'parameters' and 'injections'
$configuration = [
'parameters' => isset($configuration['parameters']) ? $configuration['parameters'] : [],
'injections' => isset($configuration['injections']) ? $configuration['injections'] : [],
'shared' => isset($configuration['shared']) ? $configuration['shared'] : true
];
$this->configurations[$key] = array_replace_recursive($this->configurations[$key], $configuration);
} | Sets configuration for a single alias/class
@param string $aliasOrClass
@param array $configuration
@param bool $append | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L301-L316 |
schpill/thin | src/Injection/Manager.php | InstanceManager.getClasses | public function getClasses()
{
$classes = [];
foreach ($this->configurations as $name => $data) {
if (strpos($name, 'alias') === 0) {
continue;
}
$classes[] = $name;
}
return $classes;
} | php | public function getClasses()
{
$classes = [];
foreach ($this->configurations as $name => $data) {
if (strpos($name, 'alias') === 0) {
continue;
}
$classes[] = $name;
}
return $classes;
} | Get classes
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L323-L336 |
schpill/thin | src/Injection/Manager.php | InstanceManager.hasTypePreferences | public function hasTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
return (isset($this->typePreferences[$key]) && $this->typePreferences[$key]);
} | php | public function hasTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
return (isset($this->typePreferences[$key]) && $this->typePreferences[$key]);
} | Check for type preferences
@param string $interfaceOrAbstract
@return bool | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L397-L402 |
schpill/thin | src/Injection/Manager.php | InstanceManager.setTypePreference | public function setTypePreference($interfaceOrAbstract, array $preferredImplementations)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
foreach ($preferredImplementations as $preferredImplementation) {
$this->addTypePreference($key, $preferredImplementation);
}
return $this;
} | php | public function setTypePreference($interfaceOrAbstract, array $preferredImplementations)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
foreach ($preferredImplementations as $preferredImplementation) {
$this->addTypePreference($key, $preferredImplementation);
}
return $this;
} | Set type preference
@param string $interfaceOrAbstract
@param array $preferredImplementations
@return InstanceManager | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L411-L420 |
schpill/thin | src/Injection/Manager.php | InstanceManager.getTypePreferences | public function getTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (isset($this->typePreferences[$key])) {
return $this->typePreferences[$key];
}
return [];
} | php | public function getTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (isset($this->typePreferences[$key])) {
return $this->typePreferences[$key];
}
return [];
} | Get type preferences
@param string $interfaceOrAbstract
@return array | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L428-L437 |
schpill/thin | src/Injection/Manager.php | InstanceManager.unsetTypePreferences | public function unsetTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
unset($this->typePreferences[$key]);
} | php | public function unsetTypePreferences($interfaceOrAbstract)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
unset($this->typePreferences[$key]);
} | Unset type preferences
@param string $interfaceOrAbstract
@return void | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L445-L450 |
schpill/thin | src/Injection/Manager.php | InstanceManager.addTypePreference | public function addTypePreference($interfaceOrAbstract, $preferredImplementation)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (!isset($this->typePreferences[$key])) {
$this->typePreferences[$key] = [];
}
$this->typePreferences[$key][] = $preferredImplementation;
return $this;
} | php | public function addTypePreference($interfaceOrAbstract, $preferredImplementation)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (!isset($this->typePreferences[$key])) {
$this->typePreferences[$key] = [];
}
$this->typePreferences[$key][] = $preferredImplementation;
return $this;
} | Adds a type preference. A type preference is a redirection to a preferred alias or type when an abstract type
$interfaceOrAbstract is requested
@param string $interfaceOrAbstract
@param string $preferredImplementation
@return self | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L460-L471 |
schpill/thin | src/Injection/Manager.php | InstanceManager.removeTypePreference | public function removeTypePreference($interfaceOrAbstract, $preferredType)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (!isset($this->typePreferences[$key]) || !Arrays::in($preferredType, $this->typePreferences[$key])) {
return false;
}
unset($this->typePreferences[$key][array_search($key, $this->typePreferences)]);
return $this;
} | php | public function removeTypePreference($interfaceOrAbstract, $preferredType)
{
$key = ($this->hasAlias($interfaceOrAbstract)) ? 'alias:' . $interfaceOrAbstract : $interfaceOrAbstract;
if (!isset($this->typePreferences[$key]) || !Arrays::in($preferredType, $this->typePreferences[$key])) {
return false;
}
unset($this->typePreferences[$key][array_search($key, $this->typePreferences)]);
return $this;
} | Removes a previously set type preference
@param string $interfaceOrAbstract
@param string $preferredType
@return bool|self | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Injection/Manager.php#L480-L491 |
jasny/entity | src/EventListener/ToAssocRecursive.php | ToAssocRecursive.toAssocEntity | protected function toAssocEntity(Entity $entity, SplObjectStorage $list): array
{
$list[$entity] = null;
$assoc = $this->toAssocRecursive($entity->toAssoc(), $list);
$list[$entity] = $assoc;
return $assoc;
} | php | protected function toAssocEntity(Entity $entity, SplObjectStorage $list): array
{
$list[$entity] = null;
$assoc = $this->toAssocRecursive($entity->toAssoc(), $list);
$list[$entity] = $assoc;
return $assoc;
} | Cast the entity to an associative array.
@param Entity $entity
@param SplObjectStorage $list Entity / assoc map for entities that already have been converted
@return array | https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/EventListener/ToAssocRecursive.php#L45-L53 |
jasny/entity | src/EventListener/ToAssocRecursive.php | ToAssocRecursive.toAssocRecursive | protected function toAssocRecursive($input, SplObjectStorage $list): array
{
$values = is_iterable($input)
? i\iterable_to_array($input)
: object_get_properties($input, $input instanceof stdClass || $input instanceof DynamicEntity);
foreach ($values as $key => &$value) {
if ($value instanceof Entity) {
$value = $list->contains($value) ? $list[$value] : $this->toAssocEntity($value, $list);
if ($value === null && !is_int($key)) {
unset($values[$key]);
}
} elseif (is_iterable($value) || $value instanceof stdClass) {
$value = $this->toAssocRecursive($value, $list);
}
}
return $values;
} | php | protected function toAssocRecursive($input, SplObjectStorage $list): array
{
$values = is_iterable($input)
? i\iterable_to_array($input)
: object_get_properties($input, $input instanceof stdClass || $input instanceof DynamicEntity);
foreach ($values as $key => &$value) {
if ($value instanceof Entity) {
$value = $list->contains($value) ? $list[$value] : $this->toAssocEntity($value, $list);
if ($value === null && !is_int($key)) {
unset($values[$key]);
}
} elseif (is_iterable($value) || $value instanceof stdClass) {
$value = $this->toAssocRecursive($value, $list);
}
}
return $values;
} | Recursively cast to associative arrays.
@param iterable|object $input
@param SplObjectStorage $list Entity / assoc map for entities that already have been converted
@return array | https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/EventListener/ToAssocRecursive.php#L62-L81 |
MovingImage24/VM6ApiClient | lib/Entity/Video.php | Video.getStills | public function getStills()
{
if (!isset($this->stills)) {
$this->stills = [
new Still($this->thumbnail_url, 'default'),
new Still($this->thumbnail_url_lq, 'lq'),
new Still($this->thumbnail_url_mq, 'mq'),
];
}
return $this->stills;
} | php | public function getStills()
{
if (!isset($this->stills)) {
$this->stills = [
new Still($this->thumbnail_url, 'default'),
new Still($this->thumbnail_url_lq, 'lq'),
new Still($this->thumbnail_url_mq, 'mq'),
];
}
return $this->stills;
} | Generate a list of Still entities based on
other properties that come from VM 6.
@return Still[] | https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/Entity/Video.php#L267-L278 |
MovingImage24/VM6ApiClient | lib/Entity/Video.php | Video.getKeywords | public function getKeywords()
{
if (!isset($this->keywordObjs)) {
$this->keywordObjs = [];
$keywords = explode(',', $this->keywords);
foreach ($keywords as $keyword) {
$this->keywordObjs[] = new Keyword($keyword);
}
}
return $this->keywordObjs;
} | php | public function getKeywords()
{
if (!isset($this->keywordObjs)) {
$this->keywordObjs = [];
$keywords = explode(',', $this->keywords);
foreach ($keywords as $keyword) {
$this->keywordObjs[] = new Keyword($keyword);
}
}
return $this->keywordObjs;
} | {@inheritdoc} | https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/Entity/Video.php#L315-L327 |
MovingImage24/VM6ApiClient | lib/Entity/Video.php | Video.getCustomMetadata | public function getCustomMetadata()
{
if (!isset($this->customMetaDatas)) {
$this->customMetaDatas = [
new CustomMetaData('custom_data_field_1', $this->custom_data_field_1),
new CustomMetaData('custom_data_field_2', $this->custom_data_field_2),
new CustomMetaData('custom_data_field_3', $this->custom_data_field_3),
new CustomMetaData('custom_data_field_4', $this->custom_data_field_4),
new CustomMetaData('custom_data_field_5', $this->custom_data_field_5),
new CustomMetaData('custom_data_field_6', $this->custom_data_field_6),
new CustomMetaData('custom_data_field_7', $this->custom_data_field_7),
new CustomMetaData('custom_data_field_8', $this->custom_data_field_8),
new CustomMetaData('custom_data_field_9', $this->custom_data_field_9),
new CustomMetaData('custom_data_field_10', $this->custom_data_field_10),
];
}
return $this->customMetaDatas;
} | php | public function getCustomMetadata()
{
if (!isset($this->customMetaDatas)) {
$this->customMetaDatas = [
new CustomMetaData('custom_data_field_1', $this->custom_data_field_1),
new CustomMetaData('custom_data_field_2', $this->custom_data_field_2),
new CustomMetaData('custom_data_field_3', $this->custom_data_field_3),
new CustomMetaData('custom_data_field_4', $this->custom_data_field_4),
new CustomMetaData('custom_data_field_5', $this->custom_data_field_5),
new CustomMetaData('custom_data_field_6', $this->custom_data_field_6),
new CustomMetaData('custom_data_field_7', $this->custom_data_field_7),
new CustomMetaData('custom_data_field_8', $this->custom_data_field_8),
new CustomMetaData('custom_data_field_9', $this->custom_data_field_9),
new CustomMetaData('custom_data_field_10', $this->custom_data_field_10),
];
}
return $this->customMetaDatas;
} | {@inheritdoc} | https://github.com/MovingImage24/VM6ApiClient/blob/84e6510fa0fb71cfbb42ea9f23775f681c266fac/lib/Entity/Video.php#L332-L350 |
PhoxPHP/Glider | src/Connection/ConnectionManager.php | ConnectionManager.getAlternativeId | public function getAlternativeId(String $id)
{
// If no id is provided, we will try to reconnect with the default
// connection id.
if (empty($id)) {
$id = ConnectionManager::DEFAULT_CONNECTION_ID;
}
if (!in_array($id, array_keys($this->loadedConnections)) && $id !== ConnectionManager::USE_ALT_KEY) {
throw new RuntimeException('Cannot initialize a reconnection.');
}
$loaded = $this->loadedConnections;
$nextKey = ConnectionManager::USE_ALT_KEY;
$failedId = $this->getConnectionId();
if (isset($loaded[$failedId]['alt']) && isset($loaded[$loaded[$failedId]['alt']])) {
return [$loaded[$failedId]['alt'] => $loaded[$loaded[$failedId]['alt']]];
}
return null;
} | php | public function getAlternativeId(String $id)
{
// If no id is provided, we will try to reconnect with the default
// connection id.
if (empty($id)) {
$id = ConnectionManager::DEFAULT_CONNECTION_ID;
}
if (!in_array($id, array_keys($this->loadedConnections)) && $id !== ConnectionManager::USE_ALT_KEY) {
throw new RuntimeException('Cannot initialize a reconnection.');
}
$loaded = $this->loadedConnections;
$nextKey = ConnectionManager::USE_ALT_KEY;
$failedId = $this->getConnectionId();
if (isset($loaded[$failedId]['alt']) && isset($loaded[$loaded[$failedId]['alt']])) {
return [$loaded[$failedId]['alt'] => $loaded[$loaded[$failedId]['alt']]];
}
return null;
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/ConnectionManager.php#L148-L169 |
PhoxPHP/Glider | src/Connection/ConnectionManager.php | ConnectionManager.configure | public static function configure(String $id, Closure $settings)
{
$configInstance = new Configurator($id);
self::instance()->loader->callClassMethod($configInstance, 'attachConfiguration', $settings);
} | php | public static function configure(String $id, Closure $settings)
{
$configInstance = new Configurator($id);
self::instance()->loader->callClassMethod($configInstance, 'attachConfiguration', $settings);
} | {@inheritDoc} | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/ConnectionManager.php#L199-L203 |
PhoxPHP/Glider | src/Connection/ConnectionManager.php | ConnectionManager.get | private function get(String $id)
{
if (!$id) {
$id = ConnectionManager::DEFAULT_CONNECTION_ID;
}
if (count($this->loadedConnections) < 1) {
return false;
}
if (isset($this->loadedConnections[$id])) {
$this->configuredConnectionId = $id;
$this->platformConnector = [$id => $this->loadedConnections[$id]];
$connector = new PlatformResolver($this);
return $connector->resolvePlatform(new EventManager());
}
} | php | private function get(String $id)
{
if (!$id) {
$id = ConnectionManager::DEFAULT_CONNECTION_ID;
}
if (count($this->loadedConnections) < 1) {
return false;
}
if (isset($this->loadedConnections[$id])) {
$this->configuredConnectionId = $id;
$this->platformConnector = [$id => $this->loadedConnections[$id]];
$connector = new PlatformResolver($this);
return $connector->resolvePlatform(new EventManager());
}
} | Try to connection with this id from the loaded connections in the configuration
file.
@param $id <String>
@access private
@return <Mixed> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Connection/ConnectionManager.php#L223-L239 |
alekitto/metadata | lib/Loader/Locator/IteratorFileLocator.php | IteratorFileLocator.locate | public function locate(string $basePath, string $extension): array
{
if ('.' !== $extension[0]) {
throw new \InvalidArgumentException('Extension argument must start with a dot');
}
// Cannot use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME because of this:
// https://bugs.php.net/bug.php?id=66405
$regex = '/'.preg_quote($extension, '/').'$/';
$iterator = new \CallbackFilterIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($basePath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY
),
function (\SplFileInfo $fileInfo) use ($regex) {
return preg_match($regex, $fileInfo->getPathname());
}
);
return array_map(function (\SplFileInfo $fileInfo) {
return $fileInfo->getPathname();
}, iterator_to_array($iterator));
} | php | public function locate(string $basePath, string $extension): array
{
if ('.' !== $extension[0]) {
throw new \InvalidArgumentException('Extension argument must start with a dot');
}
// Cannot use RecursiveDirectoryIterator::CURRENT_AS_PATHNAME because of this:
// https://bugs.php.net/bug.php?id=66405
$regex = '/'.preg_quote($extension, '/').'$/';
$iterator = new \CallbackFilterIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($basePath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY
),
function (\SplFileInfo $fileInfo) use ($regex) {
return preg_match($regex, $fileInfo->getPathname());
}
);
return array_map(function (\SplFileInfo $fileInfo) {
return $fileInfo->getPathname();
}, iterator_to_array($iterator));
} | {@inheritdoc} | https://github.com/alekitto/metadata/blob/0422ac8d7fe72d5fa8cc51b6f1e173866e8afb2c/lib/Loader/Locator/IteratorFileLocator.php#L10-L33 |
phramework/testphase | src/Globals.php | Globals.get | public static function get($key = null, $operators = null)
{
if (static::$globals === null) {
static::initializeGlobals();
}
if ($key !== null) {
$parsed = Expression::parse($key);
if ($parsed === null) {
throw new \Exception(sprintf(
'Invalid key "%s"',
$key
));
}
if (!static::exists($parsed->key)) {
throw new UnsetGlobalException($parsed->key);
}
$global = static::$globals->{$parsed->key};
switch ($parsed->mode) {
case Globals::KEY_FUNCTION:
$functionParameters = [];
if (property_exists($parsed, 'parameters')) {
$functionParameters = Globals::handleFunctionVariable($parsed->parameters);
}
return call_user_func_array(
$global,
$functionParameters
);
case Globals::KEY_ARRAY:
return $global[(int) Globals::handleArrayVariable($parsed->index)];
case Globals::KEY_VARIABLE:
default:
return $global;
}
}
return static::$globals;
} | php | public static function get($key = null, $operators = null)
{
if (static::$globals === null) {
static::initializeGlobals();
}
if ($key !== null) {
$parsed = Expression::parse($key);
if ($parsed === null) {
throw new \Exception(sprintf(
'Invalid key "%s"',
$key
));
}
if (!static::exists($parsed->key)) {
throw new UnsetGlobalException($parsed->key);
}
$global = static::$globals->{$parsed->key};
switch ($parsed->mode) {
case Globals::KEY_FUNCTION:
$functionParameters = [];
if (property_exists($parsed, 'parameters')) {
$functionParameters = Globals::handleFunctionVariable($parsed->parameters);
}
return call_user_func_array(
$global,
$functionParameters
);
case Globals::KEY_ARRAY:
return $global[(int) Globals::handleArrayVariable($parsed->index)];
case Globals::KEY_VARIABLE:
default:
return $global;
}
}
return static::$globals;
} | Get global key's value.
An expression to access array elements or a function can be given.
@param string $key Expression key, can have parenthesis or square brackets operator.
@return mixed|callable|array If you access a function without the
parenthesis operator or an array without square brackets operator
then this method will return the callable or the whole array respectively.
@example
```php
Globals::get('myVarible');
Globals::get('rand-boolean()');
Globals::get('rand-integer(10)'); //A random integer from 0 to 10
Globals::get('myArray[1]'); //Get second array element
```
@throws \Exception When expression key is invalid.
@throws \Phramework\Exceptions\NotFoundException When key is not found. | https://github.com/phramework/testphase/blob/b00107b7a37cf1a1b9b8860b3eb031aacfa2634c/src/Globals.php#L123-L166 |
phramework/testphase | src/Globals.php | Globals.set | public static function set($key, $value)
{
if (static::$globals === null) {
static::initializeGlobals();
}
if (!preg_match('/^' . Expression::PATTERN_KEY . '$/', $key)) {
throw new \Exception('Invalid key');
}
static::$globals->{$key} = $value;
} | php | public static function set($key, $value)
{
if (static::$globals === null) {
static::initializeGlobals();
}
if (!preg_match('/^' . Expression::PATTERN_KEY . '$/', $key)) {
throw new \Exception('Invalid key');
}
static::$globals->{$key} = $value;
} | Will overwrite value with same key
@param string $key Key
@param mixed $value
@example
```php
Globals::set('myVariable', 5);
Globals::set(
'dots',
function ($length = 4) {
return str_repeat('.', $length);
}
);
Globals::get('dots()'); //Will return a string of 4 dots
Globals::get('dots(10)'); //Will return a string of 10 dots
```
@throws \Exception When key is invalid, *see Expression::PATTERN_KEY* | https://github.com/phramework/testphase/blob/b00107b7a37cf1a1b9b8860b3eb031aacfa2634c/src/Globals.php#L228-L239 |
phramework/testphase | src/Globals.php | Globals.toString | public static function toString()
{
$return = [];
foreach (static::$globals as $key => $value) {
$type = gettype($value);
if (is_callable($value)) {
$valueString = 'callable';
$type = 'callable';
} elseif (is_array($value)) {
$valueString = implode(', ', $value);
} else {
$valueString = (string)$value;
}
$return[] = sprintf(
'"%s": (%s) %s',
$key,
$type,
$valueString
);
}
return implode(PHP_EOL, $return);
} | php | public static function toString()
{
$return = [];
foreach (static::$globals as $key => $value) {
$type = gettype($value);
if (is_callable($value)) {
$valueString = 'callable';
$type = 'callable';
} elseif (is_array($value)) {
$valueString = implode(', ', $value);
} else {
$valueString = (string)$value;
}
$return[] = sprintf(
'"%s": (%s) %s',
$key,
$type,
$valueString
);
}
return implode(PHP_EOL, $return);
} | Return keys and values of global variables as string
@return string | https://github.com/phramework/testphase/blob/b00107b7a37cf1a1b9b8860b3eb031aacfa2634c/src/Globals.php#L245-L270 |
DBRisinajumi/d2company | controllers/CcucUserCompanyController.php | CcucUserCompanyController.actionEditableSaver | public function actionEditableSaver()
{
Yii::import('EditableSaver'); //or you can add import 'ext.editable.*' to config
$es = new EditableSaver('CcucUserCompany'); // classname of model to be updated
$es->update();
//verify if change statuss
if($es->attribute != 'ccuc_status'){
return;
}
//verify if status changet to USER
if($es->value != CcucUserCompany::CCUC_STATUS_USER){
return;
}
//if do not have user, create
$m = Person::model();
return $m->createUser($es->model->ccucPerson->id);
} | php | public function actionEditableSaver()
{
Yii::import('EditableSaver'); //or you can add import 'ext.editable.*' to config
$es = new EditableSaver('CcucUserCompany'); // classname of model to be updated
$es->update();
//verify if change statuss
if($es->attribute != 'ccuc_status'){
return;
}
//verify if status changet to USER
if($es->value != CcucUserCompany::CCUC_STATUS_USER){
return;
}
//if do not have user, create
$m = Person::model();
return $m->createUser($es->model->ccucPerson->id);
} | for company ccuc on change status to USER create customer office uses
@return type | https://github.com/DBRisinajumi/d2company/blob/20df0db96ac2c8e73471c4bab7d487b67ef4ed0a/controllers/CcucUserCompanyController.php#L129-L149 |
rbone/phactory | lib/Phactory/Loader.php | Loader.load | public function load($name)
{
$factoryClass = ucfirst($name) . "Phactory";
if (!class_exists($factoryClass)) {
throw new \Exception("Unknown factory '$name'");
}
return new Factory($name, new $factoryClass);
} | php | public function load($name)
{
$factoryClass = ucfirst($name) . "Phactory";
if (!class_exists($factoryClass)) {
throw new \Exception("Unknown factory '$name'");
}
return new Factory($name, new $factoryClass);
} | Loads the factory according to the object class name
@param string $name
@return \Phactory\Factory
@throws \Exception | https://github.com/rbone/phactory/blob/f1c474084f9b310d171f393fe196e8a2a7aae1ec/lib/Phactory/Loader.php#L17-L26 |
newestindustry/ginger-rest | src/Ginger/XMLSerializer.php | XMLSerializer.generateValidXmlFromArray | public static function generateValidXmlFromArray($array, $node_block='response', $node_name='item')
{
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
} | php | public static function generateValidXmlFromArray($array, $node_block='response', $node_name='item')
{
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= '<' . $node_block . '>';
$xml .= self::generateXmlFromArray($array, $node_name);
$xml .= '</' . $node_block . '>';
return $xml;
} | Generate valid xml from array
@param array $array
@param string $node_block
@param string $node_name
@return string | https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/XMLSerializer.php#L38-L47 |
newestindustry/ginger-rest | src/Ginger/XMLSerializer.php | XMLSerializer.generateXmlFromArray | private static function generateXmlFromArray($array, $node_name)
{
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
} | php | private static function generateXmlFromArray($array, $node_name)
{
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES);
}
return $xml;
} | Generate XML from array
@param array $array
@param string $node_name
@return string | https://github.com/newestindustry/ginger-rest/blob/482b77dc122a60ab0bf143a3c4a1e67168985c83/src/Ginger/XMLSerializer.php#L56-L73 |
OpenClassrooms/FrontDesk | src/Services/Impl/EnrollmentServiceImpl.php | EnrollmentServiceImpl.query | public function query(array $field = [], array $filter = [], $limit = 100)
{
return $this->enrollmentGateway->query($field, $filter, $limit);
} | php | public function query(array $field = [], array $filter = [], $limit = 100)
{
return $this->enrollmentGateway->query($field, $filter, $limit);
} | {@inheritdoc} | https://github.com/OpenClassrooms/FrontDesk/blob/1d221ff96fa0a3948b8bd210dec77542074ed988/src/Services/Impl/EnrollmentServiceImpl.php#L21-L24 |
acacha/forge-publish | src/Console/Commands/PublishLogin.php | PublishLogin.handle | public function handle()
{
$this->checkIfCommandHaveToBeSkipped();
$emails = $this->getPossibleEmails();
$email = $this->argument('email') ?
$this->argument('email') :
$this->anticipate('Email?', $emails, $current_value = fp_env('ACACHA_FORGE_EMAIL'));
if ($email != fp_env('ACACHA_FORGE_EMAIL')) {
$this->addValueToEnv('ACACHA_FORGE_EMAIL', $email);
}
$password = $this->secret('Password?');
$this->url = config('forge-publish.url') . config('forge-publish.token_uri');
$response = '';
try {
$response = $this->http->post($this->url, [
'form_params' => [
'client_id' => config('forge-publish.client_id'),
'client_secret' => config('forge-publish.client_secret'),
'grant_type' => 'password',
'username' => $email,
'password' => $password,
'scope' => '*',
]
]);
} catch (\Exception $e) {
$this->showErrorAndDie($e);
}
$body = json_decode((string) $response->getBody());
if (!isset($body->access_token)) {
$this->error("The URL $this->url doesn't return an access_token!");
die();
}
$access_token = $body->access_token;
$this->addValueToEnv('ACACHA_FORGE_ACCESS_TOKEN', $access_token);
$this->info('The access token has been added to file .env with key ACACHA_FORGE_ACCESS_TOKEN');
} | php | public function handle()
{
$this->checkIfCommandHaveToBeSkipped();
$emails = $this->getPossibleEmails();
$email = $this->argument('email') ?
$this->argument('email') :
$this->anticipate('Email?', $emails, $current_value = fp_env('ACACHA_FORGE_EMAIL'));
if ($email != fp_env('ACACHA_FORGE_EMAIL')) {
$this->addValueToEnv('ACACHA_FORGE_EMAIL', $email);
}
$password = $this->secret('Password?');
$this->url = config('forge-publish.url') . config('forge-publish.token_uri');
$response = '';
try {
$response = $this->http->post($this->url, [
'form_params' => [
'client_id' => config('forge-publish.client_id'),
'client_secret' => config('forge-publish.client_secret'),
'grant_type' => 'password',
'username' => $email,
'password' => $password,
'scope' => '*',
]
]);
} catch (\Exception $e) {
$this->showErrorAndDie($e);
}
$body = json_decode((string) $response->getBody());
if (!isset($body->access_token)) {
$this->error("The URL $this->url doesn't return an access_token!");
die();
}
$access_token = $body->access_token;
$this->addValueToEnv('ACACHA_FORGE_ACCESS_TOKEN', $access_token);
$this->info('The access token has been added to file .env with key ACACHA_FORGE_ACCESS_TOKEN');
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishLogin.php#L65-L109 |
luoxiaojun1992/lb_framework | components/Log.php | Log.record | public function record(
$message = '',
$context = [],
$level = Logger::NOTICE,
$role = 'system',
$times = 0,
$ttl = 0,
$defer = false
) {
if (isset($this->loggers[$role])) {
if ($times > 0 && $ttl > 0) {
$cacheKey = md5($message);
$cnt = RedisKit::incr($cacheKey);
if ($cnt == 1) {
RedisKit::expire($cacheKey, $ttl);
}
if ($cnt > $times) {
return;
}
}
if ($defer) {
$this->addDeferLog($role, $level, $message, $context);
if ($this->deferLogsCount >= self::MAX_DEFER_LOGS) {
$this->flush();
}
return;
}
$this->loggers[$role]->addRecord($level, $message, $context);
Lb::app()->trigger(
self::LOG_WRITE_EVENT, new LogWriteEvent(
[
'level' => $level,
'message' => $message,
'context' => $context,
'role' => $role,
'time' => time(),
]
)
);
}
} | php | public function record(
$message = '',
$context = [],
$level = Logger::NOTICE,
$role = 'system',
$times = 0,
$ttl = 0,
$defer = false
) {
if (isset($this->loggers[$role])) {
if ($times > 0 && $ttl > 0) {
$cacheKey = md5($message);
$cnt = RedisKit::incr($cacheKey);
if ($cnt == 1) {
RedisKit::expire($cacheKey, $ttl);
}
if ($cnt > $times) {
return;
}
}
if ($defer) {
$this->addDeferLog($role, $level, $message, $context);
if ($this->deferLogsCount >= self::MAX_DEFER_LOGS) {
$this->flush();
}
return;
}
$this->loggers[$role]->addRecord($level, $message, $context);
Lb::app()->trigger(
self::LOG_WRITE_EVENT, new LogWriteEvent(
[
'level' => $level,
'message' => $message,
'context' => $context,
'role' => $role,
'time' => time(),
]
)
);
}
} | Add a log
@param string $message
@param array $context
@param int $level
@param string $role
@param int $times
@param int $ttl
@param bool $defer | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Log.php#L93-L135 |
luoxiaojun1992/lb_framework | components/Log.php | Log.addDeferLog | protected function addDeferLog($role, $level, $message, $context)
{
$this->deferLogs[] = compact('role', 'level', 'message', 'context');
$this->deferLogsCount++;
} | php | protected function addDeferLog($role, $level, $message, $context)
{
$this->deferLogs[] = compact('role', 'level', 'message', 'context');
$this->deferLogsCount++;
} | Add a defer log
@param $role
@param $level
@param $message
@param $context | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Log.php#L145-L149 |
luoxiaojun1992/lb_framework | components/Log.php | Log.removeDeferLog | protected function removeDeferLog($k)
{
if (!isset($this->deferLogs[$k])) {
return;
}
unset($this->deferLogs[$k]);
$this->deferLogsCount--;
} | php | protected function removeDeferLog($k)
{
if (!isset($this->deferLogs[$k])) {
return;
}
unset($this->deferLogs[$k]);
$this->deferLogsCount--;
} | Remove a defer log
@param $k | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Log.php#L156-L164 |
luoxiaojun1992/lb_framework | components/Log.php | Log.flush | public function flush()
{
//todo bugfix batch record
foreach ($this->deferLogs as $k => $deferLog) {
$this->record($deferLog['message'], $deferLog['context'], $deferLog['level'], $deferLog['role']);
$this->removeDeferLog($k);
}
} | php | public function flush()
{
//todo bugfix batch record
foreach ($this->deferLogs as $k => $deferLog) {
$this->record($deferLog['message'], $deferLog['context'], $deferLog['level'], $deferLog['role']);
$this->removeDeferLog($k);
}
} | Flush defer logs | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Log.php#L169-L176 |
factorio-item-browser/api-client | src/Serializer/SerializerFactory.php | SerializerFactory.addCacheDirectory | protected function addCacheDirectory(ContainerInterface $container, SerializerBuilder $builder): void
{
$config = $container->get('config');
$libraryConfig = $config[ConfigKey::PROJECT][ConfigKey::API_CLIENT] ?? [];
$cacheDir = (string) ($libraryConfig[ConfigKey::CACHE_DIR] ?? '');
if ($cacheDir !== '') {
$builder->setCacheDir($cacheDir);
}
} | php | protected function addCacheDirectory(ContainerInterface $container, SerializerBuilder $builder): void
{
$config = $container->get('config');
$libraryConfig = $config[ConfigKey::PROJECT][ConfigKey::API_CLIENT] ?? [];
$cacheDir = (string) ($libraryConfig[ConfigKey::CACHE_DIR] ?? '');
if ($cacheDir !== '') {
$builder->setCacheDir($cacheDir);
}
} | Adds the cache directory from the config to the builder.
@param ContainerInterface $container
@param SerializerBuilder $builder | https://github.com/factorio-item-browser/api-client/blob/ebda897483bd537c310a17ff868ca40c0568f728/src/Serializer/SerializerFactory.php#L56-L65 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.setOptions | public function setOptions($options)
{
if (!is_array($options) && !$options instanceof Traversable) {
throw new \InvalidArgumentException(sprintf(
'Expected an array or Traversable; received "%s"',
(is_object($options) ? get_class($options) : gettype($options))
));
}
foreach ($options as $key => $value){
$key = strtolower($key);
if($key == 'loader'){
$this->setLoader($value);
}
}
return $this;
} | php | public function setOptions($options)
{
if (!is_array($options) && !$options instanceof Traversable) {
throw new \InvalidArgumentException(sprintf(
'Expected an array or Traversable; received "%s"',
(is_object($options) ? get_class($options) : gettype($options))
));
}
foreach ($options as $key => $value){
$key = strtolower($key);
if($key == 'loader'){
$this->setLoader($value);
}
}
return $this;
} | Configure service broker
Use this method to configure service broker.
Currently supports only option 'loader' which
calls {@see setLoader()}.
@param array|Traversable $options
@throws \InvalidArgumentException
@return \ValuSo\Broker\ServiceBroker | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L96-L115 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.getDefaultIdentity | public function getDefaultIdentity()
{
if (!$this->defaultIdentity) {
$this->defaultIdentity = new ArrayObject(array());
if ($this->exists('Identity')) {
$responses = $this->execute(
'Identity',
'getIdentity',
array(),
function($response){if($response instanceof ArrayAccess) return true;});
if (sizeof($responses)) {
$this->defaultIdentity = $responses->last();
}
if ($this->defaultIdentity instanceof \ArrayObject) {
$this->defaultIdentity->setFlags(\ArrayObject::ARRAY_AS_PROPS);
} elseif(!$this->defaultIdentity) {
return new \ArrayObject([]);
}
}
}
return $this->defaultIdentity;
} | php | public function getDefaultIdentity()
{
if (!$this->defaultIdentity) {
$this->defaultIdentity = new ArrayObject(array());
if ($this->exists('Identity')) {
$responses = $this->execute(
'Identity',
'getIdentity',
array(),
function($response){if($response instanceof ArrayAccess) return true;});
if (sizeof($responses)) {
$this->defaultIdentity = $responses->last();
}
if ($this->defaultIdentity instanceof \ArrayObject) {
$this->defaultIdentity->setFlags(\ArrayObject::ARRAY_AS_PROPS);
} elseif(!$this->defaultIdentity) {
return new \ArrayObject([]);
}
}
}
return $this->defaultIdentity;
} | Retrieve default identity
@return \ArrayAccess|null | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L141-L167 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.setLoader | public function setLoader(ServiceLoader $loader){
$this->loader = $loader;
$that = $this;
$this->loader->addInitializer(function ($instance) use ($that) {
// Inject broker to services
if ($instance instanceof Feature\ServiceBrokerAwareInterface) {
$instance->setServiceBroker($that);
}
// Inject event manager to services
if ($instance instanceof EventManagerAwareInterface) {
$instance->setEventManager($that->getEventManager());
}
});
return $this;
} | php | public function setLoader(ServiceLoader $loader){
$this->loader = $loader;
$that = $this;
$this->loader->addInitializer(function ($instance) use ($that) {
// Inject broker to services
if ($instance instanceof Feature\ServiceBrokerAwareInterface) {
$instance->setServiceBroker($that);
}
// Inject event manager to services
if ($instance instanceof EventManagerAwareInterface) {
$instance->setEventManager($that->getEventManager());
}
});
return $this;
} | Set service loader instance
@param ServiceLoader $loader | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L185-L204 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.service | public function service($service){
if(!$this->exists($service)){
throw new ServiceNotFoundException(sprintf('Service "%s" not found', $service));
}
return new Worker($this, $service);
} | php | public function service($service){
if(!$this->exists($service)){
throw new ServiceNotFoundException(sprintf('Service "%s" not found', $service));
}
return new Worker($this, $service);
} | Initialize and retrieve a new service Worker
@param string $service
@throws ServiceNotFoundException
@return Worker | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L257-L264 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.executeInContext | public function executeInContext($context, $service, $operation, $argv = array(), $callback = null)
{
$command = new Command(
$service,
$operation,
$argv,
$context);
return $this->dispatch($command, $callback);
} | php | public function executeInContext($context, $service, $operation, $argv = array(), $callback = null)
{
$command = new Command(
$service,
$operation,
$argv,
$context);
return $this->dispatch($command, $callback);
} | Execute service operation in context
@param string $context
@param string $service
@param string $operation
@param array $argv
@param mixed $callback Valid PHP callback
@param string $context
@return ResponseCollection | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L290-L299 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.queue | public function queue(CommandInterface $command, array $options = [])
{
$queueName = null;
if (array_key_exists(self::QUEUE_OPTION_NAME, $options)) {
$queueName = $options[self::QUEUE_OPTION_NAME] ?: null;
unset($options[self::QUEUE_OPTION_NAME]);
}
$queue = $this->getQueue($queueName);
if ($command->getIdentity()) {
$identity = $command->getIdentity();
} else if ($this->getDefaultIdentity()) {
$identity = $this->getDefaultIdentity();
} else {
$identity = null;
}
if (method_exists($identity, 'toArray')) {
$identity = $identity->toArray();
} else if ($identity instanceof \ArrayObject) {
$identity = $identity->getArrayCopy();
}
$job = new ServiceJob();
$job->setup($command, $identity);
$job->setServiceBroker($this);
$queue->push($job, $options);
return $job;
} | php | public function queue(CommandInterface $command, array $options = [])
{
$queueName = null;
if (array_key_exists(self::QUEUE_OPTION_NAME, $options)) {
$queueName = $options[self::QUEUE_OPTION_NAME] ?: null;
unset($options[self::QUEUE_OPTION_NAME]);
}
$queue = $this->getQueue($queueName);
if ($command->getIdentity()) {
$identity = $command->getIdentity();
} else if ($this->getDefaultIdentity()) {
$identity = $this->getDefaultIdentity();
} else {
$identity = null;
}
if (method_exists($identity, 'toArray')) {
$identity = $identity->toArray();
} else if ($identity instanceof \ArrayObject) {
$identity = $identity->getArrayCopy();
}
$job = new ServiceJob();
$job->setup($command, $identity);
$job->setServiceBroker($this);
$queue->push($job, $options);
return $job;
} | Queue execution of service operation
@param CommandInterface $command
@param array $options
@return ServiceJob | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L308-L339 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.dispatch | public function dispatch(CommandInterface $command, $callback = null){
if (!$command->getIdentity() && $this->getDefaultIdentity()) {
$command->setIdentity($this->getDefaultIdentity());
}
$service = $command->getService();
$operation = $command->getOperation();
$context = $command->getContext();
$argv = $command->getParams();
$exception = null;
if(!$this->exists($command->getService())){
throw new ServiceNotFoundException(sprintf(
'Service "%s" not found', $command->getService()));
}
$responses = null;
// Notify, that a (background) job is about to start
if ($command->getJob()) {
$jobEvent = $this->createEvent(
'job.start', $command);
$this->getEventManager()
->trigger($jobEvent);
}
// Prepare and trigger init.<service>.<operation> event
$initEvent = strtolower('init.'.$service.'.'.$operation);
if(!$this->getEventManager()->getListeners($initEvent)->isEmpty()){
$e = $this->createEvent($initEvent, $command);
$eventResponses = $this->trigger(
$e,
function($response){if($response === false) return true;}
);
if($eventResponses->stopped() && $eventResponses->last() === false){
$responses = new ResponseCollection();
$responses->setStopped(true);
}
}
// Dispatch command
if ($responses === null) {
try{
$responses = $this->getLoader()->getCommandManager()->trigger(
$command,
$callback
);
} catch(\Exception $ex) {
$exception = $ex;
}
}
// Prepare and trigger final.<service>.<operation> event
$finalEvent = strtolower('final.'.$service.'.'.$operation);
if(!$this->getEventManager()->getListeners($finalEvent)->isEmpty()){
$e = $this->createEvent($finalEvent, $command);
// Set exception
if ($exception) {
$e->setException($exception);
}
$this->trigger($e);
// Listeners have a chance to clear (or change) the exception
$exception = $e->getException();
}
// Notify that the job has ended
if ($command->getJob()) {
$jobEvent = $this->createEvent('job.end', $command);
if ($exception) {
$jobEvent->setException($exception);
}
$this->trigger($jobEvent);
}
// Throw exception if it still exists
if ($exception instanceof \Exception) {
throw $exception;
}
return $responses;
} | php | public function dispatch(CommandInterface $command, $callback = null){
if (!$command->getIdentity() && $this->getDefaultIdentity()) {
$command->setIdentity($this->getDefaultIdentity());
}
$service = $command->getService();
$operation = $command->getOperation();
$context = $command->getContext();
$argv = $command->getParams();
$exception = null;
if(!$this->exists($command->getService())){
throw new ServiceNotFoundException(sprintf(
'Service "%s" not found', $command->getService()));
}
$responses = null;
// Notify, that a (background) job is about to start
if ($command->getJob()) {
$jobEvent = $this->createEvent(
'job.start', $command);
$this->getEventManager()
->trigger($jobEvent);
}
// Prepare and trigger init.<service>.<operation> event
$initEvent = strtolower('init.'.$service.'.'.$operation);
if(!$this->getEventManager()->getListeners($initEvent)->isEmpty()){
$e = $this->createEvent($initEvent, $command);
$eventResponses = $this->trigger(
$e,
function($response){if($response === false) return true;}
);
if($eventResponses->stopped() && $eventResponses->last() === false){
$responses = new ResponseCollection();
$responses->setStopped(true);
}
}
// Dispatch command
if ($responses === null) {
try{
$responses = $this->getLoader()->getCommandManager()->trigger(
$command,
$callback
);
} catch(\Exception $ex) {
$exception = $ex;
}
}
// Prepare and trigger final.<service>.<operation> event
$finalEvent = strtolower('final.'.$service.'.'.$operation);
if(!$this->getEventManager()->getListeners($finalEvent)->isEmpty()){
$e = $this->createEvent($finalEvent, $command);
// Set exception
if ($exception) {
$e->setException($exception);
}
$this->trigger($e);
// Listeners have a chance to clear (or change) the exception
$exception = $e->getException();
}
// Notify that the job has ended
if ($command->getJob()) {
$jobEvent = $this->createEvent('job.end', $command);
if ($exception) {
$jobEvent->setException($exception);
}
$this->trigger($jobEvent);
}
// Throw exception if it still exists
if ($exception instanceof \Exception) {
throw $exception;
}
return $responses;
} | Execute operation
@param CommandInterface $command
@param mixed $callback
@throws ServiceNotFoundException
@throws \Exception
@return ResponseCollection|null | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L404-L495 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.trigger | protected function trigger(ServiceEvent $event, $callback = null)
{
return $this->getEventManager()->trigger($event, $callback);
} | php | protected function trigger(ServiceEvent $event, $callback = null)
{
return $this->getEventManager()->trigger($event, $callback);
} | Triggers an event
@param ServiceEvent $event
@param mixed $callback | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L503-L506 |
valu-digital/valuso | src/ValuSo/Broker/ServiceBroker.php | ServiceBroker.createEvent | protected function createEvent($name, CommandInterface $command)
{
$event = new ServiceEvent();
$event->setName($name);
$event->setCommand($command);
$event->setParams($command->getParams());
return $event;
} | php | protected function createEvent($name, CommandInterface $command)
{
$event = new ServiceEvent();
$event->setName($name);
$event->setCommand($command);
$event->setParams($command->getParams());
return $event;
} | Create a new service event
@param string $name
@param CommandInterface $command
@return \ValuSo\Broker\ServiceEvent | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Broker/ServiceBroker.php#L515-L523 |
worldnettps/magento2-module-subscription | Model/Status.php | Status.getCurrency | public function getCurrency()
{
$options = [ 'EUR' => __('Euro'),
'GBP' => __('Sterling'),
'USD' => __('US Dollar'),
'CAD' => __('Canadian Dollar'),
'AUD' => __('Australian Dollar'),
'DKK' => __('Danish Krone'),
'SEK' => __('Swedish Krona'),
'NOK' => __('Norwegian Krone')
];
return $options;
} | php | public function getCurrency()
{
$options = [ 'EUR' => __('Euro'),
'GBP' => __('Sterling'),
'USD' => __('US Dollar'),
'CAD' => __('Canadian Dollar'),
'AUD' => __('Australian Dollar'),
'DKK' => __('Danish Krone'),
'SEK' => __('Swedish Krona'),
'NOK' => __('Norwegian Krone')
];
return $options;
} | Get Grid row currency labels array.
@return array | https://github.com/worldnettps/magento2-module-subscription/blob/dcac6fb7f13bc9a3d47cb9ca04734fef627b0eab/Model/Status.php#L11-L23 |
phramework/phramework | src/URIStrategy/ClassBased.php | ClassBased.invoke | public function invoke(
&$requestParameters,
$requestMethod,
$requestHeaders,
$requestUser
) {
//Get controller from the request (URL parameter)
if (!isset($requestParameters['controller']) || empty($requestParameters['controller'])) {
if (($defaultController = Phramework::getSetting('default_controller'))) {
$requestParameters['controller'] = $defaultController;
} else {
throw new \Phramework\Exceptions\ServerException(
'Default controller has not been configured'
);
}
}
$controller = $requestParameters['controller'];
unset($requestParameters['controller']);
//Check if requested controller and method are allowed
if (!in_array($controller, $this->controllerWhitelist)) {
throw new NotFoundException('Method not found');
} elseif (!in_array($requestMethod, Phramework::$methodWhitelist)) {
throw new \Phramework\Exceptions\MethodNotAllowedException(
'Method not found'
);
}
//If not authenticated allow only certain controllers to access
if (!$requestUser &&
!in_array($controller, $this->controllerUnauthenticatedWhitelist) &&
!in_array($controller, $this->controllerPublicWhitelist)) {
throw new \Phramework\Exceptions\UnauthorizedException();
}
// Append suffix
$controller = $controller . ($this->suffix ? $this->suffix : '');
/**
* Check if the requested controller and model is callable
* In order to be callable :
* 1) The controllers class must be defined as : myname_$suffix
* 2) the methods must be defined as : public static function GET($requestParameters)
* where $requestParameters are the passed parameters
*/
if (!is_callable($this->namespace . "{$controller}::$requestMethod")) {
//Retry using capitalized first letter of the class
$controller = ucfirst($controller);
if (!is_callable($this->namespace . "{$controller}::$requestMethod")) {
throw new NotFoundException('Method not found');
}
}
//Call handler method
call_user_func(
[$this->namespace . $controller, $requestMethod],
$requestParameters,
$requestMethod,
$requestHeaders
);
return [$controller, $requestMethod];
} | php | public function invoke(
&$requestParameters,
$requestMethod,
$requestHeaders,
$requestUser
) {
//Get controller from the request (URL parameter)
if (!isset($requestParameters['controller']) || empty($requestParameters['controller'])) {
if (($defaultController = Phramework::getSetting('default_controller'))) {
$requestParameters['controller'] = $defaultController;
} else {
throw new \Phramework\Exceptions\ServerException(
'Default controller has not been configured'
);
}
}
$controller = $requestParameters['controller'];
unset($requestParameters['controller']);
//Check if requested controller and method are allowed
if (!in_array($controller, $this->controllerWhitelist)) {
throw new NotFoundException('Method not found');
} elseif (!in_array($requestMethod, Phramework::$methodWhitelist)) {
throw new \Phramework\Exceptions\MethodNotAllowedException(
'Method not found'
);
}
//If not authenticated allow only certain controllers to access
if (!$requestUser &&
!in_array($controller, $this->controllerUnauthenticatedWhitelist) &&
!in_array($controller, $this->controllerPublicWhitelist)) {
throw new \Phramework\Exceptions\UnauthorizedException();
}
// Append suffix
$controller = $controller . ($this->suffix ? $this->suffix : '');
/**
* Check if the requested controller and model is callable
* In order to be callable :
* 1) The controllers class must be defined as : myname_$suffix
* 2) the methods must be defined as : public static function GET($requestParameters)
* where $requestParameters are the passed parameters
*/
if (!is_callable($this->namespace . "{$controller}::$requestMethod")) {
//Retry using capitalized first letter of the class
$controller = ucfirst($controller);
if (!is_callable($this->namespace . "{$controller}::$requestMethod")) {
throw new NotFoundException('Method not found');
}
}
//Call handler method
call_user_func(
[$this->namespace . $controller, $requestMethod],
$requestParameters,
$requestMethod,
$requestHeaders
);
return [$controller, $requestMethod];
} | Invoke URIStrategy
@param object $requestParameters Request parameters
@param string $requestMethod HTTP request method
@param array $requestHeaders Request headers
@param object|false $requestUser Use object if successful
authenticated otherwise false
@throws Phramework\Exceptions\NotFoundException
@throws Phramework\Exceptions\UnauthorizedException
@throws Phramework\Exceptions\ServerException
@return string[2] This method should return `[$class, $method]` on success | https://github.com/phramework/phramework/blob/40041d1ef23b1f8cdbd26fb112448d6a3dbef012/src/URIStrategy/ClassBased.php#L98-L161 |
PHPColibri/framework | Validation/Validation.php | Validation.check | private function check(string $method, $key, string $message = null, callable $check)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->$method($name, $message);
}
} else {
if (isset($this->scope[$key]) && ! $check($key)) {
$this->errors[$key] = sprintf($message !== null ? $message : self::${$method . 'Message'}, $key);
}
}
return $this;
} | php | private function check(string $method, $key, string $message = null, callable $check)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->$method($name, $message);
}
} else {
if (isset($this->scope[$key]) && ! $check($key)) {
$this->errors[$key] = sprintf($message !== null ? $message : self::${$method . 'Message'}, $key);
}
}
return $this;
} | @param string $method
@param string|array $key
@param string $message
@param callable $check
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L106-L119 |
PHPColibri/framework | Validation/Validation.php | Validation.required | public function required($key, $message = null)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->required($name, $message);
}
} else {
if ( ! (isset($this->scope[$key]) && ! empty($this->scope[$key]))) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$requiredMessage, $key);
}
}
return $this;
} | php | public function required($key, $message = null)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->required($name, $message);
}
} else {
if ( ! (isset($this->scope[$key]) && ! empty($this->scope[$key]))) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$requiredMessage, $key);
}
}
return $this;
} | 'Required' validation rule. Checks if specified by $key data exists in scope.
@param string|array $key
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L129-L142 |
PHPColibri/framework | Validation/Validation.php | Validation.minLength | public function minLength($key, $minLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->minLength($name, is_array($minLength) ? $minLength[$k] : $minLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) < $minLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$minLengthMessage, $key, $minLength);
}
}
return $this;
} | php | public function minLength($key, $minLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->minLength($name, is_array($minLength) ? $minLength[$k] : $minLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) < $minLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$minLengthMessage, $key, $minLength);
}
}
return $this;
} | 'MinLength' validation rule. Checks that specified by $key data not shorter than $minLength.
@param string|array $key
@param int|array $minLength
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L153-L166 |
PHPColibri/framework | Validation/Validation.php | Validation.maxLength | public function maxLength($key, $maxLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->maxLength($name, is_array($maxLength) ? $maxLength[$k] : $maxLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) > $maxLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$maxLengthMessage, $key, $maxLength);
}
}
return $this;
} | php | public function maxLength($key, $maxLength, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->maxLength($name, is_array($maxLength) ? $maxLength[$k] : $maxLength, $message);
}
} else {
if (isset($this->scope[$key]) && mb_strlen($this->scope[$key]) > $maxLength) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$maxLengthMessage, $key, $maxLength);
}
}
return $this;
} | 'MaxLength' validation rule. Checks that specified by $key data not longer than $maxLength.
@param string|array $key
@param int|array $maxLength
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L177-L190 |
PHPColibri/framework | Validation/Validation.php | Validation.regex | public function regex($key, $pattern, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->regex($name, is_array($pattern) ? $pattern[$k] : $pattern, $message);
}
} else {
if (isset($this->scope[$key]) && ! (bool)preg_match($pattern, $this->scope[$key])) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$regexMessage, $key);
}
}
return $this;
} | php | public function regex($key, $pattern, $message = null)
{
if (is_array($key)) {
foreach ($key as $k => $name) {
$this->regex($name, is_array($pattern) ? $pattern[$k] : $pattern, $message);
}
} else {
if (isset($this->scope[$key]) && ! (bool)preg_match($pattern, $this->scope[$key])) {
$this->errors[$key] = sprintf($message !== null ? $message : self::$regexMessage, $key);
}
}
return $this;
} | 'Regex' validation rule. Checks that specified by $key data matches to $pattern.
@param string|array $key
@param string $pattern
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L201-L214 |
PHPColibri/framework | Validation/Validation.php | Validation.isIntGt0 | public function isIntGt0($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isInt($this->scope[$key]) && ((int)$this->scope[$key]) > 0;
});
} | php | public function isIntGt0($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isInt($this->scope[$key]) && ((int)$this->scope[$key]) > 0;
});
} | 'IsIntGt0' validation rule. Checks that specified by $key data is integer and greater than zero.
@param string|array $key
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L224-L229 |
PHPColibri/framework | Validation/Validation.php | Validation.isJSON | public function isJSON($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isJSON($this->scope[$key]);
});
} | php | public function isJSON($key, $message = null)
{
return $this->check(__FUNCTION__, $key, $message, function ($key) {
return Str::isJSON($this->scope[$key]);
});
} | 'IsJSON' validation rule. Checks that specified by $key data stores a JSON string.
@param string|array $key
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L239-L244 |
PHPColibri/framework | Validation/Validation.php | Validation.isEqual | public function isEqual(array $keys, $message = null)
{
$existingKey = null;
foreach ($keys as $key) {
if (isset($this->scope[$key])) {
$existingKey = $key;
break;
}
}
if ($existingKey === null) {
return $this;
}
foreach ($keys as $key) {
if (isset($this->scope[$key]) && $this->scope[$key] != $this->scope[$existingKey]) {
$keysList = implode("', '", $keys);
$this->errors[$key] = sprintf($message !== null ? $message : self::$isEqualMessage, $keysList);
}
}
return $this;
} | php | public function isEqual(array $keys, $message = null)
{
$existingKey = null;
foreach ($keys as $key) {
if (isset($this->scope[$key])) {
$existingKey = $key;
break;
}
}
if ($existingKey === null) {
return $this;
}
foreach ($keys as $key) {
if (isset($this->scope[$key]) && $this->scope[$key] != $this->scope[$existingKey]) {
$keysList = implode("', '", $keys);
$this->errors[$key] = sprintf($message !== null ? $message : self::$isEqualMessage, $keysList);
}
}
return $this;
} | 'IsEqual' validation rule. Checks that specified by $keys values are equal.
@param array $keys
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L269-L290 |
PHPColibri/framework | Validation/Validation.php | Validation.isNot | public function isNot($checkFunc, $key, $message)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->isNot($checkFunc, $name, $message);
}
} else {
if (isset($this->scope[$key]) && call_user_func($checkFunc, $this->scope[$key])) {
$this->errors[$key] = sprintf($message, $key);
}
}
return $this;
} | php | public function isNot($checkFunc, $key, $message)
{
if (is_array($key)) {
foreach ($key as $name) {
$this->isNot($checkFunc, $name, $message);
}
} else {
if (isset($this->scope[$key]) && call_user_func($checkFunc, $this->scope[$key])) {
$this->errors[$key] = sprintf($message, $key);
}
}
return $this;
} | 'Is' validation rule. Custom rule specified by $checkFunc(). Checks that data NOT satisfies to rule.
@param callable $checkFunc
@param string|array $key
@param string $message
@return $this | https://github.com/PHPColibri/framework/blob/7e5b77141da5e5e7c63afc83592671321ac52f36/Validation/Validation.php#L325-L338 |
luismareze/geomanager | src/app/GeoTemplates.php | GeoTemplates.services | private function services()
{
$this->crud->addField([ // CustomHTML
'name' => 'metas_separator',
'type' => 'custom_html',
'value' => '<br><h2>Metas</h2><hr>',
]);
$this->crud->addField([
'name' => 'meta_title',
'label' => 'Meta Title',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([
'name' => 'meta_description',
'label' => 'Meta Description',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([
'name' => 'meta_keywords',
'type' => 'textarea',
'label' => 'Meta Keywords',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([ // CustomHTML
'name' => 'content_separator',
'type' => 'custom_html',
'value' => '<br><h2>Content</h2><hr>',
]);
$this->crud->addField([
'name' => 'content',
'label' => 'Content',
'type' => 'wysiwyg',
'placeholder' => 'Your content here',
]);
} | php | private function services()
{
$this->crud->addField([ // CustomHTML
'name' => 'metas_separator',
'type' => 'custom_html',
'value' => '<br><h2>Metas</h2><hr>',
]);
$this->crud->addField([
'name' => 'meta_title',
'label' => 'Meta Title',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([
'name' => 'meta_description',
'label' => 'Meta Description',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([
'name' => 'meta_keywords',
'type' => 'textarea',
'label' => 'Meta Keywords',
'fake' => true,
'store_in' => 'extras',
]);
$this->crud->addField([ // CustomHTML
'name' => 'content_separator',
'type' => 'custom_html',
'value' => '<br><h2>Content</h2><hr>',
]);
$this->crud->addField([
'name' => 'content',
'label' => 'Content',
'type' => 'wysiwyg',
'placeholder' => 'Your content here',
]);
} | /*
|--------------------------------------------------------------------------
| Geo Templates for LuisMareze\GeoManager
|--------------------------------------------------------------------------
|
| Each geo template has its own method, that define what fields should show up using the LuisMareze\CRUD API.
| Use snake_case for naming and GeoManager will make sure it looks pretty in the create/update form
| template dropdown.
|
| Any fields defined here will show up after the standard geo fields:
| - select template
| - geo name (only seen by admins)
| - geo title
| - geo slug | https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/GeoTemplates.php#L23-L60 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.generateSelectForModel | public function generateSelectForModel(AbstractModel $model, $param)
{
$cacheData = $this->fetchCacheData($model);
if (isset($cacheData[self::RELATION_INDEX])) {
$this->checkRelations($cacheData[self::RELATION_INDEX]);
}
/**
* select Strategy
*/
$strategy = new MySQLSelectStrategy(
$cacheData[self::TABLE_DATA_INDEX],
array_keys($param),
$param
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$param,
self::SELECT_QUERY
];
} | php | public function generateSelectForModel(AbstractModel $model, $param)
{
$cacheData = $this->fetchCacheData($model);
if (isset($cacheData[self::RELATION_INDEX])) {
$this->checkRelations($cacheData[self::RELATION_INDEX]);
}
/**
* select Strategy
*/
$strategy = new MySQLSelectStrategy(
$cacheData[self::TABLE_DATA_INDEX],
array_keys($param),
$param
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$param,
self::SELECT_QUERY
];
} | @param AbstractModel $model
@param array $param
@return string | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L81-L104 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.prepareModelData | public function prepareModelData(AbstractModel $model, MySQLTableData $tableData)
{
$data = $columData = [];
$keyList = $tableData->getPrimaryKey();
$reflection = new \ReflectionClass($model);
foreach ($tableData->getColumnNames() as $column) {
try {
$reflectedProperty = $reflection->getProperty($column);
$reflectedProperty->setAccessible(true);
$columData = [
'value' => $reflectedProperty->getValue($model),
'name' => $column
];
if (in_array($column, $keyList)) {
array_merge($columData, ['KEY' => true]);
}
$data[] = $columData;
} catch (\Exception $e) {
$logger = \chilimatic\lib\di\ClosureFactory::getInstance()->get('error-log');
$logger->error($e->getMessage(), $e->getTraceAsString());
}
}
return $data;
} | php | public function prepareModelData(AbstractModel $model, MySQLTableData $tableData)
{
$data = $columData = [];
$keyList = $tableData->getPrimaryKey();
$reflection = new \ReflectionClass($model);
foreach ($tableData->getColumnNames() as $column) {
try {
$reflectedProperty = $reflection->getProperty($column);
$reflectedProperty->setAccessible(true);
$columData = [
'value' => $reflectedProperty->getValue($model),
'name' => $column
];
if (in_array($column, $keyList)) {
array_merge($columData, ['KEY' => true]);
}
$data[] = $columData;
} catch (\Exception $e) {
$logger = \chilimatic\lib\di\ClosureFactory::getInstance()->get('error-log');
$logger->error($e->getMessage(), $e->getTraceAsString());
}
}
return $data;
} | @param AbstractModel $model
@param MySQLTableData $tableData
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L112-L142 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.generateInsertForModel | public function generateInsertForModel(AbstractModel $model)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLInsertStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getModelData()),
self::INSERT_QUERY
];
} | php | public function generateInsertForModel(AbstractModel $model)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLInsertStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getModelData()),
self::INSERT_QUERY
];
} | @param AbstractModel $model
@return mixed | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L149-L169 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.prepareModelDataForStatement | public function prepareModelDataForStatement($modelData)
{
$newModelData = [];
foreach ($modelData as $column) {
$name = $this->paramTransformer->transform($column['name']);
switch (true) {
case is_object($column['value']):
switch (true) {
case ($column['value'] instanceOf \DateTime):
$newModelData[] = [$name, (string) $column['value']->format('Y-m-d H:i:s')];
break;
}
break;
default:
$newModelData[] = [$name, (string) $column['value']];
break;
}
}
return $newModelData;
} | php | public function prepareModelDataForStatement($modelData)
{
$newModelData = [];
foreach ($modelData as $column) {
$name = $this->paramTransformer->transform($column['name']);
switch (true) {
case is_object($column['value']):
switch (true) {
case ($column['value'] instanceOf \DateTime):
$newModelData[] = [$name, (string) $column['value']->format('Y-m-d H:i:s')];
break;
}
break;
default:
$newModelData[] = [$name, (string) $column['value']];
break;
}
}
return $newModelData;
} | @param $modelData
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L176-L199 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.generateUpdateForModel | public function generateUpdateForModel(AbstractModel $model, $diff = null)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLUpdateStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getModelData()),
self::UPDATE_QUERY
];
} | php | public function generateUpdateForModel(AbstractModel $model, $diff = null)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLUpdateStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getModelData()),
self::UPDATE_QUERY
];
} | @param AbstractModel $model
@param null $diff
@return array | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L208-L226 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.generateDeleteForModel | public function generateDeleteForModel(AbstractModel $model)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLDeleteStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getPrimaryKeySet()),
self::DELETE_QUERY
];
} | php | public function generateDeleteForModel(AbstractModel $model)
{
$cacheData = $this->fetchCacheData($model);
$strategy = new MySQLDeleteStrategy(
$cacheData[self::TABLE_DATA_INDEX],
$this->prepareModelData(
$model,
$cacheData[self::TABLE_DATA_INDEX]
)
);
$strategy->setTransformer($this->paramTransformer);
return [
$strategy->generateSQLStatement(),
$this->prepareModelDataForStatement($strategy->getPrimaryKeySet()),
self::DELETE_QUERY
];
} | @param AbstractModel $model
@return mixed | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L233-L252 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php | MySQLQueryBuilder.setParamTransformer | public function setParamTransformer(\chilimatic\lib\interfaces\IFlyWeightTransformer $paramTransformer)
{
$this->paramTransformer = $paramTransformer;
return $this;
} | php | public function setParamTransformer(\chilimatic\lib\interfaces\IFlyWeightTransformer $paramTransformer)
{
$this->paramTransformer = $paramTransformer;
return $this;
} | @param \chilimatic\lib\interfaces\IFlyWeightTransformer $paramTransformer
@return $this | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/querybuilder/MySQLQueryBuilder.php#L367-L372 |
daijulong/sms | src/SmsSender.php | SmsSender.agent | public function agent(string $agent, array $spare_agents = []): self
{
$this->default_agent = $agent;
if (!empty($spare_agents)) {
$this->spare_agents = $spare_agents;
}
return $this;
} | php | public function agent(string $agent, array $spare_agents = []): self
{
$this->default_agent = $agent;
if (!empty($spare_agents)) {
$this->spare_agents = $spare_agents;
}
return $this;
} | 指定代理器
@param string $agent
@param array $spare_agents
@return $this | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/SmsSender.php#L72-L79 |
daijulong/sms | src/SmsSender.php | SmsSender.onlyAgent | public function onlyAgent(string $agent): self
{
$this->default_agent = $agent;
$this->spare_agents = [];
return $this;
} | php | public function onlyAgent(string $agent): self
{
$this->default_agent = $agent;
$this->spare_agents = [];
return $this;
} | 指定唯一代理器
如果指定的代理器发送失败,将不再尝试使用备用代理器
@param string $agent
@return $this | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/SmsSender.php#L89-L94 |
daijulong/sms | src/SmsSender.php | SmsSender.send | public function send(): bool
{
if (!$this->receiver) {
throw new SmsSendException('Missing SMS receiver!');
}
if (!$this->sms) {
throw new SmsSendException('Missing SMS!');
}
$this->send_results = [];
$send_result = false;
array_unshift($this->spare_agents, $this->default_agent);
$agents = array_unique($this->spare_agents);
if (empty($agents)) {
throw new SmsSendException('No agent available!');
}
foreach ($agents as $agent_name) {
$agent = SmsAgent::getAgent($agent_name);
$result = $agent->send($this->receiver, $this->sms, $this->sms_params);
$this->send_results[$agent_name] = $agent->getResult();
if ($result) {
$send_result = true;
break;
}
}
$this->reset();
return $send_result;
} | php | public function send(): bool
{
if (!$this->receiver) {
throw new SmsSendException('Missing SMS receiver!');
}
if (!$this->sms) {
throw new SmsSendException('Missing SMS!');
}
$this->send_results = [];
$send_result = false;
array_unshift($this->spare_agents, $this->default_agent);
$agents = array_unique($this->spare_agents);
if (empty($agents)) {
throw new SmsSendException('No agent available!');
}
foreach ($agents as $agent_name) {
$agent = SmsAgent::getAgent($agent_name);
$result = $agent->send($this->receiver, $this->sms, $this->sms_params);
$this->send_results[$agent_name] = $agent->getResult();
if ($result) {
$send_result = true;
break;
}
}
$this->reset();
return $send_result;
} | 发送短信
@return bool
@throws SmsSendException | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/SmsSender.php#L126-L158 |
daijulong/sms | src/SmsSender.php | SmsSender.reset | private function reset()
{
$this->default_agent = SmsConfig::getDefaultAgent();
$this->spare_agents = SmsConfig::getSpareAgents();
$this->receiver = '';
$this->sms = null;
$this->sms_params = [];
} | php | private function reset()
{
$this->default_agent = SmsConfig::getDefaultAgent();
$this->spare_agents = SmsConfig::getSpareAgents();
$this->receiver = '';
$this->sms = null;
$this->sms_params = [];
} | 重置
发送成功后恢复初始状态以供下一次发送 | https://github.com/daijulong/sms/blob/3a632f332e3674de156cfc03ae334ee50248ba04/src/SmsSender.php#L187-L194 |
makinacorpus/drupal-plusql | src/Standard/ForeignKeyTrait.php | ForeignKeyTrait.add | public function add(string $table, string $name, $definition)
{
if (!is_array($definition)) {
throw new \InvalidArgumentException("Invalid definition given");
}
if (!array_key_exists('table', $definition)) {
throw new \InvalidArgumentException("Missing 'table' in definition");
}
if (!array_key_exists('columns', $definition)) {
throw new \InvalidArgumentException("Missing 'columns' in definition");
}
if (!array_key_exists('delete', $definition)) {
throw new \InvalidArgumentException("Missing 'delete' in definition");
}
switch ($definition['delete']) {
case 'cascade':
$suffix = " ON DELETE CASCADE";
break;
case 'set null':
$suffix = " ON DELETE SET NULL";
break;
case 'restrict':
$suffix = "";
break;
default:
throw new \InvalidArgumentException(sprintf("'%s' delete behavior unknown, must be on of 'cascade', 'set null' or 'restrict'", $definition['delete']));
}
$constraintName = $this->getSqlName($table, $name);
$foreignTable = $definition['table'];
$columns = implode(', ', array_keys($definition['columns']));
$foreignColumns = implode(', ', $definition['columns']);
$query = "ALTER TABLE {{$table}} ADD CONSTRAINT {{$constraintName}} FOREIGN KEY ({$columns}) REFERENCES {{$foreignTable}} ({$foreignColumns}) $suffix";
try {
$this->getConnection()->query($query);
} catch (\PDOException $e) {
switch ($e->getCode()) {
case 42710: // PostgreSQL constraint already exists
throw new ConstraintExistsException(sprintf("Foreign key '%s' already exists", $constraintName), null, $e);
case 23000: // MySQL duplicate key in table
throw new ConstraintExistsException(sprintf("Foreign key '%s' already exists", $constraintName), null, $e);
default:
throw $e;
}
}
} | php | public function add(string $table, string $name, $definition)
{
if (!is_array($definition)) {
throw new \InvalidArgumentException("Invalid definition given");
}
if (!array_key_exists('table', $definition)) {
throw new \InvalidArgumentException("Missing 'table' in definition");
}
if (!array_key_exists('columns', $definition)) {
throw new \InvalidArgumentException("Missing 'columns' in definition");
}
if (!array_key_exists('delete', $definition)) {
throw new \InvalidArgumentException("Missing 'delete' in definition");
}
switch ($definition['delete']) {
case 'cascade':
$suffix = " ON DELETE CASCADE";
break;
case 'set null':
$suffix = " ON DELETE SET NULL";
break;
case 'restrict':
$suffix = "";
break;
default:
throw new \InvalidArgumentException(sprintf("'%s' delete behavior unknown, must be on of 'cascade', 'set null' or 'restrict'", $definition['delete']));
}
$constraintName = $this->getSqlName($table, $name);
$foreignTable = $definition['table'];
$columns = implode(', ', array_keys($definition['columns']));
$foreignColumns = implode(', ', $definition['columns']);
$query = "ALTER TABLE {{$table}} ADD CONSTRAINT {{$constraintName}} FOREIGN KEY ({$columns}) REFERENCES {{$foreignTable}} ({$foreignColumns}) $suffix";
try {
$this->getConnection()->query($query);
} catch (\PDOException $e) {
switch ($e->getCode()) {
case 42710: // PostgreSQL constraint already exists
throw new ConstraintExistsException(sprintf("Foreign key '%s' already exists", $constraintName), null, $e);
case 23000: // MySQL duplicate key in table
throw new ConstraintExistsException(sprintf("Foreign key '%s' already exists", $constraintName), null, $e);
default:
throw $e;
}
}
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/Standard/ForeignKeyTrait.php#L44-L100 |
makinacorpus/drupal-plusql | src/Standard/ForeignKeyTrait.php | ForeignKeyTrait.findAllInTable | public function findAllInTable(string $table, array $definition): array
{
$ret = [];
if (isset($definition['foreign keys'])) {
foreach ($definition['foreign keys'] as $name => $item) {
if (isset($item['delete'])) {
$ret[$name] = $definition['foreign keys'][$name];
}
}
}
return $ret;
} | php | public function findAllInTable(string $table, array $definition): array
{
$ret = [];
if (isset($definition['foreign keys'])) {
foreach ($definition['foreign keys'] as $name => $item) {
if (isset($item['delete'])) {
$ret[$name] = $definition['foreign keys'][$name];
}
}
}
return $ret;
} | {@inheritdoc} | https://github.com/makinacorpus/drupal-plusql/blob/7182d653a117d53b6bb3e3edd53f07af11ff5d43/src/Standard/ForeignKeyTrait.php#L105-L118 |
bariew/yii2-doctest-extension | MethodParser.php | MethodParser.processComment | protected function processComment()
{
$comment=strtr(trim(preg_replace('/^\s*\**( |\t)?/m','',trim($this->getDocComment(),'/'))),"\r",'');
if(preg_match('/^\s*@\w+/m',$comment, $matches, PREG_OFFSET_CAPTURE)){
$meta=substr($comment,$matches[0][1]);
$this->processTags($meta);
}
} | php | protected function processComment()
{
$comment=strtr(trim(preg_replace('/^\s*\**( |\t)?/m','',trim($this->getDocComment(),'/'))),"\r",'');
if(preg_match('/^\s*@\w+/m',$comment, $matches, PREG_OFFSET_CAPTURE)){
$meta=substr($comment,$matches[0][1]);
$this->processTags($meta);
}
} | gets tags lines from docblock
@author Qiang Xue <[email protected]> | https://github.com/bariew/yii2-doctest-extension/blob/526e0281f055dbd55ad5fbcb2a3104164a056e0b/MethodParser.php#L23-L30 |
bariew/yii2-doctest-extension | MethodParser.php | MethodParser.processTags | protected function processTags($comment)
{
$tags = preg_split('/^\s*@/m',$comment,-1,PREG_SPLIT_NO_EMPTY);
foreach($tags as $tag){
$segs = preg_split('/\s+/',trim($tag),2);
$tagName= $segs[0];
$param = isset($segs[1]) ? trim($segs[1]) : '';
$this->tags[$tagName][] = $param;
}
} | php | protected function processTags($comment)
{
$tags = preg_split('/^\s*@/m',$comment,-1,PREG_SPLIT_NO_EMPTY);
foreach($tags as $tag){
$segs = preg_split('/\s+/',trim($tag),2);
$tagName= $segs[0];
$param = isset($segs[1]) ? trim($segs[1]) : '';
$this->tags[$tagName][] = $param;
}
} | extracts tags array from docblock
@param string $comment docblock
@author Qiang Xue <[email protected]> | https://github.com/bariew/yii2-doctest-extension/blob/526e0281f055dbd55ad5fbcb2a3104164a056e0b/MethodParser.php#L36-L45 |
gbprod/doctrine-specification | src/DoctrineSpecification/Registry.php | Registry.getFactory | public function getFactory(Specification $spec): Factory
{
if(!isset($this->factories[get_class($spec)])) {
throw new \OutOfRangeException(sprintf(
'Factory for Specification "%s" not registred',
get_class($spec)
));
}
return $this->factories[get_class($spec)];
} | php | public function getFactory(Specification $spec): Factory
{
if(!isset($this->factories[get_class($spec)])) {
throw new \OutOfRangeException(sprintf(
'Factory for Specification "%s" not registred',
get_class($spec)
));
}
return $this->factories[get_class($spec)];
} | Get registred factory for Specification
@param Specification $spec
@return Factory
@throw OutOfRangeException if Factory not found | https://github.com/gbprod/doctrine-specification/blob/348e8ec31547f4949a193d21b3a1d5cdb48b23cb/src/DoctrineSpecification/Registry.php#L42-L52 |
carno-php/nsq | src/Chips/TMCommands.php | TMCommands.retry | public function retry(int $delayed = 0) : void
{
$this->link->req($this->id(), $delayed);
} | php | public function retry(int $delayed = 0) : void
{
$this->link->req($this->id(), $delayed);
} | delayed in milliseconds
@param int $delayed | https://github.com/carno-php/nsq/blob/cc4f1278556ff530bbe2e03345bdeb54fef1275a/src/Chips/TMCommands.php#L41-L44 |
bruno-barros/w.eloquent-framework | src/weloquent/Plugins/Blade/blade.php | BladePlugin.parse | public function parse($template)
{
$viewsFromConfig = $this->app['config']->get('view.paths');
$views = array_merge((array)$viewsFromConfig, (array)$this->paths['theme']);
$cache = $this->paths['storage'] . '/views';
$blade = new BladeAdapter($views, $cache);
if (!$blade->getCompiler()->isExpired($template))
{
return $blade->getCompiler()->getCompiledPath($template);
}
$blade->getCompiler()->compile($template);
return $blade->getCompiler()->getCompiledPath($template);
} | php | public function parse($template)
{
$viewsFromConfig = $this->app['config']->get('view.paths');
$views = array_merge((array)$viewsFromConfig, (array)$this->paths['theme']);
$cache = $this->paths['storage'] . '/views';
$blade = new BladeAdapter($views, $cache);
if (!$blade->getCompiler()->isExpired($template))
{
return $blade->getCompiler()->getCompiledPath($template);
}
$blade->getCompiler()->compile($template);
return $blade->getCompiler()->getCompiledPath($template);
} | Handle the compilation of the templates
@param $template | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Plugins/Blade/blade.php#L103-L122 |
liufee/cms-core | backend/actions/CreateAction.php | CreateAction.run | public function run()
{
/* @var $model yii\db\ActiveRecord */
$model = new $this->modelClass;
$model->setScenario( $this->scenario );
if (yii::$app->getRequest()->getIsPost()) {
if ($model->load(yii::$app->getRequest()->post()) && $model->save()) {
yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
return $this->controller->redirect(['index']);
} else {
$errors = $model->getErrors();
$err = '';
foreach ($errors as $v) {
$err .= $v[0] . '<br>';
}
Yii::$app->getSession()->setFlash('error', $err);
}
}
$model->loadDefaultValues();
$data = array_merge(['model' => $model], $this->data);
return $this->controller->render('create', $data);
} | php | public function run()
{
/* @var $model yii\db\ActiveRecord */
$model = new $this->modelClass;
$model->setScenario( $this->scenario );
if (yii::$app->getRequest()->getIsPost()) {
if ($model->load(yii::$app->getRequest()->post()) && $model->save()) {
yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
return $this->controller->redirect(['index']);
} else {
$errors = $model->getErrors();
$err = '';
foreach ($errors as $v) {
$err .= $v[0] . '<br>';
}
Yii::$app->getSession()->setFlash('error', $err);
}
}
$model->loadDefaultValues();
$data = array_merge(['model' => $model], $this->data);
return $this->controller->render('create', $data);
} | create创建页
@return string|\yii\web\Response | https://github.com/liufee/cms-core/blob/440ee229e3b722d6088c57926d612b5f891b370d/backend/actions/CreateAction.php#L28-L49 |
Anahkiasen/php-configuration | src/TreeBuilder/ClosureNode.php | ClosureNode.validateType | protected function validateType($value)
{
if (!$value instanceof Closure && $value !== null) {
$exception = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected closure, but got %s.',
$this->getPath(),
gettype($value)
));
if ($hint = $this->getInfo()) {
$exception->addHint($hint);
}
$exception->setPath($this->getPath());
throw $exception;
}
} | php | protected function validateType($value)
{
if (!$value instanceof Closure && $value !== null) {
$exception = new InvalidTypeException(sprintf(
'Invalid type for path "%s". Expected closure, but got %s.',
$this->getPath(),
gettype($value)
));
if ($hint = $this->getInfo()) {
$exception->addHint($hint);
}
$exception->setPath($this->getPath());
throw $exception;
}
} | Validates the type of a Node.
@param mixed $value The value to validate
@throws InvalidTypeException when the value is invalid | https://github.com/Anahkiasen/php-configuration/blob/f67f1e045f3e2e3dc8bd88c66caf960095e69d97/src/TreeBuilder/ClosureNode.php#L27-L44 |
rackberg/para | src/Service/Strategy/DisplayCombinedOutputStrategy.php | DisplayCombinedOutputStrategy.execute | public function execute(string $cmd, array $projects, BufferedOutputInterface $output)
{
// For each project start an asynchronous process.
/** @var \Para\Entity\Project $project */
foreach ($projects as $project) {
$process = $this->createProcess($cmd, $project->getPath());
// Dispatch an event to be able to easily configure a process when needed.
$event = new PostProcessCreationEvent($process, $project);
$this->dispatcher->dispatch(
PostProcessCreationEvent::NAME,
$event
);
$this->addProcessInfo($process, $project);
}
$this->handleProcesses($output);
} | php | public function execute(string $cmd, array $projects, BufferedOutputInterface $output)
{
// For each project start an asynchronous process.
/** @var \Para\Entity\Project $project */
foreach ($projects as $project) {
$process = $this->createProcess($cmd, $project->getPath());
// Dispatch an event to be able to easily configure a process when needed.
$event = new PostProcessCreationEvent($process, $project);
$this->dispatcher->dispatch(
PostProcessCreationEvent::NAME,
$event
);
$this->addProcessInfo($process, $project);
}
$this->handleProcesses($output);
} | {@inheritdoc} | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Service/Strategy/DisplayCombinedOutputStrategy.php#L52-L70 |
rackberg/para | src/Service/Strategy/DisplayCombinedOutputStrategy.php | DisplayCombinedOutputStrategy.addProcessInfo | private function addProcessInfo(Process $process, Project $project)
{
$this->processes[$project->getName()] = [
'process' => $process,
'project' => $project,
];
} | php | private function addProcessInfo(Process $process, Project $project)
{
$this->processes[$project->getName()] = [
'process' => $process,
'project' => $project,
];
} | Adds the process and project info.
@param \Symfony\Component\Process\Process $process
@param \Para\Entity\Project $project | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Service/Strategy/DisplayCombinedOutputStrategy.php#L78-L84 |
rackberg/para | src/Service/Strategy/DisplayCombinedOutputStrategy.php | DisplayCombinedOutputStrategy.workaroundForSingleChar | private function workaroundForSingleChar(
string &$incrementalOutput,
Project $project
) {
// Check if there is a temporarily stored char.
if (!empty($this->tmpChar[$project->getName()]) && !empty($incrementalOutput)) {
// Add the char directly at the beginning of the current
// incremental output value.
$incrementalOutput = $this->tmpChar[$project->getName()] . $incrementalOutput;
// Clear the temporarily stored char.
$this->tmpChar[$project->getName()] = '';
}
// If there is a single char store it temporarily.
if (strlen($incrementalOutput) == 1) {
$this->tmpChar[$project->getName()] = $incrementalOutput;
// Clear the current incremental output value so that nothing will be written to the console.
$incrementalOutput = '';
}
} | php | private function workaroundForSingleChar(
string &$incrementalOutput,
Project $project
) {
// Check if there is a temporarily stored char.
if (!empty($this->tmpChar[$project->getName()]) && !empty($incrementalOutput)) {
// Add the char directly at the beginning of the current
// incremental output value.
$incrementalOutput = $this->tmpChar[$project->getName()] . $incrementalOutput;
// Clear the temporarily stored char.
$this->tmpChar[$project->getName()] = '';
}
// If there is a single char store it temporarily.
if (strlen($incrementalOutput) == 1) {
$this->tmpChar[$project->getName()] = $incrementalOutput;
// Clear the current incremental output value so that nothing will be written to the console.
$incrementalOutput = '';
}
} | Workaround for single char.
Sometimes it happens that only one char has been returned by $process->getIncrementalOutput()
even if there are more chars that could also be returned.
In this case we need to create a workaround, that temporarily stores
the single char returned to output it in front of the next
incremental output value.
@param string $incrementalOutput
@param Project $project | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Service/Strategy/DisplayCombinedOutputStrategy.php#L118-L136 |
rackberg/para | src/Service/Strategy/DisplayCombinedOutputStrategy.php | DisplayCombinedOutputStrategy.handleProcessOutput | protected function handleProcessOutput(
array $processInfo,
BufferedOutputInterface $output,
callable $processTerminatedCallback
) {
// Get the process.
/** @var Process $process */
$process = $processInfo['process'];
// Get the project.
/** @var Project $project */
$project = $processInfo['project'];
// Start the process if not already started.
if (!$process->isStarted()) {
$process->start();
}
// Get the last output from the process.
$incrementalOutput = $this->getIncrementalProcessOutput($process);
$this->workaroundForSingleChar(
$incrementalOutput,
$project
);
// Show the output.
if ($incrementalOutput != '') {
// Dispatch an event.
$this->dispatcher->dispatch(
IncrementalOutputReceivedEvent::NAME,
new IncrementalOutputReceivedEvent(
$incrementalOutput,
$project,
$process
)
);
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) {
if ($project->getForegroundColor() <= 0) {
$output->write(
sprintf(
'%s:' . "\t" . '%s',
$project->getName(),
$incrementalOutput
)
);
} else {
if ($this->writtenToBuffer) {
$output->write("\n");
}
$projectName = sprintf(
"\033[38;5;%dm%s:\033[0m",
$project->getForegroundColor(),
$project->getName()
);
if (!empty($project->getBackgroundColor())) {
$projectName = sprintf(
"\033[38;5;%dm%s:\033[0m",
$project->getBackgroundColor(),
$project->getName()
);
$projectOutput = sprintf(
"\t\033[38;5;%dm\033[48;5;%dm%s\033[0m",
$project->getForegroundColor(),
$project->getBackgroundColor(),
$incrementalOutput
);
} else {
$projectOutput = sprintf(
"\t%s",
$incrementalOutput
);
}
$output->write(
sprintf(
'%s%s',
$projectName,
$projectOutput
)
);
$this->writtenToBuffer = true;
}
}
}
if ($process->isTerminated()) {
$processTerminatedCallback();
}
} | php | protected function handleProcessOutput(
array $processInfo,
BufferedOutputInterface $output,
callable $processTerminatedCallback
) {
// Get the process.
/** @var Process $process */
$process = $processInfo['process'];
// Get the project.
/** @var Project $project */
$project = $processInfo['project'];
// Start the process if not already started.
if (!$process->isStarted()) {
$process->start();
}
// Get the last output from the process.
$incrementalOutput = $this->getIncrementalProcessOutput($process);
$this->workaroundForSingleChar(
$incrementalOutput,
$project
);
// Show the output.
if ($incrementalOutput != '') {
// Dispatch an event.
$this->dispatcher->dispatch(
IncrementalOutputReceivedEvent::NAME,
new IncrementalOutputReceivedEvent(
$incrementalOutput,
$project,
$process
)
);
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_NORMAL) {
if ($project->getForegroundColor() <= 0) {
$output->write(
sprintf(
'%s:' . "\t" . '%s',
$project->getName(),
$incrementalOutput
)
);
} else {
if ($this->writtenToBuffer) {
$output->write("\n");
}
$projectName = sprintf(
"\033[38;5;%dm%s:\033[0m",
$project->getForegroundColor(),
$project->getName()
);
if (!empty($project->getBackgroundColor())) {
$projectName = sprintf(
"\033[38;5;%dm%s:\033[0m",
$project->getBackgroundColor(),
$project->getName()
);
$projectOutput = sprintf(
"\t\033[38;5;%dm\033[48;5;%dm%s\033[0m",
$project->getForegroundColor(),
$project->getBackgroundColor(),
$incrementalOutput
);
} else {
$projectOutput = sprintf(
"\t%s",
$incrementalOutput
);
}
$output->write(
sprintf(
'%s%s',
$projectName,
$projectOutput
)
);
$this->writtenToBuffer = true;
}
}
}
if ($process->isTerminated()) {
$processTerminatedCallback();
}
} | Handles the output for a process.
@param array $processInfo The process information.
@param \Para\Service\Output\BufferedOutputInterface $output
@param callable $processTerminatedCallback | https://github.com/rackberg/para/blob/e0ef1356ed2979670eb7c670d88921406cade46e/src/Service/Strategy/DisplayCombinedOutputStrategy.php#L145-L239 |
ossbrownie/util | src/Brownie/Util/StorageList.php | StorageList.get | public function get($keyName, $defaultValue = null)
{
$this->initList();
$keyName = strtolower($keyName);
if (empty($this->list[$keyName])) {
return $defaultValue;
}
return $this->list[$keyName];
} | php | public function get($keyName, $defaultValue = null)
{
$this->initList();
$keyName = strtolower($keyName);
if (empty($this->list[$keyName])) {
return $defaultValue;
}
return $this->list[$keyName];
} | Gets value of by key name.
@param string $keyName Key name.
@param mixed $defaultValue Default value.
@return string|mixed | https://github.com/ossbrownie/util/blob/d60edd989f4c1e3caad243a75020f251a4b80283/src/Brownie/Util/StorageList.php#L71-L79 |
kiler129/TinyWs | src/UpgradeHandler.php | UpgradeHandler.onRequest | public function onRequest(StreamServerNodeInterface $client, HttpRequest $request)
{
$this->verifyUpgradeRequest($request);
$switchResponse = $this->generateSwitchResponse($client, $request);
$newClient = new WebSocketClient($this->clientsHandler, $client->socket, $this->logger);
$newClient->pushData($switchResponse);
$this->clientsHandler->onAfterUpgrade($newClient);
throw new ClientUpgradeException($client, $newClient);
} | php | public function onRequest(StreamServerNodeInterface $client, HttpRequest $request)
{
$this->verifyUpgradeRequest($request);
$switchResponse = $this->generateSwitchResponse($client, $request);
$newClient = new WebSocketClient($this->clientsHandler, $client->socket, $this->logger);
$newClient->pushData($switchResponse);
$this->clientsHandler->onAfterUpgrade($newClient);
throw new ClientUpgradeException($client, $newClient);
} | @param StreamServerNodeInterface $client HTTP client
@param HttpRequest $request HTTP request (which is expected to be valid WebSocket upgrade handshake)
@throws ClientUpgradeException Raised after client HTTP=>WS handshake is completed
@throws HttpException | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/UpgradeHandler.php#L55-L65 |
kiler129/TinyWs | src/UpgradeHandler.php | UpgradeHandler.generateSwitchResponse | private function generateSwitchResponse($client, $request)
{
$acceptHeader = sha1($request->getHeader("sec-websocket-key") . self::WEBSOCKET_GUID, true);
$switchParams = array(
"Upgrade" => "websocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Accept" => base64_encode($acceptHeader)
);
$response = new HttpResponse("", $switchParams, HttpCode::SWITCHING_PROTOCOLS);
$response = $this->clientsHandler->onUpgrade($client, $request, $response);
return $response;
} | php | private function generateSwitchResponse($client, $request)
{
$acceptHeader = sha1($request->getHeader("sec-websocket-key") . self::WEBSOCKET_GUID, true);
$switchParams = array(
"Upgrade" => "websocket",
"Connection" => "Upgrade",
"Sec-WebSocket-Accept" => base64_encode($acceptHeader)
);
$response = new HttpResponse("", $switchParams, HttpCode::SWITCHING_PROTOCOLS);
$response = $this->clientsHandler->onUpgrade($client, $request, $response);
return $response;
} | Generates WebSocket upgrade response & notifies clients handler
@param HttpClient|StreamServerNodeInterface $client WebSocketClient which should be upgraded to WebSocket
protocol
@param HttpRequest $request Original HTTP upgrade handshake sent by client
@return HttpResponse | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/UpgradeHandler.php#L76-L88 |
kiler129/TinyWs | src/UpgradeHandler.php | UpgradeHandler.verifyUpgradeRequest | private function verifyUpgradeRequest(HttpRequest $request)
{
$this->logger->debug("Attempting to switch protocols (checking preconditions per RFC)");
//That "ifology" is ugly, but I don't have better idea to perform checks
//Check request to conform with RFC 6455 [see page 16]
if ($request->getMethod() !== "GET") {
throw new HttpException("Cannot upgrade to WebSocket - invalid method", HttpCode::METHOD_NOT_ALLOWED);
}
if ($request->getProtocolVersion() != 1.1) {
throw new HttpException("Cannot upgrade to WebSockets - http version not supported",
HttpCode::VERSION_NOT_SUPPORTED);
}
//Intentionally skipped host & origin validation here
if (strtolower($request->getHeader("upgrade")) !== "websocket") {
throw new HttpException("Cannot upgrade to WebSockets - invalid upgrade header", HttpCode::BAD_REQUEST);
}
if (strpos(strtolower($request->getHeader("connection")), "upgrade") === false) {
throw new HttpException("Cannot upgrade to WebSockets - invalid connection header", HttpCode::BAD_REQUEST);
}
$wsNoonce = base64_decode($request->getHeader("sec-websocket-key"));
if (strlen($wsNoonce) !== 16) {
throw new HttpException("Cannot upgrade to WebSockets - invalid key", HttpCode::BAD_REQUEST);
}
if (strtolower($request->getHeader("sec-websocket-version")) != self::SUPPORTED_WEBSOCKET_VERSION) {
throw new HttpException("Cannot upgrade to WebSockets - version not supported", HttpCode::UPGRADE_REQUIRED,
array("Sec-WebSocket-Version" => self::SUPPORTED_WEBSOCKET_VERSION));
}
$this->logger->debug("RFC check OK");
} | php | private function verifyUpgradeRequest(HttpRequest $request)
{
$this->logger->debug("Attempting to switch protocols (checking preconditions per RFC)");
//That "ifology" is ugly, but I don't have better idea to perform checks
//Check request to conform with RFC 6455 [see page 16]
if ($request->getMethod() !== "GET") {
throw new HttpException("Cannot upgrade to WebSocket - invalid method", HttpCode::METHOD_NOT_ALLOWED);
}
if ($request->getProtocolVersion() != 1.1) {
throw new HttpException("Cannot upgrade to WebSockets - http version not supported",
HttpCode::VERSION_NOT_SUPPORTED);
}
//Intentionally skipped host & origin validation here
if (strtolower($request->getHeader("upgrade")) !== "websocket") {
throw new HttpException("Cannot upgrade to WebSockets - invalid upgrade header", HttpCode::BAD_REQUEST);
}
if (strpos(strtolower($request->getHeader("connection")), "upgrade") === false) {
throw new HttpException("Cannot upgrade to WebSockets - invalid connection header", HttpCode::BAD_REQUEST);
}
$wsNoonce = base64_decode($request->getHeader("sec-websocket-key"));
if (strlen($wsNoonce) !== 16) {
throw new HttpException("Cannot upgrade to WebSockets - invalid key", HttpCode::BAD_REQUEST);
}
if (strtolower($request->getHeader("sec-websocket-version")) != self::SUPPORTED_WEBSOCKET_VERSION) {
throw new HttpException("Cannot upgrade to WebSockets - version not supported", HttpCode::UPGRADE_REQUIRED,
array("Sec-WebSocket-Version" => self::SUPPORTED_WEBSOCKET_VERSION));
}
$this->logger->debug("RFC check OK");
} | Validates HTTP => WebSocket upgrade request
@param HttpRequest $request HTTP request, it's assumed upgrade request
@throws HttpException | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/UpgradeHandler.php#L97-L134 |
kiler129/TinyWs | src/UpgradeHandler.php | UpgradeHandler.populatePaths | private function populatePaths($paths)
{
if (!is_array($paths)) {
$paths = array($paths);
}
foreach ($paths as $path) {
if ($path[0] !== "/" && $path[0] !== "*") {
throw new InvalidArgumentException("Invalid handler path specified");
}
$this->handlerPaths[] = $path;
}
} | php | private function populatePaths($paths)
{
if (!is_array($paths)) {
$paths = array($paths);
}
foreach ($paths as $path) {
if ($path[0] !== "/" && $path[0] !== "*") {
throw new InvalidArgumentException("Invalid handler path specified");
}
$this->handlerPaths[] = $path;
}
} | Verifies & adds paths handled by this handler
It's private due to fact that for performance reasons CherryHttp will cache paths for each handler
@param string|string[] $paths One (or more) paths to be handled
@throws InvalidArgumentException Raised if any of paths is invalid | https://github.com/kiler129/TinyWs/blob/85f0335b87b3ec73ab47f5a5631eb86ba70b64a1/src/UpgradeHandler.php#L144-L157 |
weew/error-handler | src/Weew/ErrorHandler/ErrorConverter.php | ErrorConverter.createRecoverableErrorAndCallHandler | public function createRecoverableErrorAndCallHandler(
IErrorHandler $handler,
$number,
$string,
$file,
$line
) {
$error = new RecoverableError($number, $string, $file, $line);
return $handler->handleRecoverableError($error);
} | php | public function createRecoverableErrorAndCallHandler(
IErrorHandler $handler,
$number,
$string,
$file,
$line
) {
$error = new RecoverableError($number, $string, $file, $line);
return $handler->handleRecoverableError($error);
} | @param IErrorHandler $handler
@param $number
@param $string
@param $file
@param $line
@return bool|void | https://github.com/weew/error-handler/blob/883ac0b2cb6c83f177abdd61dfa33eaaa7b23043/src/Weew/ErrorHandler/ErrorConverter.php#L19-L29 |
weew/error-handler | src/Weew/ErrorHandler/ErrorConverter.php | ErrorConverter.extractFatalErrorAndCallHandler | public function extractFatalErrorAndCallHandler(IErrorHandler $handler) {
$error = $this->getLastError();
if ($error === null) {
return;
}
if ( ! ErrorType::isFatal(array_get($error, 'type'))) {
return;
}
$error = new FatalError(
array_get($error, 'type'),
array_get($error, 'message'),
array_get($error, 'file'),
array_get($error, 'line')
);
return $handler->handleFatalError($error);
} | php | public function extractFatalErrorAndCallHandler(IErrorHandler $handler) {
$error = $this->getLastError();
if ($error === null) {
return;
}
if ( ! ErrorType::isFatal(array_get($error, 'type'))) {
return;
}
$error = new FatalError(
array_get($error, 'type'),
array_get($error, 'message'),
array_get($error, 'file'),
array_get($error, 'line')
);
return $handler->handleFatalError($error);
} | @param IErrorHandler $handler
@return bool|void | https://github.com/weew/error-handler/blob/883ac0b2cb6c83f177abdd61dfa33eaaa7b23043/src/Weew/ErrorHandler/ErrorConverter.php#L36-L55 |
weew/error-handler | src/Weew/ErrorHandler/ErrorConverter.php | ErrorConverter.convertErrorToExceptionAndCallHandler | public function convertErrorToExceptionAndCallHandler(
IErrorHandler $handler,
IError $error
) {
return $handler->handleException(
ErrorType::createExceptionForError($error)
);
return true;
} | php | public function convertErrorToExceptionAndCallHandler(
IErrorHandler $handler,
IError $error
) {
return $handler->handleException(
ErrorType::createExceptionForError($error)
);
return true;
} | @param IErrorHandler $handler
@param IError $error
@return bool | https://github.com/weew/error-handler/blob/883ac0b2cb6c83f177abdd61dfa33eaaa7b23043/src/Weew/ErrorHandler/ErrorConverter.php#L63-L72 |
eloquent/endec | src/Base64/Base64MimeDecodeTransform.php | Base64MimeDecodeTransform.transform | public function transform($data, &$context, $isEnd = false)
{
if ($isEnd) {
list($output, $consumed, $error) = parent::transform(
preg_replace('{[^[:alnum:]+/=]+}', '', $data),
$context,
true
);
if (null !== $error) {
return array(
'',
0,
new InvalidEncodedDataException(
'base64mime',
$error->data()
),
);
}
return array($output, strlen($data), $error);
}
$chunks = preg_split(
'{([^[:alnum:]+/=]+)}',
$data,
-1,
PREG_SPLIT_OFFSET_CAPTURE
);
$numChunks = count($chunks);
$buffer = '';
$output = '';
$lastFullyConsumed = -1;
$consumed = 0;
for ($i = 0; $i < $numChunks; $i ++) {
$buffer .= $chunks[$i][0];
list($thisOutput, $consumed, $error) = parent::transform(
$buffer,
$context
);
$output .= $thisOutput;
if ($consumed === strlen($buffer)) {
$buffer = '';
$lastFullyConsumed = $i;
} else {
$buffer = substr($buffer, $consumed);
}
}
if ($lastFullyConsumed > -1) {
if ($lastFullyConsumed < $numChunks - 1) {
$consumed = $chunks[$lastFullyConsumed + 1][1];
} else {
$consumed = $chunks[$lastFullyConsumed][1] +
strlen($chunks[$lastFullyConsumed][0]);
}
}
return array($output, $consumed, null);
} | php | public function transform($data, &$context, $isEnd = false)
{
if ($isEnd) {
list($output, $consumed, $error) = parent::transform(
preg_replace('{[^[:alnum:]+/=]+}', '', $data),
$context,
true
);
if (null !== $error) {
return array(
'',
0,
new InvalidEncodedDataException(
'base64mime',
$error->data()
),
);
}
return array($output, strlen($data), $error);
}
$chunks = preg_split(
'{([^[:alnum:]+/=]+)}',
$data,
-1,
PREG_SPLIT_OFFSET_CAPTURE
);
$numChunks = count($chunks);
$buffer = '';
$output = '';
$lastFullyConsumed = -1;
$consumed = 0;
for ($i = 0; $i < $numChunks; $i ++) {
$buffer .= $chunks[$i][0];
list($thisOutput, $consumed, $error) = parent::transform(
$buffer,
$context
);
$output .= $thisOutput;
if ($consumed === strlen($buffer)) {
$buffer = '';
$lastFullyConsumed = $i;
} else {
$buffer = substr($buffer, $consumed);
}
}
if ($lastFullyConsumed > -1) {
if ($lastFullyConsumed < $numChunks - 1) {
$consumed = $chunks[$lastFullyConsumed + 1][1];
} else {
$consumed = $chunks[$lastFullyConsumed][1] +
strlen($chunks[$lastFullyConsumed][0]);
}
}
return array($output, $consumed, null);
} | Transform the supplied data.
This method may transform only part of the supplied data. The return
value includes information about how much data was actually consumed. The
transform can be forced to consume all data by passing a boolean true as
the $isEnd argument.
The $context argument will initially be null, but any value assigned to
this variable will persist until the stream transformation is complete.
It can be used as a place to store state, such as a buffer.
It is guaranteed that this method will be called with $isEnd = true once,
and only once, at the end of the stream transformation.
@param string $data The data to transform.
@param mixed &$context An arbitrary context value.
@param boolean $isEnd True if all supplied data must be transformed.
@return tuple<string,integer,mixed> A 3-tuple of the transformed data, the number of bytes consumed, and any resulting error. | https://github.com/eloquent/endec/blob/90043a26439739d6bac631cc57dab3ecf5cafdc3/src/Base64/Base64MimeDecodeTransform.php#L59-L121 |
pmdevelopment/tool-bundle | Framework/PMKernel.php | PMKernel.getBaseTmpDir | public function getBaseTmpDir()
{
$folders = explode(DIRECTORY_SEPARATOR, $this->getRootDir());
$foldersCount = count($folders);
/**
* Base Path
*/
$projectDir = '';
if (true === isset($folders[$foldersCount - 2])) {
$projectDir = $folders[$foldersCount - 2];
}
$tempDirPath = FileUtility::getUserBasedCachedDir(sprintf('%s-%s', $projectDir, $this->getEnvironment()));
FileUtility::mkdir($tempDirPath);
return $tempDirPath;
} | php | public function getBaseTmpDir()
{
$folders = explode(DIRECTORY_SEPARATOR, $this->getRootDir());
$foldersCount = count($folders);
/**
* Base Path
*/
$projectDir = '';
if (true === isset($folders[$foldersCount - 2])) {
$projectDir = $folders[$foldersCount - 2];
}
$tempDirPath = FileUtility::getUserBasedCachedDir(sprintf('%s-%s', $projectDir, $this->getEnvironment()));
FileUtility::mkdir($tempDirPath);
return $tempDirPath;
} | Get Base Tmp Dir
@return string | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/PMKernel.php#L97-L114 |
valu-digital/valuso | src/ValuSo/Service/MetaService.php | MetaService.describe | public function describe($serviceId)
{
$cache = $this->getCache();
$cacheId = self::CACHE_ID_PREFIX . $serviceId;
if ($cache && ($description = $this->getCache()->getItem($cacheId))) {
return $description;
}
$loader = $this->getServiceLoader();
$options = $loader->getServiceOptions($serviceId);
$service = $loader->getServicePluginManager()->get($serviceId, $options, true, false);
if (!$service) {
return null;
}
$description = [];
$description['id'] = $serviceId;
$description['name'] = $loader->getServiceName($serviceId);
if (!is_callable($service)) {
$specs = $this->getAnnotationBuilder()->getServiceSpecification($service);
$specs = $specs->getArrayCopy();
$description = array_merge($specs, $description);
}
$reflectionClass = new ReflectionClass($service);
// Convert associative 'operations' array into numeric array
if (isset($description['operations'])) {
$description['operations'] = $this->decorateOperations($reflectionClass, $description['operations']);
}
if ($cache) {
$cache->setItem($cacheId, $description);
}
return $description;
} | php | public function describe($serviceId)
{
$cache = $this->getCache();
$cacheId = self::CACHE_ID_PREFIX . $serviceId;
if ($cache && ($description = $this->getCache()->getItem($cacheId))) {
return $description;
}
$loader = $this->getServiceLoader();
$options = $loader->getServiceOptions($serviceId);
$service = $loader->getServicePluginManager()->get($serviceId, $options, true, false);
if (!$service) {
return null;
}
$description = [];
$description['id'] = $serviceId;
$description['name'] = $loader->getServiceName($serviceId);
if (!is_callable($service)) {
$specs = $this->getAnnotationBuilder()->getServiceSpecification($service);
$specs = $specs->getArrayCopy();
$description = array_merge($specs, $description);
}
$reflectionClass = new ReflectionClass($service);
// Convert associative 'operations' array into numeric array
if (isset($description['operations'])) {
$description['operations'] = $this->decorateOperations($reflectionClass, $description['operations']);
}
if ($cache) {
$cache->setItem($cacheId, $description);
}
return $description;
} | Retrieve service description
@param string $serviceId Service ID
@ValuService\Context({"cli", "http", "http-get"}) | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Service/MetaService.php#L52-L92 |
valu-digital/valuso | src/ValuSo/Service/MetaService.php | MetaService.describeMany | public function describeMany(array $services)
{
$descriptions = [];
foreach ($services as $serviceId) {
$descriptions[] = $this->describe($serviceId);
}
return $descriptions;
} | php | public function describeMany(array $services)
{
$descriptions = [];
foreach ($services as $serviceId) {
$descriptions[] = $this->describe($serviceId);
}
return $descriptions;
} | Retrieve description for all services matched by IDs in
array $services
@param array $services
@return array
@ValuService\Context({"cli", "http", "http-get"}) | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Service/MetaService.php#L103-L111 |
valu-digital/valuso | src/ValuSo/Service/MetaService.php | MetaService.getServiceBroker | public function getServiceBroker()
{
if (!$this->serviceBroker) {
$this->setServiceBroker($this->getServiceLocator()->get('ServiceBroker'));
}
return $this->serviceBroker;
} | php | public function getServiceBroker()
{
if (!$this->serviceBroker) {
$this->setServiceBroker($this->getServiceLocator()->get('ServiceBroker'));
}
return $this->serviceBroker;
} | Retrieve service broker instance
@return \ValuSo\Broker\ServiceBroker | https://github.com/valu-digital/valuso/blob/c96bed0f6bd21551822334fe6cfe913a7436dd17/src/ValuSo/Service/MetaService.php#L160-L167 |
bavix/laravel-helpers | src/Helpers/Corundum/Adapters/Adapter.php | Adapter.received | protected function received(Image $image, Slice $config, $minimal = true): Slice
{
$width = (int)$config->getRequired('width');
$height = (int)$config->getRequired('height');
$shiftWidth = 0;
$shiftHeight = 0;
$_width = $width;
$_height = $height;
if ($image->height() < $image->width())
{
$_height = $image->height() * $width / $image->width();
$shiftHeight = ($_height - $height) / 2;
}
else
{
$_width = $image->width() * $height / $image->height();
$shiftWidth = ($_width - $width) / 2;
}
if ($minimal ^ $_width > $width)
{
$_height = $_height * $width / $_width;
$_width = $width;
}
if ($minimal ^ $_height > $height)
{
$_width = $_width * $height / $_height;
$_height = $height;
}
return new Slice([
'config' => [
'width' => $width,
'height' => $height,
],
'received' => [
'width' => (int)$_width,
'height' => (int)$_height,
],
'shift' => [
'width' => (int)$shiftWidth,
'height' => (int)$shiftHeight,
]
]);
} | php | protected function received(Image $image, Slice $config, $minimal = true): Slice
{
$width = (int)$config->getRequired('width');
$height = (int)$config->getRequired('height');
$shiftWidth = 0;
$shiftHeight = 0;
$_width = $width;
$_height = $height;
if ($image->height() < $image->width())
{
$_height = $image->height() * $width / $image->width();
$shiftHeight = ($_height - $height) / 2;
}
else
{
$_width = $image->width() * $height / $image->height();
$shiftWidth = ($_width - $width) / 2;
}
if ($minimal ^ $_width > $width)
{
$_height = $_height * $width / $_width;
$_width = $width;
}
if ($minimal ^ $_height > $height)
{
$_width = $_width * $height / $_height;
$_height = $height;
}
return new Slice([
'config' => [
'width' => $width,
'height' => $height,
],
'received' => [
'width' => (int)$_width,
'height' => (int)$_height,
],
'shift' => [
'width' => (int)$shiftWidth,
'height' => (int)$shiftHeight,
]
]);
} | @param Image $image
@param Slice $config
@param bool $minimal
@return Slice | https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Adapters/Adapter.php#L47-L95 |
bavix/laravel-helpers | src/Helpers/Corundum/Adapters/Adapter.php | Adapter.handler | protected function handler(Image $image, Slice $slice, string $color = null): Image
{
$color = $color ?: 'rgba(0, 0, 0, 0)';
$image->resize(
$slice->getRequired('received.width'),
$slice->getRequired('received.height')
);
$image->resizeCanvas(
$width = $slice->getRequired('config.width'),
$height = $slice->getRequired('config.height'),
'center',
false,
$color
);
$fill = $this->corundum
->imageManager()
->canvas($width, $height, $color);
if ($this->corundum->driver() === 'gd')
{
bx_swap($fill, $image);
}
return $fill->fill(
$image,
$slice->getRequired('shift.width'),
$slice->getRequired('shift.height')
);
} | php | protected function handler(Image $image, Slice $slice, string $color = null): Image
{
$color = $color ?: 'rgba(0, 0, 0, 0)';
$image->resize(
$slice->getRequired('received.width'),
$slice->getRequired('received.height')
);
$image->resizeCanvas(
$width = $slice->getRequired('config.width'),
$height = $slice->getRequired('config.height'),
'center',
false,
$color
);
$fill = $this->corundum
->imageManager()
->canvas($width, $height, $color);
if ($this->corundum->driver() === 'gd')
{
bx_swap($fill, $image);
}
return $fill->fill(
$image,
$slice->getRequired('shift.width'),
$slice->getRequired('shift.height')
);
} | @param Image $image
@param Slice $slice
@param string $color
@return Image | https://github.com/bavix/laravel-helpers/blob/a713460d2647a58b3eb8279d2a2726034ca79876/src/Helpers/Corundum/Adapters/Adapter.php#L104-L135 |
pmdevelopment/tool-bundle | Services/PdfService.php | PdfService.get | public function get($html) {
$kernel_dir = $this->kerneldir;
require __DIR__ . "/../Resources/config/dompdf.php";
$this->pdf = new DOMPDF;
foreach ($this->options as $optionKey => $optionValue) {
$this->pdf->set_option($optionKey, $optionValue);
}
$this->pdf->load_html($html);
$this->pdf->set_paper("a4", 'portrait');
$this->pdf->render();
$response = new Response();
$response->setContent($this->pdf->output());
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/pdf');
return $response;
} | php | public function get($html) {
$kernel_dir = $this->kerneldir;
require __DIR__ . "/../Resources/config/dompdf.php";
$this->pdf = new DOMPDF;
foreach ($this->options as $optionKey => $optionValue) {
$this->pdf->set_option($optionKey, $optionValue);
}
$this->pdf->load_html($html);
$this->pdf->set_paper("a4", 'portrait');
$this->pdf->render();
$response = new Response();
$response->setContent($this->pdf->output());
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/pdf');
return $response;
} | Get PDF By HTML
@param string $html
@return Response | https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Services/PdfService.php#L55-L76 |
jasny/entity | src/Traits/SetTrait.php | SetTrait.set | public function set($key, $value = null)
{
i\type_check($key, ['array', 'string']);
if (func_num_args() === 1 && is_string($key)) {
throw new BadMethodCallException(sprintf(
"Too few arguments to method %s::%s(). If first argument is a string, a second argument is required",
__CLASS__,
__FUNCTION__
));
}
$input = func_num_args() === 1 ? (array)$key : [$key => $value];
/** @var Event\BeforeSet $event */
$event = $this->dispatchEvent(new Event\BeforeSet($this, $input));
$data = $event->getPayload();
object_set_properties($this, $data, $this instanceof DynamicEntity);
$this->dispatchEvent(new Event\AfterSet($this, $data));
return $this;
} | php | public function set($key, $value = null)
{
i\type_check($key, ['array', 'string']);
if (func_num_args() === 1 && is_string($key)) {
throw new BadMethodCallException(sprintf(
"Too few arguments to method %s::%s(). If first argument is a string, a second argument is required",
__CLASS__,
__FUNCTION__
));
}
$input = func_num_args() === 1 ? (array)$key : [$key => $value];
/** @var Event\BeforeSet $event */
$event = $this->dispatchEvent(new Event\BeforeSet($this, $input));
$data = $event->getPayload();
object_set_properties($this, $data, $this instanceof DynamicEntity);
$this->dispatchEvent(new Event\AfterSet($this, $data));
return $this;
} | Set a value or multiple values.
<code>
$entity->set('foo', 22);
$entity->set('bar', null);
$entity->set(['qux' => 100, 'clr' => 'red']);
</code>
@param string|array $key Property or set of values
@param mixed $value
@return $this | https://github.com/jasny/entity/blob/5af7c94645671a3257d6565ff1891ff61fdcf69b/src/Traits/SetTrait.php#L39-L62 |
znframework/package-hypertext | HtmlElementsTrait.php | HtmlElementsTrait.aria | public function aria(String $type, String $element)
{
$this->settings['attr']['aria-'.$type] = $element;
return $this;
} | php | public function aria(String $type, String $element)
{
$this->settings['attr']['aria-'.$type] = $element;
return $this;
} | Sets aria attribute
@param string $type
@param string $element
@return self | https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L22-L27 |
znframework/package-hypertext | HtmlElementsTrait.php | HtmlElementsTrait.data | public function data(String $type, String $element)
{
$this->settings['attr']['data-'.$type] = $element;
return $this;
} | php | public function data(String $type, String $element)
{
$this->settings['attr']['data-'.$type] = $element;
return $this;
} | Sets data attribute
@param string $type
@param string $element
@return self | https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L37-L42 |
znframework/package-hypertext | HtmlElementsTrait.php | HtmlElementsTrait.spry | public function spry(String $type, String $element)
{
$this->settings['attr']['spry-'.$type] = $element;
return $this;
} | php | public function spry(String $type, String $element)
{
$this->settings['attr']['spry-'.$type] = $element;
return $this;
} | Sets spry attribute
@param string $type
@param string $element
@return self | https://github.com/znframework/package-hypertext/blob/12bbc3bd47a2fae735f638a3e01cc82c1b9c9005/HtmlElementsTrait.php#L66-L71 |
bennybi/yii2-cza-base | models/statics/ResponseDatum.php | ResponseDatum.getSuccessDatum | public static function getSuccessDatum($meta = [], $data = null, $html = false) {
$defaultMeta = array(
'result' => OperationResult::SUCCESS,
'type' => OperationResult::getType(OperationResult::SUCCESS),
'time' => date('Y-m-d H:i:s'),
'message' => Yii::t('cza', 'Operation completed.')
);
if (isset($meta['message']) && is_array($meta['message'])) {
$meta['message'] = self::formatMsg($meta['message']);
}
$result = array(
'_data' => $data, '_meta' => array_merge($defaultMeta, $meta),
);
if ($html)
$result['_meta']['message'] = '<div class=\'alert-box done\'><i class=\'fa-check-circle\'></i> ' . $result['_meta']['message'] . '</div>';
return $result;
} | php | public static function getSuccessDatum($meta = [], $data = null, $html = false) {
$defaultMeta = array(
'result' => OperationResult::SUCCESS,
'type' => OperationResult::getType(OperationResult::SUCCESS),
'time' => date('Y-m-d H:i:s'),
'message' => Yii::t('cza', 'Operation completed.')
);
if (isset($meta['message']) && is_array($meta['message'])) {
$meta['message'] = self::formatMsg($meta['message']);
}
$result = array(
'_data' => $data, '_meta' => array_merge($defaultMeta, $meta),
);
if ($html)
$result['_meta']['message'] = '<div class=\'alert-box done\'><i class=\'fa-check-circle\'></i> ' . $result['_meta']['message'] . '</div>';
return $result;
} | standardize the datum format
@param array $data - return data fields
@param array $metaData - meta data
@return ['_data'=>[], '_meta'=[]] | https://github.com/bennybi/yii2-cza-base/blob/8257db8034bd948712fa469062921f210f0ba8da/models/statics/ResponseDatum.php#L39-L58 |
puntmig/comment-bundle | DependencyInjection/PuntmigCommentConfiguration.php | PuntmigCommentConfiguration.setupTree | protected function setupTree(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('repositories')
->prototype('array')
->children()
->scalarNode('secret')
->isRequired()
->end()
->scalarNode('endpoint')
->isRequired()
->end()
->booleanNode('test')
->defaultFalse();
} | php | protected function setupTree(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('repositories')
->prototype('array')
->children()
->scalarNode('secret')
->isRequired()
->end()
->scalarNode('endpoint')
->isRequired()
->end()
->booleanNode('test')
->defaultFalse();
} | Configure the root node.
@param ArrayNodeDefinition $rootNode Root node | https://github.com/puntmig/comment-bundle/blob/7a0a3bf556222a047503d56f78da8f1434e54d5e/DependencyInjection/PuntmigCommentConfiguration.php#L32-L47 |
buse974/Dal | src/Dal/Paginator/Paginator.php | Paginator.getItems | public function getItems()
{
$statement = (null !== $this->c && null !== $this->d) ? $this->getStatementDay() : $this->getStatementPagination();
$result = $statement->execute((is_array($this->select)) ? $this->select[1] : null);
$resultSet = clone $this->resultSetPrototype;
$this->result = $resultSet->initialize($result);
return $this->result;
} | php | public function getItems()
{
$statement = (null !== $this->c && null !== $this->d) ? $this->getStatementDay() : $this->getStatementPagination();
$result = $statement->execute((is_array($this->select)) ? $this->select[1] : null);
$resultSet = clone $this->resultSetPrototype;
$this->result = $resultSet->initialize($result);
return $this->result;
} | Returns an ResultSet of items for a page.
@return \Dal\Db\ResultSet\ResultSet | https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L204-L213 |
buse974/Dal | src/Dal/Paginator/Paginator.php | Paginator.getStatementDay | public function getStatementDay()
{
if (null === $this->n) {
$this->n = 1;
}
$date = new \DateTime($this->d, new \DateTimeZone('UTC'));
$date->sub(new \DateInterval(sprintf('P%dD', ($this->p * $this->n) - 1)));
$start_date = $date->format('Y-m-j');
$date->add(new \DateInterval(sprintf('P%dD', $this->n)));
$end_date = $date->format('Y-m-j');
if (is_array($this->select)) {
$query = sprintf('%s WHERE %s BETWEEN %s AND %s', $this->select[0], $this->c, $start_date, $end_date);
$adt = $this->sql->getAdapter();
$statement = $adt->query($query, $adt::QUERY_MODE_PREPARE);
} else {
$select = clone $this->select;
$select->where(new Between($this->c, $start_date, $end_date));
$statement = $this->sql->prepareStatementForSqlObject($select);
}
return $statement;
} | php | public function getStatementDay()
{
if (null === $this->n) {
$this->n = 1;
}
$date = new \DateTime($this->d, new \DateTimeZone('UTC'));
$date->sub(new \DateInterval(sprintf('P%dD', ($this->p * $this->n) - 1)));
$start_date = $date->format('Y-m-j');
$date->add(new \DateInterval(sprintf('P%dD', $this->n)));
$end_date = $date->format('Y-m-j');
if (is_array($this->select)) {
$query = sprintf('%s WHERE %s BETWEEN %s AND %s', $this->select[0], $this->c, $start_date, $end_date);
$adt = $this->sql->getAdapter();
$statement = $adt->query($query, $adt::QUERY_MODE_PREPARE);
} else {
$select = clone $this->select;
$select->where(new Between($this->c, $start_date, $end_date));
$statement = $this->sql->prepareStatementForSqlObject($select);
}
return $statement;
} | Get Statement Pagination By Date
@return \Zend\Db\Adapter\Driver\StatementInterface | https://github.com/buse974/Dal/blob/faeac9e260c5e675bc7ed1fcea77c7ba251bf8ab/src/Dal/Paginator/Paginator.php#L220-L246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.